notations 1.0.6 → 1.0.7

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 (43) hide show
  1. package/dist/NotationView.css +15 -0
  2. package/dist/NotationView.css.map +1 -1
  3. package/dist/NotationView.min.css +1 -1
  4. package/dist/NotationView.min.css.map +1 -1
  5. package/dist/notations.umd.js +142 -26
  6. package/dist/notations.umd.min.js +2 -2
  7. package/dist/notations.umd.min.js.map +1 -1
  8. package/lib/cjs/beats.js +1 -1
  9. package/lib/cjs/beats.js.map +1 -1
  10. package/lib/cjs/carnatic/NotationView.d.ts +1 -0
  11. package/lib/cjs/carnatic/NotationView.js +10 -0
  12. package/lib/cjs/carnatic/NotationView.js.map +1 -1
  13. package/lib/cjs/carnatic/atomviews.d.ts +4 -1
  14. package/lib/cjs/carnatic/atomviews.js +18 -2
  15. package/lib/cjs/carnatic/atomviews.js.map +1 -1
  16. package/lib/cjs/carnatic/embelishments.d.ts +18 -1
  17. package/lib/cjs/carnatic/embelishments.js +87 -1
  18. package/lib/cjs/carnatic/embelishments.js.map +1 -1
  19. package/lib/cjs/core.d.ts +3 -3
  20. package/lib/cjs/core.js +17 -17
  21. package/lib/cjs/core.js.map +1 -1
  22. package/lib/cjs/shapes.d.ts +2 -1
  23. package/lib/cjs/shapes.js +11 -6
  24. package/lib/cjs/shapes.js.map +1 -1
  25. package/lib/esm/beats.js +1 -1
  26. package/lib/esm/beats.js.map +1 -1
  27. package/lib/esm/carnatic/NotationView.d.ts +1 -0
  28. package/lib/esm/carnatic/NotationView.js +10 -0
  29. package/lib/esm/carnatic/NotationView.js.map +1 -1
  30. package/lib/esm/carnatic/atomviews.d.ts +4 -1
  31. package/lib/esm/carnatic/atomviews.js +19 -3
  32. package/lib/esm/carnatic/atomviews.js.map +1 -1
  33. package/lib/esm/carnatic/embelishments.d.ts +18 -1
  34. package/lib/esm/carnatic/embelishments.js +85 -0
  35. package/lib/esm/carnatic/embelishments.js.map +1 -1
  36. package/lib/esm/core.d.ts +3 -3
  37. package/lib/esm/core.js +17 -17
  38. package/lib/esm/core.js.map +1 -1
  39. package/lib/esm/shapes.d.ts +2 -1
  40. package/lib/esm/shapes.js +11 -6
  41. package/lib/esm/shapes.js.map +1 -1
  42. package/package.json +1 -1
  43. package/styles/NotationView.scss +15 -0
@@ -1,4 +1,4 @@
1
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Notations=e():t.Notations=e()}(this,()=>(()=>{"use strict";var t,e,s,n={d:(t,e)=>{for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},r={};n.d(r,{aq:()=>_,YJ:()=>k});class i{constructor(t=null){if(this.TYPE="Entity",this.uuid=i.counter++,this._parent=null,this._eventsEnabled=!1,(t=t||{}).metadata)throw new Error("See where metadata is being passed")}enableEvents(){return this._eventsEnabled=!0,this}disableEvents(){return this._eventsEnabled=!1,this}get eventsEnabled(){return this._eventsEnabled}get parent(){return this._parent}setParent(t){this._parent=t}debugValue(){return{type:this.TYPE}}toString(){return`Entity(id = ${this.uuid})`}equals(t,e=!1){return this.TYPE==t.TYPE}clone(){const t=this.newInstance();return this.copyTo(t),t}copyTo(t){}newInstance(){return new this.constructor}}i.counter=0;class o extends i{constructor(){super(...arguments),this.TYPE="TimedEntity"}equals(t){return super.equals(t)&&this.duration.equals(t.duration)}}function a(t,e){if(!t)throw new Error(e)}!function(t){t.ADD="add",t.INSERT="insert",t.REMOVE="remove",t.UPDATE="update"}(t||(t={})),function(t){t.ADD="add",t.REMOVE="remove"}(e||(e={})),function(t){t.ADD="add",t.REMOVE="remove"}(s||(s={}));const l=Math.pow(2,32);Math.pow(2,64);class h{constructor(t,e,s){this.uuid=h.counter++,this._spawnedFrom=null,this.sourceState=null,this.cancelled=!1,this.timeStamp=-1,this.children=[],this.name=t,this.source=e,this.payload=s}get spawnedFrom(){return this._spawnedFrom}setSpawnedFrom(t){this._spawnedFrom=t,this._rootEvent=null==t?this:t.rootEvent}spawn(t,e,s){const n=new h(t,e,s);return n.setSpawnedFrom(this),this.children.push(n),n}get rootEvent(){return this._rootEvent}}h.counter=0;class u{constructor(){this.stateData=null,this.id=u.counter++}get name(){return this.constructor.name}enter(t){this.stateData=t}handle(t){}}u.counter=0;class c{constructor(){this._eventHub=new d}get eventHub(){return this._eventHub}set eventHub(t){const e=this._eventHub;this._eventHub=t,this.eventHubChanged(e)}eventHubChanged(t){console.log("WARNING - EventHub Change Listener not implemented: ",this.constructor.name)}}class d{constructor(){this._handlers={},this._events=[],this._inBatchMode=!1}on(t,e){return this._addHandler(t,this._handlers,e)}removeOn(t,e){return this._removeHandler(t,this._handlers,e)}_ensurestrings(t){return"string"==typeof t&&(t=t.split(",")),t.map(function(t){return t.trim()})}_addHandler(t,e,s){return this._ensurestrings(t).forEach(function(t){e[t]=e[t]||[],e[t].push(s)}),this}_removeHandler(t,e,s){return this._ensurestrings(t).forEach(function(t){const n=e[t]||[];for(let t=0;t<n.length;t++)if(n[t]==s){n.splice(t,1);break}}),this}emit(t,e,s){const n=new h(t,e,s);return this._inBatchMode?(this._events.push(n),!0):this.dispatchEvent(n)}dispatchEvent(t){const e=this._handlers[t.name]||[];for(const s of e)if(s(t),t.cancelled)return!1;return!0}startBatchMode(){return this._inBatchMode||(this._inBatchMode=!0),this}cancelBatch(){this._inBatchMode=!1,this._events=[]}commitBatch(){this._inBatchMode=!1,this.emit(d.BATCH_EVENTS,this,this._events),this._events=[]}}d.BATCH_EVENTS="BatchEvents";class f{constructor(...t){this._firstChild=null,this._lastChild=null,this._size=0;for(const e of t)this.pushBack(e)}toJSON(){return Array.from(this.values())}forEach(t){let e=this._firstChild,s=0;for(;null!=e&&0!=t(e);)s++,e=e.nextSibling;return s}equals(t,e){if(this.size!=t.size)return!1;let s=this.first,n=t.first;for(;null!=s&&null!=n;s=s.nextSibling,n=n.nextSibling)if(!e(s,n))return!1;return null==s&&null==n}get isEmpty(){return 0==this._size}get size(){return this._size}get first(){return this._firstChild}get last(){return this._lastChild}*reversedValues(){let t=this._lastChild;for(;null!=t;)yield t,t=t.prevSibling}*values(){let t=this._firstChild;for(;null!=t;)yield t,t=t.nextSibling}add(t,e=null){if(null!=t.nextSibling||null!=t.prevSibling)throw new Error("New node already added to a list. Remove it first");if(t.nextSibling=t.prevSibling=null,this._size++,null==this._firstChild||null==this._lastChild)this._firstChild=this._lastChild=t;else if(null==e)t.prevSibling=this._lastChild,t.nextSibling=null,this._lastChild.nextSibling=t,this._lastChild=t;else if(e==this._firstChild)t.nextSibling=e,t.prevSibling=null,this._firstChild.prevSibling=t,this._firstChild=t;else{const s=e.prevSibling;t.nextSibling=e,e.prevSibling=t,t.prevSibling=s,null!=s&&(s.nextSibling=t)}return this}pushFront(t){return this.add(t,this._firstChild)}pushBack(t){return this.add(t)}remove(t){const e=t.nextSibling,s=t.prevSibling;return null==e?(this._lastChild=s,null==s&&(this._firstChild=null)):e.prevSibling=s,null==s?(this._firstChild=e,null==e&&(this._lastChild=null)):s.nextSibling=e,this._size--,t.prevSibling=t.nextSibling=null,this}popBack(){if(null==this._lastChild)throw new Error("No children");const t=this._lastChild;return this.remove(t),t}popFront(){if(null==this._firstChild)throw new Error("No children");const t=this._firstChild;return this.remove(t),t}}class g{}function m(t,e){for(t=Math.abs(t),e=Math.abs(e);e>0;){const s=e;e=t%e,t=s}return t}g.IS_EXPLORER=()=>navigator&&navigator.userAgent.indexOf("MSIE")>-1,g.IS_FIREFOX=()=>navigator&&navigator.userAgent.indexOf("Firefox")>-1,g.IS_OPERA=()=>navigator&&navigator.userAgent.toLowerCase().indexOf("op")>-1,g.UAHasChrome=()=>navigator&&navigator.userAgent.indexOf("Chrome")>-1,g.UAHasSafari=()=>navigator&&navigator.userAgent.indexOf("Safari")>-1,g.IS_SAFARI=()=>navigator&&g.UAHasSafari()&&(!g.UAHasChrome()||!g.UAHasSafari()),g.IS_CHROME=()=>navigator&&g.UAHasChrome()&&(!g.UAHasChrome()||!g.IS_OPERA());class p{constructor(t=0,e=1,s=!1){if(isNaN(t)||isNaN(e))throw new Error(`Invalid numerator(${t}) or denminator(${e})`);if(s){const s=m(t,e);t/=s,e/=s}this.num=t,this.den=e}static parse(t,e=!1){const s=t.trim().split("/").map(t=>t.trim());let n=1,r=1;if(1==s.length)n=parseInt(s[0]);else{if(2!=s.length)throw new Error("Invalid fraction string: "+t);s[0].length>0&&(n=parseInt(s[0])),s[1].length>0&&(r=parseInt(s[1]))}if(isNaN(n)||isNaN(r))throw new Error("Invalid fraction string: "+t);return new p(n,r,e)}get isWhole(){return this.num%this.den==0}get isZero(){return 0==this.num}get isInfinity(){return 0==this.den}get isOne(){return this.num==this.den}get ceil(){return this.num%this.den==0?this.num/this.den:1+Math.floor(this.num/this.den)}get floor(){return this.num%this.den==0?this.num/this.den:Math.floor(this.num/this.den)}plus(t,e=!1){return new p(this.num*t.den+this.den*t.num,this.den*t.den,e)}plusNum(t,e=!1){return new p(this.num+this.den*t,this.den,e)}minus(t,e=!1){return new p(this.num*t.den-this.den*t.num,this.den*t.den,e)}minusNum(t,e=!1){return new p(this.num-this.den*t,this.den,e)}times(t,e=!1){return new p(this.num*t.num,this.den*t.den,e)}timesNum(t,e=!1){return new p(this.num*t,this.den,e)}divby(t,e=!1){return new p(this.num*t.den,this.den*t.num,e)}divbyNum(t,e=!1){return new p(this.num,this.den*t,e)}numDivby(t,e=!1){return new p(this.den*t,this.num,e)}mod(t){const e=this.divby(t),s=Math.floor(e.num/e.den);return this.minus(t.timesNum(s))}modNum(t){const e=this.divbyNum(t),s=Math.floor(e.num/e.den);return this.minusNum(t*s)}get inverse(){return new p(this.den,this.num)}get factorized(){const t=m(this.num,this.den);return new p(this.num/t,this.den/t)}equals(t){return this.num*t.den==this.den*t.num}equalsNum(t){return this.num==this.den*t}cmp(t){return this.num*t.den-this.den*t.num}cmpNum(t){return this.num-this.den*t}isLT(t){return this.cmp(t)<0}isLTE(t){return this.cmp(t)<=0}isLTNum(t){return this.cmpNum(t)<0}isLTENum(t){return this.cmpNum(t)<=0}isGT(t){return this.cmp(t)>0}isGTE(t){return this.cmp(t)>=0}isGTNum(t){return this.cmpNum(t)>0}isGTENum(t){return this.cmpNum(t)>=0}toString(){return this.num+"/"+this.den}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}}p.ZERO=new p,p.ONE=new p(1,1),p.INFINITY=new p(1,0);const b=(t=0,e=1,s=!1)=>new p(t,e,s),y=p.ZERO;p.ONE;class S{constructor(t,e=0,s=0,n=0){this.cycle=t,this.barIndex=e,this.beatIndex=s,this.instance=n}get next(){const t=this.cycle.bars[this.barIndex],e=[[this.barIndex,this.beatIndex,this.instance],t.beatLengths[this.beatIndex]];return this.instance++,(!t.beatCounts[this.beatIndex]||this.instance>=t.beatCounts[this.beatIndex])&&(this.instance=0,this.beatIndex++,this.beatIndex>=t.beatLengths.length&&(this.beatIndex=0,this.barIndex++,this.barIndex>=this.cycle.bars.length&&(this.barIndex=0))),e}get prev(){const t=this.cycle.bars[this.barIndex],e=[[this.barIndex,this.beatIndex,this.instance],t.beatLengths[this.beatIndex]];return this.instance--,this.instance<0&&(this.beatIndex--,this.beatIndex<0&&(this.barIndex--,this.barIndex<0&&(this.barIndex=this.cycle.bars.length-1),this.beatIndex=this.cycle.bars[this.barIndex].beatCount-1),this.instance=(this.cycle.bars[this.barIndex].beatCounts[this.beatIndex]||1)-1),e}}class E extends o{constructor(t=null){super(t=t||{}),this.TYPE="Bar",this.beatLengths=[],this.beatCounts=[],this.name=t.name||"";for(const e of t.beatLengths||[])"number"==typeof e?this.beatLengths.push(b(e)):this.beatLengths.push(e);for(const e of t.beatCounts||[])this.beatCounts.push(e);for(;this.beatCounts.length<this.beatLengths.length;)this.beatCounts.push(1)}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{name,beatLengths:this.beatLengths})}equals(t){if(!super.equals(t))return!1;if(this.beatLengths.length!=t.beatLengths.length)return!1;if(this.beatCounts.length!=t.beatCounts.length)return!1;for(let e=0;e<this.beatLengths.length;e++)if(!this.beatLengths[e].equals(t.beatLengths[e]))return!1;for(let e=0;e<this.beatCounts.length;e++)if(this.beatCounts[e]!=t.beatCounts[e])return!1;return!0}copyTo(t){super.copyTo(t),t.name=this.name,t.beatLengths=[...this.beatLengths],t.beatCounts=[...this.beatCounts]}instanceCount(t){return t>this.beatCounts.length?1:this.beatCounts[t]}get beatCount(){return this.beatLengths.length}get totalBeatCount(){let t=0;for(let e=0;e<this.beatLengths.length;e++)t+=this.beatCounts[e]||1;return t}get duration(){let t=y;for(let e=0;e<this.beatLengths.length;e++)t=t.plus(this.beatLengths[e].timesNum(this.beatCounts[e]||1));return t}}class C extends o{constructor(t=null){super(t=t||{}),this.TYPE="Cycle",this.name=t.name||"",this.bars=t.bars||[]}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{name,bars:this.bars.map(t=>t.debugValue())})}children(){return this.bars}equals(t){if(!super.equals(t))return!1;if(this.bars.length!=t.bars.length)return!1;for(let e=0;e<this.bars.length;e++)if(!this.bars[e].equals(t.bars[e]))return!1;return!0}getAtIndex(t){let e=0;for(;t<0;)t+=this.totalBeatCount,e--;t>=this.totalBeatCount&&(e=Math.floor(t/this.totalBeatCount)),t%=this.totalBeatCount;let s=y;for(let n=0;n<this.bars.length;n++){const r=this.bars[n];if(t>=r.totalBeatCount)t-=r.totalBeatCount,s=s.plus(r.duration);else for(let i=0;i<r.beatCount;i++){const o=r.beatLengths[i],a=r.beatCounts[i]||1;if(!(t>=a)){const r=t;return[e,[n,i,r],s.plus(o.timesNum(r))]}t-=a,s=s.plus(o.timesNum(a))}}throw new Error("Should not be here!")}getPosition(t){const e=this.duration;let s=0;if(t.isLT(y))for(;t.isLT(y);)s--,t=t.plus(e);else if(t.isGTE(e)){const n=t.mod(e);a((t=t.minus(n).divby(e)).isWhole),s=t.floor,t=n}let n=0;for(let e=0;e<this.bars.length;e++){const r=this.bars[e],i=r.duration;if(t.isGTE(i))t=t.minus(i);else for(let i=0;i<r.beatCount;i++){const o=r.beatLengths[i],a=r.beatCounts[i]||1;for(let r=0;r<a;r++,n++){if(!t.isGTE(o))return[s,[e,i,r],t,n];t=t.minus(o)}}n+=r.totalBeatCount}throw new Error("Should not be here!")}*iterateBeats(t=0,e=0,s=0){let n=t,r=e,i=s;for(;;){const t=this.bars[n];yield[[n,r,i],t.beatLengths[r]],i++,(!t.beatCounts[r]||i>=t.beatCounts[r])&&(i=0,r++,r>=t.beatLengths.length&&(r=0,n++,n>=this.bars.length&&(n=0)))}}copyTo(t){super.copyTo(t),t.name=this.name,t.bars=this.bars.map(t=>t.clone())}get beatCount(){let t=0;for(const e of this.bars)t+=e.beatCount;return t}get totalBeatCount(){let t=0;for(const e of this.bars)t+=e.totalBeatCount;return t}get duration(){return this.bars.reduce((t,e)=>t.plus(e.duration),y)}}C.DEFAULT=new C({name:"Adi Thalam",bars:[new E({name:"Laghu",beatLengths:[1,1,1,1]}),new E({name:"Dhrutam",beatLengths:[1,1]}),new E({name:"Dhrutam",beatLengths:[1,1]})]});const w=p.ZERO,v=p.ONE;var _,x;(x=_||(_={})).NOTE="Note",x.LITERAL="Literal",x.SYLLABLE="Syllable",x.SPACE="Space",x.GROUP="Group",x.LABEL="Label",x.REST="Rest",x.MARKER="Marker";class N extends o{constructor(t=v){super(),this.TYPE="Atom",this.nextSibling=null,this.prevSibling=null,this.parentGroup=null,this.isContinuation=!1,this._duration=t||v}debugValue(){const t=super.debugValue();return this.duration.isOne||(t.duration=this.duration.factorized.toString()),this.isContinuation&&(t.isContinuation=!0),(this.markersBefore||[]).length>0&&(t.mbef=this.markersBefore.map(t=>t.debugValue())),(this.markersAfter||[]).length>0&&(t.maft=this.markersAfter.map(t=>t.debugValue())),t}copyTo(t){super.copyTo(t),t._duration=new p(this.duration.num,this.duration.den)}get duration(){return this._duration}set duration(t){this._duration=t}}class A extends N{constructor(){super(...arguments),this.TYPE="LeafAtom",this.beforeRest=!1}splitAt(t){if(this.duration.cmp(t)>0){const e=this.createSpilloverSpace(this.duration.minus(t));return e.isContinuation=!0,this.duration=t,e}return null}createSpilloverSpace(t){return new I(t)}debugValue(){return this.beforeRest?Object.assign(Object.assign({},super.debugValue()),{beforeRest:!0}):super.debugValue()}}class T extends i{constructor(t,e=!0){super(),this.text=t,this.isBefore=e,this.TYPE="Marker"}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{text:this.text,before:this.isBefore})}toString(){return`Marker(${this.text}-${this.isBefore})`}}class I extends A{constructor(t=v,e=!1){super(t),this.TYPE="Space",this.isSilent=!1,this.isSilent=e}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{isSilent:this.isSilent})}toString(){return`Space(${this.duration}-${this.isSilent})`}copyTo(t){super.copyTo(t),t.isSilent=this.isSilent}equals(t){return super.equals(t)&&this.isSilent==t.isSilent}createSpilloverSpace(t){const e=super.createSpilloverSpace(t);return e.isSilent=this.isSilent,e}}class O extends A{constructor(t,e=v){super(e),this.value=t,this.TYPE="Literal",this.embelishments=[]}debugValue(){const t=Object.assign(Object.assign({},super.debugValue()),{value:this.value});return this.embelishments.length>0&&(t.embs=this.embelishments.map(t=>"debugValue"in t?t.debugValue():t)),t}toString(){return`Lit(${this.duration}-${this.value})`}equals(t){return super.equals(t)&&this.value==t.value}copyTo(t){super.copyTo(t),t.value=this.value}}class R extends O{constructor(t,e=v,s=0,n=0){super(t,e),this.TYPE="Note",this.octave=0,this.shift=0,this.octave=s,this.shift=n}static fromLit(t){if(t.TYPE==_.NOTE)return t;const e=new R(t.value,t.duration);return e.embelishments=t.embelishments,e.beforeRest=t.beforeRest,e}debugValue(){const t=Object.assign({},super.debugValue());return 0!=this.octave&&(t.octave=this.octave),0!=this.shift&&(t.shift=this.shift),t}toString(){return`Note(${this.duration}-${this.value}-${this.octave})`}equals(t){return super.equals(t)&&this.octave==t.octave&&this.shift==t.shift}copyTo(t){super.copyTo(t),t.octave=this.octave,t.shift=this.shift}}class k extends N{constructor(...t){super(0==t.length?w:v),this.TYPE="Group",this.durationIsMultiplier=!1,this.atoms=new f,this._observers=[],this.addAtoms(!1,...t)}addObserver(t){return this._observers.push(t),()=>this.removeObserver(t)}removeObserver(t){const e=this._observers.indexOf(t);e>=0&&this._observers.splice(e,1)}notifyObservers(e,s,n){var r,i,o;if(this._eventsEnabled)for(const a of this._observers)switch(e){case t.ADD:null===(r=a.onAtomsAdded)||void 0===r||r.call(a,this,s,n);break;case t.INSERT:null===(i=a.onAtomsInserted)||void 0===i||i.call(a,this,s,n);break;case t.REMOVE:null===(o=a.onAtomsRemoved)||void 0===o||o.call(a,this,s)}}equals(t,e=!1){return!!super.equals(t)&&this.atoms.equals(t.atoms,(t,e)=>t.equals(e))}copyTo(t){super.copyTo(t),t.durationIsMultiplier=this.durationIsMultiplier;for(const e of this.atoms.values())t.atoms.add(e.clone())}get duration(){return this.durationIsMultiplier?this.totalChildDuration.divby(this._duration):this._duration}setDurationAsMultiplier(t=!0){return this.durationIsMultiplier=t,this}setDuration(t,e=!1){return this._duration=t,this.durationIsMultiplier=e,this}debugValue(){const t=Object.assign(Object.assign({},super.debugValue()),{atoms:Array.from(this.atoms.values(),t=>t.debugValue())});return this.durationIsMultiplier&&(t.durationIsMultiplier=!0),t}splitAt(t){if(this.duration.isLTE(t)||t.isLTE(w))return null;const e=new k;this.durationIsMultiplier&&(e.durationIsMultiplier=!0,e._duration=this._duration);let s=this.duration;const n=this.totalChildDuration,r=this.durationIsMultiplier?v.divby(this._duration):this._duration.divby(n,!0);for(;s.isGT(t)&&this.atoms.last;){const n=this.atoms.last,i=n.duration.times(r),o=s.minus(i);if(!o.isGTE(t)){const s=t.minus(o,!0).divby(r,!0),i=n.splitAt(s);if(null==i)throw new Error("Spill over cannot be null here");if(this.durationIsMultiplier){if(this._duration.isZero)throw new Error("How can this be?")}else this._duration=t;return i.isContinuation=!0,e.insertAtomsAt(e.atoms.first,!0,i),e}if(this.removeAtoms(!0,n),e.insertAtomsAt(e.atoms.first,!0,n),o.equals(t))return e;s=o}return e}get totalChildDuration(){let t=w;for(const e of this.atoms.values())t=t.plus(e.duration);return t}insertAtomsAt(e,s=!1,...n){const r=(s=s&&!this.durationIsMultiplier)?this.totalChildDuration:v;let i;if(e){i=0;for(const t of this.atoms.values()){if(t===e)break;i++}}else i=this.atoms.size;const o=[];for(const t of n){if(null!=t.parentGroup){if(t.parentGroup!=this)throw new Error("Atom belongs to another parent. Remove it first");t.parentGroup.removeAtoms(!1,t)}if(t.TYPE==_.REST){const t=this.atoms.last;t&&t.TYPE!=_.GROUP&&t.TYPE!=_.LABEL&&(t.beforeRest=!0)}else t.parentGroup=this,this.atoms.add(t,e),o.push(t)}if(s)if(this._duration.isZero){if(this.durationIsMultiplier)throw new Error("How can this be?");this._duration=this.totalChildDuration}else{const t=this.totalChildDuration.divby(r);this._duration=this._duration.times(t,!0)}if(o.length>0){const s=e?t.INSERT:t.ADD;this.notifyObservers(s,o,i)}return this}addAtoms(t=!1,...e){return this.insertAtomsAt(null,t,...e)}removeAtoms(e=!1,...s){const n=(e=e&&!this.durationIsMultiplier)?this.totalChildDuration:v,r=[];for(const t of s)if(t.parentGroup==this)this.atoms.remove(t),t.parentGroup=null,r.push(t);else if(null!=t.parentGroup)throw new Error("Atom cannot be removed as it does not belong to this group");if(e)if(this._duration.isZero){if(this.durationIsMultiplier)throw new Error("How can this be?");this._duration=this.totalChildDuration}else{const t=this.totalChildDuration.divby(n);this._duration=this._duration.times(t,!0)}return r.length>0&&this.notifyObservers(t.REMOVE,r,-1),this}}const L=p.ZERO;class M{constructor(t){this.uuid=M.counter++,t=t||{},this.beatDuration=t.beatDuration||1,"cycle"in t&&(this.cycle=t.cycle),this.cycle&&!this.cycle.duration.isZero||(this.cycle=C.DEFAULT),this._rowStartOffsets=[],this._rowEndOffsets=[],this._rowDurations=[],this._totalLayoutDuration=L,this._totalBeats=0,this._beatLayouts=[],this.lineBreaks=t.lineBreaks||t.layout||[]}equals(t){return this.beatDuration==t.beatDuration&&this.cycle.equals(t.cycle)&&this.lineBreaksEqual(t._lineBreaks)}lineBreaksEqual(t){return this._lineBreaks.length==t.length&&this._lineBreaks.every((e,s)=>e==t[s])}debugValue(){var t;return{cycle:null===(t=this.cycle)||void 0===t?void 0:t.debugValue(),beatDuration:this.beatDuration,lineBreaks:this._lineBreaks}}getBeatLocation(t){const e=t.index%this.totalBeats;let s=0;for(let n=0;n<this._lineBreaks.length;n++){if(e<s+this._lineBreaks[n]){let r=L;if(e>s){const n=new S(this.cycle,t.barIndex,t.beatIndex,t.instance);let[,i]=n.prev;for(let t=s;t<e;t++)[,i]=n.prev,r=r.plus(i.timesNum(this.beatDuration))}return[n,e-s,r]}s+=this._lineBreaks[n]}throw new Error("Invalid beat index: "+t.index)}get lineBreaks(){return this._lineBreaks&&0!=this._lineBreaks.length||(this.lineBreaks=[this.cycle.beatCount]),this._lineBreaks}set lineBreaks(t){this._lineBreaks=t,this.refreshLayout()}get beatLayouts(){return(!this._beatLayouts||this._beatLayouts.length<this.lineBreaks.length)&&this.refreshLayout(),this._beatLayouts}get totalBeats(){return this.beatLayouts,this._totalBeats}get totalLayoutDuration(){return this.beatLayouts,this._totalLayoutDuration}refreshLayout(){const t=this.cycle.iterateBeats(),e=this.beatDuration;this._beatLayouts=this.lineBreaks.map((s,n)=>{const r=[];for(let n=0;n<s;n++){const s=t.next().value;s[1]=s[1].timesNum(e),r.push(s)}return r}),this._totalBeats=this.lineBreaks.reduce((t,e)=>t+e,0),this._rowDurations=this._beatLayouts.map(t=>t.reduce((t,e)=>t.plus(e[1]),L)),this._rowDurations.forEach((t,e)=>{this._rowStartOffsets[e]=0==e?L:this._rowStartOffsets[e-1].plus(t)}),this._rowEndOffsets=this._rowDurations.map((t,e)=>this._rowStartOffsets[e].plus(t)),this._totalLayoutDuration=this._rowDurations.reduce((t,e)=>t.plus(e),L)}}M.counter=0;class P extends c{constructor(){super(...arguments),this.uuid=P.idCounter++,this.lastUpdatedAt=0,this.rows=[],this.rowAligns=new Map,this.colAligns=new Map}debugValue(){return{rows:this.rows.map(t=>t.debugValue()),lastUpdatedAt:this.lastUpdatedAt}}get firstRow(){for(const t of this.rows)if(t.numCells>0)return t.rowIndex;return-1}get firstCol(){let t=-1;for(const e of this.rows){const s=e.firstCol;s>=0&&(t<0||s<t)&&(t=s)}return t}cellsInRow(t){const e=[],s=this.rows[t];if(s)for(const t of s.cells)(null==t?void 0:t.value)&&e.push(t);return e}cellsInCol(t){const e=[];for(const s of this.rows){const n=s.cellAt(t);(null==n?void 0:n.value)&&e.push(n)}return e}addRowAlign(t){this.rowAligns.set(t.uuid,t)}addColAlign(t){this.colAligns.set(t.uuid,t)}addRows(t=-1,e=1){t<0&&(t=this.rows.length);let s=this.rows[t]||null;const n=this.rows[t-1]||null;for(let r=e-1;r>=0;r--){const e=new D(this,t+r);this.rows.splice(t,0,e),null!=s&&e.defaultRowAlign.addSuccessor(s.defaultRowAlign),0==r&&t>0&&n.defaultRowAlign.addSuccessor(e.defaultRowAlign),s=e}for(let s=t+e;s<this.rows.length;s++)this.rows[s].rowIndex+=e;return this}getRow(t){return t>=this.rows.length&&this.addRows(-1,1+t-this.rows.length),this.rows[t]}setValue(t,e,s,n){var r,i;const o=this.getRow(t);if(n||(n=(t,e)=>new $(t,e)),null==s){const t=o.clearCellAt(e);return null!=t&&(null===(r=this.eventHub)||void 0===r||r.emit(B.CLEARED,this,{loc:t.location})),t}{const t=o.cellAt(e,n),r=t.value;return null===(i=this.eventHub)||void 0===i||i.emit(B.UPDATED,this,{loc:t.location,cell:t,oldValue:t.value}),t.value=s,r}}eventHubChanged(){console.log("Event Hub Changed for GridModel")}}var B;P.idCounter=0,function(t){t.ADDED="CellAdded",t.CLEARED="CellCleared",t.REMOVED="CellRemoved",t.UPDATED="CellUpdated",t.MOVED="CellMoved"}(B||(B={}));class ${constructor(t,e,s=null){this.gridRow=t,this.colIndex=e,this.value=s,this.uuid=$.idCounter++,this.rowAlign=t.defaultRowAlign}get rowAlign(){return this._rowAlign}set rowAlign(t){t.addCell(this),this._rowAlign=t}get colAlign(){return this._colAlign}set colAlign(t){t.addCell(this),this._colAlign=t}get location(){return this.gridRow.rowIndex+":"+this.colIndex}get grid(){return this.gridRow.grid}get rowIndex(){return this.gridRow.rowIndex}debugValue(){const t={r:this.gridRow.rowIndex,c:this.colIndex,value:this.value,y:this.rowAlign.coordOffset,h:this.rowAlign.maxLength};return this.colAlign&&(t.x=this.colAlign.coordOffset,t.w=this.colAlign.maxLength),t}}$.idCounter=0;class D{constructor(t,e){this.grid=t,this.rowIndex=e,this.cells=[],this.defaultRowAlign=new F,this.grid.addRowAlign(this.defaultRowAlign)}get firstCol(){var t;for(let e=0;e<this.cells.length;e++)if(null===(t=this.cells[e])||void 0===t?void 0:t.value)return e;return-1}get numCols(){return this.cells.length}get numCells(){let t=0;for(const e of this.cells)null!=e&&null!=e.value&&t++;return t}cellAt(t,e){let s=this.cells[t]||null;return!s&&e&&(this.cells[t]=s=e(this,t),s.gridRow=this,s.colIndex=t,s.rowAlign&&this.grid.addRowAlign(s.rowAlign),s.colAlign&&this.grid.addColAlign(s.colAlign)),s}clearCellAt(t){const e=this.cells[t]||null;return e&&(this.cells[t]=null),e}debugValue(){return{r:this.rowIndex,cells:this.cells.filter(t=>t).map(t=>null==t?void 0:t.debugValue())}}}class U{constructor(){this.uuid=U.idCounter++,this.needsLayout=!1,this._coordOffset=0,this._maxLength=0,this.paddingBefore=5,this.paddingAfter=5,this.cells=[],this.prevLines=[],this.nextLines=[]}get coordOffset(){return this._coordOffset}get maxLength(){return this._maxLength+this.paddingBefore+this.paddingAfter}setMaxLength(t){this._maxLength=t}setPadding(t,e){t>=0&&(this.paddingBefore=t),e>=0&&(this.paddingAfter=e)}addCell(t){return this.beforeAddingCell(t)&&this.cells.push(t),this}removeCell(t){if(this.beforeRemovingCell(t))for(let e=0;e<this.cells.length;e++)if(this.cells[e].uuid==t.uuid){this.cells.splice(e,1);break}return this}addSuccessor(t){for(const e of this.nextLines)if(e==t)return;this.nextLines.push(t),t.prevLines.push(this)}}U.idCounter=0;class F extends U{setOffset(t){this._coordOffset=t;for(const e of this.cells)if(e.value){const s=this.getCellView(e);this._maxLength<=0&&this.evalMaxLength(),s.setBounds(null,t,null,this.maxLength,!0)}}evalMaxLength(t=[]){this._maxLength=0;for(const t of this.cells)if(t.value){const e=this.getCellView(t);this._maxLength=Math.max(e.minSize.height,this._maxLength)}return this._maxLength}beforeAddingCell(t){return t.rowAlign&&t.rowAlign!=this&&t.rowAlign.removeCell(t),t.rowAlign!=this}beforeRemovingCell(t){return t.rowAlign==this}}p.ZERO;const j=p.ONE;class V{constructor(t,e,s,n,r,i,o,a,l){this.index=t,this.role=e,this.offset=s,this.duration=n,this.barIndex=r,this.beatIndex=i,this.instance=o,this.prevBeat=a,this.nextBeat=l,this.uuid=V.idCounter++,this.atomIsPlaceholder=!1}debugValue(){return{index:this.index,role:this.role.name,offset:this.offset.toString(),duration:this.duration.toString(),barIndex:this.barIndex,beatIndex:this.beatIndex,instance:this.instance,atom:this.atom.debugValue()}}get endOffset(){return this.offset.plus(this.duration)}get filled(){return this.remaining.isZero}get remaining(){return this.atom?this.duration.minus(this.atom.duration,!0):this.duration}add(t){return!(this.remaining.cmp(t.duration)<0||(this.atom?(this.atomIsPlaceholder||(this.atomIsPlaceholder=!0,this.atom=new k(this.atom).setDuration(j,!0)),this.atom.addAtoms(!0,t)):this.atom=t,0))}get preMarkers(){const t=[];let e=this.atom;for(;null!=e;){for(const s of e.markersBefore||[])t.push(s);e=e.TYPE==_.GROUP?e.atoms.first:null}return t}get postMarkers(){const t=[];let e=this.atom;for(;null!=e;)t.splice(0,0,...e.markersAfter||[]),e=e.TYPE==_.GROUP?e.atoms.last:null;return t}}function G(t,e,s){const n=[],r={};return t.forEach(t=>{if(!(e(t)in r)){const i=t,o={};let l=[[t,[]]];for(;l.length>0;){const t=[];for(let h=0;h<l.length;h++){const[u,c]=l[h];a(null!=u);const d=s(u);let f=[...c];for(const[s,a]of d)s==i?(f.push([a,s]),f.forEach(([t,e],s)=>r[e]=!0),n.push([i,f]),f=f.slice(0,f.length-1)):e(s)in o||(o[e(s)]=!0,t.push([s,[...f,[a,s]]]))}l=t}}}),n}V.idCounter=0;const z=t=>t.key;class W{constructor(t=z){this._entries=[],this._entriesByKey={},this.keyFunc=t}clear(){this._entries=[],this._entriesByKey={}}remove(t){const e=[];this._entriesByKey={};let s=!1;for(let n=0;n<this._entries.length;n++){const r=this._entries[n];t(r)?s=!0:(r.id=e.length,e.push(r),this._entriesByKey[this.keyFunc(r)]=r)}return this._entries=e,s}get entries(){return this._entries}get(t){return a(t>=0&&t<this._entries.length),this._entries[t]}getByKey(t){return this._entriesByKey[t]||null}ensure(t,e=!1){if(this.has(t)){if(e)throw new Error(`Entry ${this.keyFunc(t)} already exists`);return this._entriesByKey[this.keyFunc(t)]}return this._entriesByKey[this.keyFunc(t)]=t,t.id=this._entries.length,this._entries.push(t),t}has(t){return this.keyFunc(t)in this._entriesByKey}get size(){return this._entries.length}}class K{constructor(t,e=!0){this.entries=new Set,this.hasNull=!1,this.grammar=t,this.enforceSymbolType=e}get debugString(){return"<"+this.labels().sort().join(", ")+">"}labels(t=!1){const e=[];for(const s of this.entries){const n=this.grammar.getSymById(s);a(null!=n),t&&n.isAuxiliary||e.push(n.label)}return this.hasNull&&e.push(""),e}addFrom(t,e=!0){return t.addTo(this,e)}addTo(t,e=!0){const s=t.entries.size;for(const e of this.entries)t.entries.add(e);return e&&(t.hasNull=this.hasNull||t.hasNull),t.entries.size-s}has(t){return this.entries.has(t.id)}add(t){return a(null==this.enforceSymbolType||this.enforceSymbolType==t.isTerminal,`Terminal types being enforced: ${this.enforceSymbolType}`),this.entries.add(t.id),this}delete(t){return this.entries.delete(t.id)}get size(){return this.entries.size+(this.hasNull?1:0)}}class H{constructor(t){this.grammar=t,this.refresh()}get nonterms(){const t=[];return this.entries.forEach(e=>{const s=this.grammar.getSymById(e);a(null!=s&&!s.isTerminal),t.push(s)}),t}refresh(){this.entries=new Set,this.visited={};let t=0;do{t=this.entries.size,this.grammar.allNonTerminals.forEach(t=>this.visit(t))}while(t!=this.entries.size)}visit(t){for(const e of this.grammar.rulesForNT(t))if(this.isStrNullable(e.rhs)){this.add(t);break}}isNullable(t){return!t.isTerminal&&this.entries.has(t.id)}isStrNullable(t,e=0,s=null){null==s&&(s=t.length-1);for(let n=e;n<=s;n++)if(!this.isNullable(t.syms[n]))return!1;return!0}add(t){a(!t.isTerminal),this.entries.add(t.id)}}class q{constructor(t){this.entries={},this._count=0,this.grammar=t}refresh(){this.entries={},this._count=0}forEachTerm(t,e){const s=this.entriesFor(t);s.entries.forEach(t=>{const s=this.grammar.getSymById(t);a(null!=s&&s.isTerminal),e(s)}),s.hasNull&&e(null)}get debugValue(){const t={};for(const e in this.entries)t[this.grammar.getSymById(e).label]=this.entries[e].debugString;return t}get count(){let t=0;for(const e in this.entries)t+=this.entries[e].size;return t}entriesFor(t){if(t.id in this.entries)return this.entries[t.id];{const e=new K(this.grammar);return this.entries[t.id]=e,e}}addNull(t){const e=this.entriesFor(t);return!e.hasNull&&(e.hasNull=!0,!0)}add(t,e,s=!0){t.isTerminal&&a(!1,"Should not be here");const n=this.entriesFor(t);if(e.isTerminal){if(n.has(e))return!1;n.add(e),this._count++}else{const n=this.entriesFor(e),r=this.entriesFor(t),i=n.addTo(r,s);this._count+=i}return!0}}class Q extends q{constructor(t,e){super(t),e||(e=new H(t)),this.nullables=e,this.refresh()}forEachTermIn(t,e=0,s){const n=t.syms,r={};let i=!0;for(let t=e;i&&t<n.length;t++){const e=n[t];if(e.isTerminal)s(e),i=!1;else{const t=e;this.forEachTerm(t,t=>{null==t||t.id in r||(r[t.id]=!0,s(t))}),this.nullables.isNullable(e)||(i=!1)}}i&&s(null)}refresh(){super.refresh();let t=0;do{t=this.count,this.grammar.forEachRule(null,t=>{this.processRule(t)})}while(t!=this.count)}processRule(t){const e=this.nullables;let s=!0;for(const n of t.rhs.syms)if(this.add(t.nt,n,!1),n.isTerminal||!e.isNullable(n)){s=!1;break}s&&this.addNull(t.nt)}}class J extends q{constructor(t,e){super(t),this.firstSets=e||new Q(t),this.refresh()}get nullables(){return this.firstSets.nullables}refresh(){super.refresh();const t=this.grammar;a(null!=t.startSymbol,"Select start symbol of the grammar"),this.add(t.startSymbol,t.Eof);let e=0;do{e=this.count,this.grammar.forEachRule(null,t=>this.processRule(t))}while(e!=this.count)}processRule(t){const e=t.rhs.syms,s=this.firstSets,n=this.firstSets.nullables;for(let n=0;n<e.length;n++){const r=e[n];r.isTerminal||s.forEachTermIn(t.rhs,n+1,t=>{null!=t&&this.add(r,t)})}for(let s=e.length-1;s>=0;s--){if(e[s].isTerminal)continue;let r=!0;for(let t=s+1;t<e.length;t++){const s=e[t];if(s.isTerminal||!n.isNullable(s)){r=!1;break}}r&&this.add(e[s],t.nt)}}}class Y{constructor(t,e,s,n=null){this.grammar=t,this.label=e,this.isTerminal=s,this.isAuxiliary=!1,this.auxType=null,this.precedence=1,this.assocLeft=!0,this.creationId=-1,this.isTerminal=s,this.label=e,this.id=null==n?Y.idCounter--:n}compareTo(t){return this.label.localeCompare(t.label)}equals(t){return this.label==t.label}toString(){return this.label}}Y.idCounter=-1;class X{constructor(...t){this.syms=t||[]}append(...t){for(const e of t)this.syms.push(e);return this}extend(...t){for(const e of t)this.append(...e.syms);return this}copy(){return new X(...this.syms)}add(t){this.syms.push(t)}isTerminal(t){return this.syms[t].isTerminal}get length(){return this.syms.length}toString(){return this.syms.map(t=>t.toString()).join(" ")}slice(t,e){return new X(...this.syms.slice(t,e))}splice(t,e,...s){return this.syms.splice(t,e,...s),this}compareTo(t){for(let e=0;e<this.syms.length&&e<t.syms.length;e++){const s=this.syms[e].compareTo(t.syms[e]);if(0!=s)return s}return this.syms.length-t.syms.length}equals(t){return 0==this.compareTo(t)}containsAt(t,e){let s=0;for(;s<e.length&&t+s<this.syms.length;s++)if(!this.syms[t+s].equals(e.syms[s]))return!1;return s==e.length}get debugString(){return this.syms.map(t=>t.label).join(" ")}}class Z{constructor(t){this.value=t}get isFunction(){return"string"==typeof this.value}get isChildPosition(){return"number"==typeof this.value}}class tt{constructor(t,e,s=null){if(this.nt=t,this.rhs=e,this.action=s,t.isTerminal)throw new Error("Cannot add rules to a terminal")}get debugString(){return`${this.nt.label} -> ${this.rhs.debugString}`}equals(t){return 0==this.compareTo(t)}compareTo(t){a(!isNaN(this.id));const e=this.nt.compareTo(t.nt);return 0==e&&this.rhs.compareTo(t.rhs),e}}class et{static make(t){const e=new et;return t(e),e}constructor(t){this.startSymbol=null,this.modified=!0,this.symbolSet=new W(t=>t.label),this.allRules=[],this._rulesForNT=null,this._followSets=null,this._hasNull=!1,this.auxNTCount=0,t=t||{},this.auxNTPrefix=t.auxNTPrefix||"$",this.Null=this.newTerm(""),this.Eof=this.newTerm("$end")}rulesForNT(t){if(a(!t.isTerminal),null==this._rulesForNT){this._rulesForNT={};for(const t of this.allRules)t.nt.label in this._rulesForNT||(this._rulesForNT[t.nt.label]=[]),this._rulesForNT[t.nt.label].push(t)}return t.label in this._rulesForNT||(this._rulesForNT[t.label]=[]),this._rulesForNT[t.label]}get nullables(){return this.firstSets.nullables}get firstSets(){return this.followSets.firstSets}get followSets(){return(this.modified||null==this._followSets)&&this.refresh(),a(null!=this._followSets),this._followSets}get augStartRule(){return this._AugStartRule}augmentStartSymbol(t="$accept"){a(null==this._AugStartRule,"Ensure this grammar has not yet been augmented."),a(null!=this.startSymbol,"Start symbol not yet set");const e=this.newNT(t);return this._AugStartRule=new tt(e,new X(this.startSymbol)),this.addRule(this._AugStartRule,0),this}refresh(){return this.symbolSet.entries.forEach((t,e)=>t.id=e),this._rulesForNT=null,this.allRules.forEach((t,e)=>{t.id=e}),this._followSets=new J(this),this.modified=!1,this}addTerminals(...t){for(const e of t)this.newTerm(e)}get terminals(){return this.symbolSet.entries.filter(t=>t.isTerminal)}get allNonTerminals(){return this.symbolSet.entries.filter(t=>!t.isTerminal)}get nonTerminals(){return this.symbolSet.entries.filter(t=>!t.isTerminal&&!t.isAuxiliary)}get auxNonTerminals(){return this.symbolSet.entries.filter(t=>t.isAuxiliary)}get allSymbols(){return this.symbolSet.entries}forEachNT(t){for(const e of this.symbolSet.entries)if(!e.isTerminal&&0==t(e))return}forEachRule(t,e){const s=null==t?this.allRules:this.rulesForNT(t)||[];for(let t=0;t<s.length;t++)if(0==e(s[t],t))return!1;return!0}getRule(t,e){return"string"==typeof t&&(t=this.getSym(t)),a(null!=t),this.rulesForNT(t)[e]}findRule(t,e){return this.rulesForNT(t).findIndex(s=>s.nt==t&&s.rhs.equals(e))}add(t,e,s=null){let n=null;return"string"==typeof t?(n=this.getSym(t),null==n&&(n=this.newNT(t))):n=this.ensureSym(t),this.addRule(new tt(n,e,s))}addRule(t,e=-1){if(this.findRule(t.nt,t.rhs)>=0)throw new Error("Duplicate rule: "+t.debugString);return t.id=this.allRules.length,0==t.rhs.length&&(this._hasNull=!0),e<0?this.allRules.push(t):this.allRules.splice(e,0,t),this._rulesForNT=null,this.modified=!0,t}removeRules(t){return this.allRules=this.allRules.filter(e=>!t(e)),this._rulesForNT=null,this.modified=!0,!0}removeSymbols(t){let e=!1;const s=[];return this.allRules.forEach(n=>{if(!t(n.nt))if(0==n.rhs.length)s.push(n);else{const r=new X(...n.rhs.syms.filter(e=>!t(e)));e=e||n.rhs.length!=r.length,r.length>0&&s.push(new tt(n.nt,r))}}),this.allRules=s,e=this.symbolSet.remove(t)||e,this.modified=this.modified||e,e}getSymById(t){return this.symbolSet.get(t)}getSym(t){return this.symbolSet.getByKey(t)}ensureSym(t,e=!1){const s=this.symbolSet.ensure(t,e);return t==s?s.creationId<0&&(s.creationId=this.symbolSet.size):a(!e,"Should have already thrown error"),s}T(t,e=!1){let s=this.getSym(t);if(null!=s){if(e)throw new Error(`Terminal ${t} is already exists`);if(!s.isTerminal)throw new Error(`Symbol (${t}) already exists as a non-terminal`)}else s=new Y(this,t,!0),s=this.ensureSym(s,!0);return s}NT(t,e=!1,s=!1){let n=this.getSym(t);if(null!=n){if(s)throw new Error(`Non-terminal ${t} is already exists`);if(n.isTerminal)throw new Error(`Symbol (${t}) already exists as a terminal`)}else n=new Y(this,t,!1),n.isAuxiliary=e,n=this.ensureSym(n,!0),e||null!=this.startSymbol||(this.startSymbol=n);return n}newTerm(t){return this.T(t,!0)}newNT(t,e=!1){return this.NT(t,e,!0)}isTerminal(t){const e=this.getSym(t);return null!=e&&e.isTerminal}isNT(t){const e=this.getSym(t);return null!=e&&!e.isTerminal&&!e.isAuxiliary}isAuxNT(t){const e=this.getSym(t);return null!=e&&!e.isTerminal&&e.isAuxiliary}seq(...t){if(1==t.length)return this.normalizeRule(t[0]);{const e=new X;for(const s of t){const t=this.normalizeRule(s);for(let s=0;s<t.length;s++)e.add(t.syms[s])}return e}}anyof(...t){return 1==t.length?this.normalizeRule(t[0]):new X(this.ensureAuxNT(...t.map(t=>this.normalizeRule(t))))}opt(t){const e=this.anyof(t,new X),s=e.syms[0];return a(1==e.syms.length&&s.isAuxiliary,"NT must be an auxiliary symbol"),s.auxType="opt",e}atleast0(t,e=!0){const s=this.normalizeRule(t);let n=this.findAuxNT(e=>{const n=this.rulesForNT(e);if(2!=n.length)return!1;let r=0;if(0==n[0].rhs.length)r=1;else{if(0!=n[1].rhs.length)return!1;r=0}const i=n[r].rhs;return i.length==1+t.length&&(i.syms[0].equals(e)?i.containsAt(1,s):!!i.syms[i.length-1].equals(e)&&i.containsAt(0,s))});return null==n&&(n=this.newAuxNT(),n.auxType=e?"atleast0:left":"atleast0",this.add(n,new X),e?this.add(n,new X(n).extend(s)):this.add(n,s.copy().append(n))),new X(n)}atleast1(t,e=!0){const s=this.normalizeRule(t);let n=this.findAuxNT(e=>{const n=this.rulesForNT(e);if(2!=n.length)return!1;let r=0;if(n[0].rhs.equals(s))r=1;else{if(!n[1].rhs.equals(s))return!1;r=0}const i=n[r].rhs;return i.length==1+t.length&&(i.syms[0].equals(e)?i.containsAt(1,s):!!i.syms[i.length-1].equals(e)&&i.containsAt(0,s))});return null==n&&(n=this.newAuxNT(),n.auxType=e?"atleast1:left":"atleast1",this.add(n,s),e?this.add(n,new X(n).extend(s)):this.add(n,s.copy().append(n))),new X(n)}normalizeRule(t){if("string"==typeof t){const e=this.getSym(t);if(null==e)throw new Error(`Invalid symbol: '${t}'`);return new X(e)}return t}newAuxNTName(){return this.auxNTPrefix+this.auxNTCount++}newAuxNT(t=""){return""==t&&(t=this.newAuxNTName()),this.newNT(t,!0)}ensureAuxNT(...t){let e=this.findAuxNTByRules(...t);if(null==e){e=this.newAuxNT(),e.auxType="anyof";for(const s of t)this.add(e,s)}return e}findAuxNT(t){for(const e of this.symbolSet.entries)if(e.isAuxiliary&&t(e))return e;return null}findAuxNTByRules(...t){return this.findAuxNT(e=>{const s=this.rulesForNT(e);if(s.length!=t.length)return!1;for(let e=0;e<s.length;e++)if(!s[e].rhs.equals(t[e]))return!1;return!0})}print(t=null){const e=(t=t||{}).ruleSep||"->",s=t.includeSemiColon||!1,n=t.lambdaSymbol||"",r=[];return this.forEachRule(null,(t,i)=>{let o=`${t.nt.label} ${e} `;t.rhs.length>0?o+=t.rhs.debugString:o+=n,s&&(o+=" ;"),r.push(o)}),r}get debugValue(){const t=[];return this.forEachRule(null,(e,s)=>{t.push(`${e.nt.label} -> ${e.rhs.debugString}`)}),t}get terminalDerivingSymbols(){const t=new K(this,null);let e=-1,s=!0;for(;0!=e;){e=0;for(const n of this.allRules){s=!0;for(const r of n.rhs.syms)t.has(r)||(r.isTerminal?(t.add(r),e++):s=!1);s&&!t.has(n.nt)&&(t.add(n.nt),e++)}}return t}reachableSymbols(t=null){null==t&&(t=this._AugStartRule?this._AugStartRule.nt:this.startSymbol),a(null!=t,"Start symbol does not exist");const e=new K(this,!1).add(t);let s=[t];for(;s.length>0;){const t=[];for(const n of s)for(const s of this.rulesForNT(n))for(const n of s.rhs.syms)n.isTerminal||e.has(n)||(t.push(n),e.add(n));s=t}return e}get cycles(){return G(this.allNonTerminals,t=>t.label,t=>{const e=[];return this.forEachRule(t,(s,n)=>{s.rhs.syms.forEach((r,i)=>{r.isTerminal||this.nullables.isStrNullable(s.rhs,0,i-1)&&this.nullables.isStrNullable(s.rhs,i+1)&&e.push([r,[t,n]])})}),e})}get leftRecursion(){return G(this.allNonTerminals,t=>t.id,t=>{const e=[];return this.forEachRule(t,(t,s)=>{t.rhs.syms.forEach((t,n)=>{if(!t.isTerminal)return e.push([t,s]),this.nullables.isNullable(t)})}),e})}}var st;!function(t){t[t.WORD_CHAR=0]="WORD_CHAR",t[t.DIGITS=1]="DIGITS",t[t.SPACES=2]="SPACES"}(st||(st={}));const nt="0".charCodeAt(0),rt="9".charCodeAt(0),it="a".charCodeAt(0),ot="z".charCodeAt(0),at="A".charCodeAt(0),lt="Z".charCodeAt(0),ht="_".charCodeAt(0);class ut{matches(t,e){const s=this.match(t);return e?!s:s}}const ct=[new class extends ut{match(t){return t==ht||t>=nt&&t<=rt||t>=it&&t<=ot||t>=at&&t<=lt}reString(t){return t?"\\W":"\\w"}},new class extends ut{match(t){return t>=nt&&t<=rt}reString(t){return t?"\\D":"\\d"}},new class extends ut{match(t){if(t>=8192&&t<=8202)return!0;for(let e=0;e<14;e++)if(" \f\n\r\t\v  \u2028\u2029   \ufeff".charCodeAt(e)==t)return!0;return!1}reString(t){return t?"\\S":"\\s"}}];var dt,ft,gt,mt,pt;!function(t){t[t.gc=0]="gc",t[t.General_Category=0]="General_Category",t[t.sc=1]="sc",t[t.Script=1]="Script",t[t.scx=2]="scx",t[t.Script_Extension=2]="Script_Extension",t[t.Any=3]="Any",t[t.ASCII=4]="ASCII",t[t.AHex=5]="AHex",t[t.ASCII_Hex_Digit=5]="ASCII_Hex_Digit",t[t.Alpha=6]="Alpha",t[t.Alphabetic=6]="Alphabetic",t[t.Bidi_M=7]="Bidi_M",t[t.Bidi_Mirrored=7]="Bidi_Mirrored",t[t.Bidi_C=8]="Bidi_C",t[t.Bidi_Control=8]="Bidi_Control",t[t.CI=9]="CI",t[t.Case_Ignorable=9]="Case_Ignorable",t[t.Cased=10]="Cased",t[t.CWCF=11]="CWCF",t[t.Changes_When_Casefolded=11]="Changes_When_Casefolded",t[t.CWCM=12]="CWCM",t[t.Changes_When_Casemapped=12]="Changes_When_Casemapped",t[t.CWL=13]="CWL",t[t.Changes_When_Lowercased=13]="Changes_When_Lowercased",t[t.CWKCF=14]="CWKCF",t[t.Changes_When_NFKC_Casefolded=14]="Changes_When_NFKC_Casefolded",t[t.CWT=15]="CWT",t[t.Changes_When_Titlecased=15]="Changes_When_Titlecased",t[t.CWU=16]="CWU",t[t.Changes_When_Uppercased=16]="Changes_When_Uppercased",t[t.Dash=17]="Dash",t[t.DI=18]="DI",t[t.Default_Ignorable_Code_Point=18]="Default_Ignorable_Code_Point",t[t.Dep=19]="Dep",t[t.Deprecated=19]="Deprecated",t[t.Dia=20]="Dia",t[t.Diacritic=20]="Diacritic",t[t.Emoji=21]="Emoji",t[t.Emoji_Component=22]="Emoji_Component",t[t.Emoji_Modifier=23]="Emoji_Modifier",t[t.Emoji_Modifier_Base=24]="Emoji_Modifier_Base",t[t.Emoji_Presentation=25]="Emoji_Presentation",t[t.Ext=26]="Ext",t[t.Extender=26]="Extender",t[t.Gr_Base=27]="Gr_Base",t[t.Grapheme_Base=27]="Grapheme_Base",t[t.Gr_Ext=28]="Gr_Ext",t[t.Grapheme_Extend=28]="Grapheme_Extend",t[t.Hex=29]="Hex",t[t.Hex_Digit=29]="Hex_Digit",t[t.IDSB=30]="IDSB",t[t.IDS_Binary_Operator=30]="IDS_Binary_Operator",t[t.IDST=31]="IDST",t[t.IDS_Trinary_Operator=31]="IDS_Trinary_Operator",t[t.IDC=32]="IDC",t[t.ID_Continue=32]="ID_Continue",t[t.IDS=33]="IDS",t[t.ID_Start=33]="ID_Start",t[t.Ideo=34]="Ideo",t[t.Ideographic=34]="Ideographic",t[t.Join_C=35]="Join_C",t[t.Join_Control=35]="Join_Control",t[t.LOE=36]="LOE",t[t.Logical_Order_Exception=36]="Logical_Order_Exception",t[t.Lower=37]="Lower",t[t.Lowercase=37]="Lowercase",t[t.Math=38]="Math",t[t.NChar=39]="NChar",t[t.Noncharacter_Code_Point=39]="Noncharacter_Code_Point",t[t.Pat_Syn=40]="Pat_Syn",t[t.Pattern_Syntax=40]="Pattern_Syntax",t[t.Pat_WS=41]="Pat_WS",t[t.Pattern_White_Space=41]="Pattern_White_Space",t[t.QMark=42]="QMark",t[t.Quotation_Mark=42]="Quotation_Mark",t[t.Radical=43]="Radical",t[t.RI=44]="RI",t[t.Regional_Indicator=44]="Regional_Indicator",t[t.STerm=45]="STerm",t[t.Sentence_Terminal=45]="Sentence_Terminal",t[t.SD=46]="SD",t[t.Soft_Dotted=46]="Soft_Dotted",t[t.Term=47]="Term",t[t.Terminal_Punctuation=47]="Terminal_Punctuation",t[t.UIdeo=48]="UIdeo",t[t.Unified_Ideograph=48]="Unified_Ideograph",t[t.Upper=49]="Upper",t[t.Uppercase=49]="Uppercase",t[t.VS=50]="VS",t[t.Variation_Selector=50]="Variation_Selector",t[t.space=51]="space",t[t.White_Space=51]="White_Space",t[t.XIDC=52]="XIDC",t[t.XID_Continue=52]="XID_Continue",t[t.XIDS=53]="XIDS",t[t.XID_Start=53]="XID_Start"}(dt||(dt={})),function(t){t[t.LC=0]="LC",t[t.Cased_Letter=0]="Cased_Letter",t[t.Pe=1]="Pe",t[t.Close_Punctuation=1]="Close_Punctuation",t[t.Pc=2]="Pc",t[t.Connector_Punctuation=2]="Connector_Punctuation",t[t.Cc=3]="Cc",t[t.cntrl=3]="cntrl",t[t.Control=3]="Control",t[t.Sc=4]="Sc",t[t.Currency_Symbol=4]="Currency_Symbol",t[t.Pd=5]="Pd",t[t.Dash_Punctuation=5]="Dash_Punctuation",t[t.Nd=6]="Nd",t[t.digit=6]="digit",t[t.Decimal_Number=6]="Decimal_Number",t[t.Me=7]="Me",t[t.Enclosing_Mark=7]="Enclosing_Mark",t[t.Pf=8]="Pf",t[t.Final_Punctuation=8]="Final_Punctuation",t[t.Cf=9]="Cf",t[t.Format=9]="Format",t[t.Pi=10]="Pi",t[t.Initial_Punctuation=10]="Initial_Punctuation",t[t.L=11]="L",t[t.Letter=11]="Letter",t[t.Nl=12]="Nl",t[t.Letter_Number=12]="Letter_Number",t[t.Zl=13]="Zl",t[t.Line_Separator=13]="Line_Separator",t[t.Ll=14]="Ll",t[t.Lowercase_Letter=14]="Lowercase_Letter",t[t.M=15]="M",t[t.Combining_Mark=15]="Combining_Mark",t[t.Mark=16]="Mark",t[t.Sm=17]="Sm",t[t.Math_Symbol=17]="Math_Symbol",t[t.Lm=18]="Lm",t[t.Modifier_Letter=18]="Modifier_Letter",t[t.Sk=19]="Sk",t[t.Modifier_Symbol=19]="Modifier_Symbol",t[t.Mn=20]="Mn",t[t.Nonspacing_Mark=20]="Nonspacing_Mark",t[t.N=21]="N",t[t.Number=21]="Number",t[t.Ps=22]="Ps",t[t.Open_Punctuation=22]="Open_Punctuation",t[t.C=23]="C",t[t.Other=23]="Other",t[t.Lo=24]="Lo",t[t.Other_Letter=24]="Other_Letter",t[t.No=25]="No",t[t.Other_Number=25]="Other_Number",t[t.Po=26]="Po",t[t.Other_Punctuation=26]="Other_Punctuation",t[t.So=27]="So",t[t.Other_Symbol=27]="Other_Symbol",t[t.Zp=28]="Zp",t[t.Paragraph_Separator=28]="Paragraph_Separator",t[t.Co=29]="Co",t[t.Private_Use=29]="Private_Use",t[t.P=30]="P",t[t.punct=30]="punct",t[t.Punctuation=30]="Punctuation",t[t.Z=31]="Z",t[t.Separator=31]="Separator",t[t.Zs=32]="Zs",t[t.Space_Separator=32]="Space_Separator",t[t.Mc=33]="Mc",t[t.Spacing_Mark=33]="Spacing_Mark",t[t.Cs=34]="Cs",t[t.Surrogate=34]="Surrogate",t[t.S=35]="S",t[t.Symbol=35]="Symbol",t[t.Lt=36]="Lt",t[t.Titlecase_Letter=36]="Titlecase_Letter",t[t.Cn=37]="Cn",t[t.Unassigned=37]="Unassigned",t[t.Lu=38]="Lu",t[t.Uppercase_Letter=38]="Uppercase_Letter"}(ft||(ft={})),function(t){t[t.START_OF_INPUT=0]="START_OF_INPUT",t[t.END_OF_INPUT=1]="END_OF_INPUT",t[t.START_OF_WORD=2]="START_OF_WORD",t[t.END_OF_WORD=3]="END_OF_WORD",t[t.UNION=4]="UNION",t[t.CAT=5]="CAT",t[t.VAR=6]="VAR",t[t.BACK_NAMED_REF=7]="BACK_NAMED_REF",t[t.BACK_NUM_REF=8]="BACK_NUM_REF",t[t.QUANT=9]="QUANT",t[t.LOOK_AHEAD=10]="LOOK_AHEAD",t[t.LOOK_BACK=11]="LOOK_BACK",t[t.CHAR=12]="CHAR"}(gt||(gt={}));class bt{constructor(){this.parent=null,this.reString=null,this.groupIndex=-1,this.groupName=null,this.groupIsSilent=!1,this.ignoreCase=null,this.dotAll=null,this.multiline=null}setOptions(t){return"dotAll"in t&&(this.dotAll=t.dotAll),"ignoreCase"in t&&(this.ignoreCase=t.ignoreCase),"groupIndex"in t&&(this.groupIndex=t.groupIndex),"multiline"in t&&(this.multiline=t.multiline),this}debugValue(){const t={};return this.dotAll&&(t.dotAll=!0),this.ignoreCase&&(t.ignoreCase=!0),this.multiline&&(t.multiline=!0),this.groupIndex>=0&&(t.groupIndex=this.groupIndex),t}get isVariable(){return!1}get toString(){return null==this.reString&&(this.reString=this.evalREString()),this.reString}get modifiers(){let t="";return this.dotAll&&(t+="d"),this.ignoreCase&&(t+="i"),this.multiline&&(t+="m"),this.groupIndex>=0&&(t+="g:"+this.groupIndex),0==t.length?t:"<"+t+">"}}class yt extends bt{constructor(){super(...arguments),this.tag=gt.START_OF_INPUT}debugValue(){return"^"}reverse(){return this}evalREString(){return"^"}}class St extends bt{constructor(){super(...arguments),this.tag=gt.END_OF_INPUT}debugValue(){return"$"}evalREString(){return"$"}reverse(){return this}}class Et extends bt{constructor(t,e,s=!1){super(),this.expr=t,this.cond=e,this.negate=s}}class Ct extends Et{constructor(){super(...arguments),this.tag=gt.LOOK_AHEAD}evalREString(){return`${this.expr.toString}(?${this.negate?"!":"="}${this.cond.toString})`}debugValue(){return["LookAhead",{...super.debugValue(),negate:this.negate,expr:this.expr.debugValue(),cond:this.cond.debugValue()}]}reverse(){return new wt(this.expr.reverse(),this.cond.reverse(),this.negate)}}class wt extends Et{constructor(){super(...arguments),this.tag=gt.LOOK_BACK}evalREString(){return`(?<${this.negate?"!":"="}${this.cond.toString})${this.expr.toString}`}debugValue(){return["LookBack",{...super.debugValue(),negate:this.negate,expr:this.expr.debugValue(),cond:this.cond.debugValue()}]}reverse(){return new Ct(this.expr.reverse(),this.cond.reverse(),this.negate)}}class vt extends bt{constructor(t,e=1,s=1,n=!0){super(),this.expr=t,this.minCount=e,this.maxCount=s,this.greedy=n,this.tag=gt.QUANT}get isUnlimited(){return this.maxCount<0||this.maxCount==l}get isVariable(){return this.minCount!=this.maxCount||!this.expr.isVariable}reverse(){return new vt(this.expr.reverse(),this.minCount,this.maxCount,this.greedy)}evalREString(){let t="*";return 1==this.minCount&&this.isUnlimited?t="+":0==this.minCount&&this.isUnlimited?t="*":0==this.minCount&&1==this.maxCount?t="?":1==this.minCount&&1==this.maxCount||(t=this.minCount==this.maxCount?`{${this.minCount}}`:`{${this.minCount},${this.isUnlimited?"":this.maxCount}}`),`${this.expr.toString}${t}`}debugValue(){let t="*";return 1==this.minCount&&this.isUnlimited?t=this.greedy?"+?":"+":0==this.minCount&&this.isUnlimited?t=this.greedy?"*?":"*":0==this.minCount&&1==this.maxCount?t=this.greedy?"??":"?":1==this.minCount&&1==this.maxCount||(t=this.minCount==this.maxCount?`{${this.minCount}}`+(this.greedy?"?":""):`{${this.minCount},${this.maxCount}}`+(this.greedy?"?":"")),[t,super.debugValue(),this.expr.debugValue()]}}class _t extends bt{constructor(...t){super(),this.tag=gt.CAT,this.children=[];for(const e of t)this.add(e)}get isVariable(){for(const t of this.children)if(t.isVariable)return!0;return!1}evalREString(){const t=this.children.map(t=>t.toString).join("");return this.children.length>1?"("+t+")":t}reverse(){const t=this.children.map(t=>t.reverse());return t.reverse(),new _t(...t)}add(t){if(t.tag!=gt.CAT||t.groupIndex>=0)this.children.push(t);else for(const e of t.children)this.add(e);return this}debugValue(){return["Cat",{...super.debugValue()},this.children.map(t=>t.debugValue())]}}class xt extends bt{constructor(...t){super(),this.tag=gt.UNION,this.options=[];for(const e of t)this.add(e)}get isVariable(){for(const t of this.options)if(t.isVariable)return!0;return!1}evalREString(){const t=this.options.map(t=>t.toString).join("|");return this.options.length>1?"("+t+")":t}reverse(){const t=this.options.map(t=>t.reverse());return new xt(...t)}add(t){if(t.tag!=gt.UNION||t.groupIndex>=0)this.options.push(t);else for(const e of t.options)this.add(e);return this}debugValue(){return["Union",{...super.debugValue()},this.options.map(t=>t.debugValue())]}}!function(t){t[t.AnyChar=1]="AnyChar",t[t.SingleChar=2]="SingleChar",t[t.CharRange=3]="CharRange",t[t.PropertyEscape=4]="PropertyEscape",t[t.CharClass=5]="CharClass",t[t.Union=6]="Union",t[t.Intersection=7]="Intersection"}(mt||(mt={}));class Nt extends bt{constructor(t,e=!1){super(),this.op=t,this.neg=e,this.tag=gt.CHAR}match(t){const e=this.matchChar(t);return e&&!this.neg||this.neg&&!e}reverse(){return this}debugValue(){return this.toString+this.modifiers}}class At extends Nt{constructor(t,e=!1,s=[]){super(t,e),this.op=t,this.neg=e,this.args=s}static Any(t=!1){return new At(mt.AnyChar,t)}static Class(t,e=!1){return new At(mt.CharClass,e,[t])}static Single(t,e=!1){return"string"==typeof t&&(t=t.charCodeAt(0)),new At(mt.SingleChar,e,[t])}static PropertyEscape(t,e,s=!1){return"string"==typeof t&&(t=function(t){if(!((t=t.trim())in dt))throw new SyntaxError("Invalid property name: "+t);return dt[t]}(t)),"string"==typeof e&&(e=function(t){if(!((t=t.trim())in ft))throw new SyntaxError("Invalid property value: "+t);return ft[t]}(e)),new At(mt.PropertyEscape,s,[t,e])}matchChar(t){const e=this.args;switch(this.op){case mt.SingleChar:return t==this.args[0];case mt.CharClass:return ct[e[0]].matches(t,!1);case mt.PropertyEscape:throw new Error("Property Escape Matching - TBD");default:throw new Error("Custom Chars - TBD i: "+this.op)}return!1}compareTo(t){if(this.op!=t.op)return this.op-t.op;for(let e=0;e<this.args.length&&e<t.args.length;e++)if(this.args[e]!=t.args[e])return this.args[e]-t.args[e];return this.args.length-t.args.length}evalREString(){return this.op==mt.AnyChar?".":this.op==mt.SingleChar?(t=this.args[0],String.fromCharCode(t).replace("\n","\\n").replace("\0","\\0").replace("\r","\\r").replace("\t","\\t").replace("\f","\\f").replace("\b","\\b")):this.op==mt.CharClass?ct[this.args[0]].reString(this.neg):this.op==mt.PropertyEscape?this.neg?"\\P{":"\\p{}":"Custom "+this.args.join(" ");var t}}class Tt extends Nt{constructor(t,e=!1,s=[]){super(t,e),this.op=t,this.neg=e,this.chars=s}compareTo(t){if(this.op!=t.op)return this.op-t.op;for(let e=0;e<this.chars.length&&e<t.chars.length;e++){const s=this.chars[e].compareTo(t.chars[e]);if(0!=s)return s}return this.chars.length-t.chars.length}matchChar(t){const e=this.chars;switch(this.op){case mt.CharRange:return t>=e[0].args[0]&&t<=e[1].args[0];case mt.Union:for(let s=0;s<e.length;s++)if(e[s].match(t))return!0;return!1;case mt.Intersection:for(let s=0;s<e.length;s++)if(!e[s].match(t))return!1;return!0;default:throw new Error("Custom CharGroup - TBD i: "+this.op)}return!1}evalREString(){const t=this.chars.map(t=>t.debugValue()).join("");return this.op==mt.CharRange?`${this.chars[0].toString}-${this.chars[1].toString}`:this.op==mt.Union||this.op==mt.Intersection?t.length>1?(this.neg?"[^":"[")+t+"]":t:"Custom "+this.chars.join(" ")}static Range(t,e,s=!1){return new Tt(mt.CharRange,s,[t,e])}static Union(t=!1,e){return new Tt(mt.Union,t,e)}static Intersection(t=!1,e){return new Tt(mt.Intersection,t,e)}}class It extends bt{constructor(t,e=!1){super(),this.name=t,this.reversed=e,this.tag=gt.VAR}reverse(){return new It(this.name,!this.reversed)}evalREString(){return"<"+this.name+">"}debugValue(){return["V:"+this.name,{...super.debugValue()}]}}class Ot extends bt{constructor(t,e=!1){super(),this.name=t,this.reversed=e,this.tag=gt.BACK_NAMED_REF}reverse(){return new Ot(this.name,!this.reversed)}evalREString(){return"\\k<"+this.name+">"}debugValue(){return{...super.debugValue,BackRef:this.name}}}class Rt extends bt{constructor(t,e=!1){super(),this.num=t,this.reversed=e,this.tag=gt.BACK_NUM_REF}reverse(){return new Rt(this.num,!this.reversed)}evalREString(){return"\\"+this.num}debugValue(){return"\\"+this.num}}class kt{constructor(t,e){this.expr=t,this.skip=!1,e=e||{},this.tag=e.tag||null,0==e.priority?this.priority=0:this.priority=e.priority||10,0==e.matchIndex?this.matchIndex=0:this.matchIndex=e.matchIndex||-1,this.skip=e.skip||!1,this.activeStates=e.activeStates||null}stateCanActivate(t){return null==this.activeStates||0==this.activeStates.size||this.activeStates.has("*")||this.activeStates.has(t)}get needsSpecificStates(){return null!=this.activeStates&&this.activeStates.size>0&&!this.activeStates.has("*")}}function Lt(t){return"\r"==t||"\n"==t||"\u2028"==t||"\u2029"==t}class Mt{constructor(t=10,e=-1,s=-1,n=-1){this.priority=t,this.matchIndex=e,this.start=s,this.end=n,this.groups=[],this.positions=[]}}!function(t){t[t.Any=0]="Any",t[t.AnyNonNL=1]="AnyNonNL",t[t.Char=2]="Char",t[t.CIChar=3]="CIChar",t[t.Match=4]="Match",t[t.Noop=5]="Noop",t[t.Save=6]="Save",t[t.Split=7]="Split",t[t.Jump=8]="Jump",t[t.Begin=9]="Begin",t[t.RBegin=10]="RBegin",t[t.End=11]="End",t[t.StartingChar=12]="StartingChar",t[t.EndingChar=13]="EndingChar",t[t.MLStartingChar=14]="MLStartingChar",t[t.MLEndingChar=15]="MLEndingChar",t[t.StartOfWord=16]="StartOfWord",t[t.EndOfWord=17]="EndOfWord",t[t.GroupStart=18]="GroupStart",t[t.GroupEnd=19]="GroupEnd",t[t.EnsureState=20]="EnsureState"}(pt||(pt={}));class Pt{constructor(t="INITIAL",e=!0){this.startCondition=t,this.scIsInclusive=e,this.instrs=[],this.stateMapping=new Map,this.registerState("INITIAL"),this.registerState(t)}get length(){return this.instrs.length}registerState(t){return this.stateMapping.has(t)||this.stateMapping.set(t,this.stateMapping.size),this.stateMapping.get(t)||-1}add(t,e=null,...s){const n=new Bt(t,e).add(...s);return n.offset=this.instrs.length,this.instrs.push(n),n}static with(t){const e=new Pt;return t(e),e}debugValue(t=Ut){return t?this.instrs.map((e,s)=>e.comment.trim().length>0?`L${s}: ${t(e)} # ${e.comment}`:`L${s}: ${t(e)}`):this.instrs.map((t,e)=>`L${e}: ${t.debugValue}`)}}class Bt{constructor(t,e=null){this.opcode=t,this.char=e,this.offset=0,this.comment="",this.args=[],this.char=e}add(...t){return this.args.push(...t),this}get debugValue(){let t=this.comment.trim();return t.length>0&&(t=" # "+t),`${this.opcode} ${this.args.join(" ")} ${this.char||""} ${t}`}}class $t{constructor(t=0,e=0){this.offset=t,this.gen=e,this.parentId=-1,this.id=0,this.priority=0,this.groups=[],this.positions=[],this.registers={}}regIncr(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);this.registers[t]++}regAcquire(t){if(t in this.registers)throw new Error(`Register at offset ${t} already acquired. Release it first`);this.registers[t]=0}regRelease(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);delete this.registers[t]}regValue(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);return this.registers[t]}}class Dt{getState(){return this.currState}setState(t){this.currState=t}constructor(t,e=0,s=-1,n=!0,r={}){this.prog=t,this.start=e,this.end=s,this.forward=n,this.threadCounter=0,this.currThreads=[],this.nextThreads=[],this.startPos=0,this.currState=0,this.gen=0,this.genForOffset={},s<0&&(s=t.length-1),this.end=s}savePosition(t,e,s){for(;t.positions.length<=e;)t.positions.push(-1);t.positions[e]=s}jumpBy(t,e=1){return this.jumpTo(t,t.offset+e)}jumpTo(t,e){const s=new $t(e,this.gen);return s.id=t.id,s.parentId=t.parentId,s.priority=t.priority,s.positions=t.positions,s.groups=t.groups,s.registers=t.registers,s}forkTo(t,e){const s=new $t(e,this.gen);return s.id=++this.threadCounter,s.parentId=t.id,s.priority=t.priority,s.positions=[...t.positions],s.groups=[...t.groups],s.registers={...t.registers},s}startGroup(t,e,s){const n=this.forkTo(t,t.offset+1);return n.groups.push([e,s]),n}endGroup(t,e,s){const n=this.forkTo(t,t.offset+1);return n.groups.push([-e,s]),n}addThread(t,e,s,n=0){if(t.offset<this.start||t.offset>this.end||this.genForOffset[t.offset-this.start]==this.gen)return;this.genForOffset[t.offset-this.start]=this.gen;const r=this.prog.instrs[t.offset];let i,o,a;const l=r.opcode;switch(l){case pt.Jump:a=this.jumpTo(t,r.args[0]),this.addThread(a,e,s,n);break;case pt.Split:for(let i=0;i<r.args.length;i++){const o=r.args[i],a=0==i?this.jumpTo(t,o):this.forkTo(t,o);this.addThread(a,e,s,n)}break;case pt.Save:a=this.jumpTo(t,t.offset+1),this.savePosition(a,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case pt.GroupStart:a=this.startGroup(t,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case pt.GroupEnd:a=this.endGroup(t,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case pt.StartingChar:case pt.MLStartingChar:o=this.prevCh(s),(0==s.index||l==pt.MLStartingChar&&Lt(o))&&this.addThread(this.jumpBy(t,1),e,s,n);break;case pt.EndingChar:case pt.MLEndingChar:i=this.nextCh(s),(""==i||l==pt.MLEndingChar&&Lt(i))&&this.addThread(this.jumpBy(t,1),e,s,n);break;case pt.StartOfWord:case pt.EndOfWord:break;case pt.RBegin:{const[i,o,a]=r.args,l=2*(1+i),h=t.positions[l],[u,c]=this.recurseMatch(s,h-1,r.offset+1,a,!1,1==o);u&&this.addThread(this.jumpTo(t,a+1),e,s,n)}break;case pt.Begin:const[h,u,c]=r.args;if(1==h)this.tracer&&this.tracer.threadQueued(t,s.index),e.push(t);else{const[i,o]=this.recurseMatch(s,s.index+1,r.offset+1,c,!0,1==u);i&&this.addThread(this.jumpTo(t,c+1),e,s,n)}break;case pt.EnsureState:const d=r.args;for(const r of d)if(this.currState==r){this.addThread(this.jumpBy(t,1),e,s,n);break}break;default:this.tracer&&this.tracer.threadQueued(t,s.index),e.push(t)}}matchCurrPos(t,e,s=!1){return s?e.match(t.currChCodeLower)||e.match(t.currChCodeUpper):e.match(t.currChCode)}hasMore(t){return this.forward?t.hasMore:t.index>=0}nextCh(t){const e=t.index+(this.forward?1:-1);return t.charAt(e)}prevCh(t){return t.charAt(t.index-(this.forward?1:-1))}match(t){if(this.end<this.start)return null;this.startMatching(t);let e=null;for(;this.currThreads.length>0;)e=this.stepChar(t,e);return null!=e&&(t.index=e.end),e}recurseMatch(t,e,s,n,r=!0,i=!1){const o=t.index;if(!t.canAdvance(r?1:-1))return[i,-1];t.index=e;const a=new Dt(this.prog,s,n,r).match(t),l=t.index;return t.index=o,[null!=a&&!i||null==a&&i,l]}startMatching(t){this.currThreads=[],this.nextThreads=[],this.gen++,this.addThread(new $t(this.start,this.gen),this.currThreads,t),this.startPos=t.index}stepChar(t,e=null){this.gen++;for(let s=0;s<this.currThreads.length;s++){const n=this.currThreads[s],r=this.stepThread(t,n);if(null!=r&&(null==e||r.priority>e.priority||r.priority==e.priority&&r.end>e.end)){e=r;break}}return this.hasMore(t)&&t.advance(this.forward?1:-1),this.currThreads=this.nextThreads,this.nextThreads=[],e}stepThread(t,e){this.tracer&&this.tracer.threadStepped(e,t.index,this.gen);let s=null;const n=this.prog.instrs[e.offset],r=n.opcode,i=(n.args,this.forward?1:-1);let o=!1;switch(r){case pt.RBegin:throw new Error("Invalid state. Reverse matches must be handled in addThread");case pt.Begin:const[i,l,h]=n.args;a(1==i,"Plain lookahead cannot be here");const[u,c]=this.recurseMatch(t,t.index,n.offset+1,h,!0,1==l);u&&this.addThread(this.jumpTo(e,h+1),this.nextThreads,t);break;case pt.End:const d=new Mt(-1,-1,this.startPos,t.index);return d.groups=e.groups,d.positions=e.positions,d;case pt.Match:if(t.index>this.startPos){const r=n.args[0],i=n.args[1];s=new Mt,s.start=this.startPos,s.end=t.index,s.priority=r,s.matchIndex=i,s.groups=e.groups,s.positions=e.positions}break;case pt.Char:case pt.CIChar:this.hasMore(t)&&(o=this.matchCurrPos(t,n.char,r==pt.CIChar));break;case pt.AnyNonNL:case pt.Any:this.hasMore(t)&&(o=r==pt.Any||!Lt(t.currCh))}return o&&this.addThread(this.jumpBy(e,1),this.nextThreads,t,i),s}}function Ut(t){switch(t.opcode){case pt.Match:return`Match ${t.args[0]} ${t.args[1]}`;case pt.Char:case pt.CIChar:{let e=`${pt[t.opcode].toString()} `;return e+=`${t.char.debugValue()}`,e}case pt.Any:return".";case pt.AnyNonNL:return"NL.";case pt.StartingChar:return"^";case pt.MLStartingChar:return"NL^";case pt.EndingChar:return"$NL";case pt.MLEndingChar:return"$NL_MultiLine";case pt.Save:return`Save ${t.args[0]}`;case pt.GroupStart:return`GroupStart ${t.args[0]}`;case pt.GroupEnd:return`GroupEnd ${t.args[0]}`;case pt.Split:return`Split ${t.args.join(", ")}`;case pt.Jump:return`Jump ${t.args[0]}`;case pt.Begin:return`Begin ${t.args.join(" ")}`;case pt.RBegin:return`RBegin ${t.args.join(" ")}`;case pt.End:return`End ${t.args.join(" ")}`;case pt.EnsureState:return`EnsureState ${t.args.join(" ")}`;default:throw new Error("Invalid Opcode: "+t.opcode)}}class Ft{constructor(t,e=null){this.regexResolver=t,this.listener=e,this.emitGroups=!1,this.emitPosition=!0}compile(t){const e=new Pt,s=t.length<=1?new Bt(pt.Split):e.add(pt.Split,null);return t.forEach((t,n)=>{s.add(e.instrs.length);const r=null!=t.expr.ignoreCase&&t.expr.ignoreCase,i=null==t.expr.dotAll||t.expr.dotAll,o=null==t.expr.multiline||t.expr.multiline;if(t.needsSpecificStates&&null!=t.activeStates){const s=e.add(pt.EnsureState,null);t.activeStates.forEach(t=>{const n=e.registerState(t);s.add(n)})}this.compileExpr(t.expr,e,r,i,o),e.add(pt.Match,null).add(t.priority,t.matchIndex>=0?t.matchIndex:n)}),e}compileExpr(t,e,s,n,r){const i=e.length,o=e.length;if(t.groupIndex>=0&&(this.emitPosition&&e.add(pt.Save).add(2*(1+t.groupIndex)),this.emitGroups&&e.add(pt.GroupStart).add(1+t.groupIndex)),t.tag==gt.CHAR)this.compileChar(t,e,s,n,r);else if(t.tag==gt.START_OF_INPUT){const s=null==t.multiline?r:t.multiline;e.add(s?pt.MLStartingChar:pt.StartingChar)}else if(t.tag==gt.END_OF_INPUT){const s=null==t.multiline?r:t.multiline;e.add(s?pt.MLEndingChar:pt.EndingChar)}else if(t.tag==gt.START_OF_WORD)e.add(pt.StartOfWord);else if(t.tag==gt.END_OF_WORD)e.add(pt.EndOfWord);else if(t.tag==gt.CAT)this.compileCat(t,e,s,n,r);else if(t.tag==gt.UNION)this.compileUnion(t,e,s,n,r);else if(t.tag==gt.QUANT)this.compileQuant(t,e,s,n,r);else if(t.tag==gt.VAR)this.compileVar(t,e,s,n,r);else if(t.tag==gt.BACK_NAMED_REF)this.compileBackNamedRef(t,e,s,n,r);else if(t.tag==gt.BACK_NUM_REF)this.compileBackNumRef(t,e,s,n,r);else if(t.tag==gt.LOOK_AHEAD)this.compileLookAhead(t,e,s,n,r);else{if(t.tag!=gt.LOOK_BACK)throw new Error("Regex Type not yet supported: "+t.tag);this.compileLookBack(t,e,s,n,r)}return t.groupIndex>=0&&(this.emitGroups&&e.add(pt.GroupEnd).add(1+t.groupIndex),this.emitPosition&&e.add(pt.Save).add(2*(1+t.groupIndex)+1)),this.listener&&e.length>o&&this.listener(t,e,o,e.length-o),e.length-i}compileChar(t,e,s,n,r){t.op==mt.AnyChar?e.add(n?pt.Any:pt.AnyNonNL):e.add(s?pt.CIChar:pt.Char).char=t}compileCat(t,e,s,n,r){for(const i of t.children)this.compileExpr(i,e,s,n,r)}compileBackNumRef(t,e,s,n,r){throw new Error("BackNumRef Not Implemented")}compileBackNamedRef(t,e,s,n,r){throw new Error("BackNameRef Not Implemented")}compileVar(t,e,s,n,r){const i=t.name.trim(),o=this.regexResolver?this.regexResolver(i):null;if(null==o)throw new Error(`Cannot find expression: ${i}`);this.compileExpr(o,e,s,n,r)}compileUnion(t,e,s,n,r){const i=e.add(pt.Split),o=[];for(let a=0;a<t.options.length;a++)i.add(e.length),this.compileExpr(t.options[a],e,s,n,r),a<t.options.length-1&&o.push(e.add(pt.Jump));for(const t of o)t.add(e.length)}compileQuant(t,e,s,n,r){if(0==t.minCount&&t.maxCount==l)this.compileAtleast0(t.expr,e,t.greedy,s,n,r);else if(1==t.minCount&&t.maxCount==l)this.compileAtleast1(t.expr,e,t.greedy,s,n,r);else if(0==t.minCount&&1==t.maxCount)this.compileOptional(t.expr,e,t.greedy,s,n,r);else{for(let i=0;i<t.minCount;i++)this.compileExpr(t.expr,e,s,n,r);if(t.isUnlimited)this.compileAtleast0(t.expr,e,t.greedy,s,n,r);else for(let i=t.minCount;i<t.maxCount;i++)this.compileOptional(t.expr,e,t.greedy,s,n,r)}}compileAtleast1(t,e,s=!0,n,r,i){const o=e.length;this.compileExpr(t,e,n,r,i);const a=e.add(pt.Split),l=e.length;s?a.add(o,l):a.add(l,o)}compileAtleast0(t,e,s,n,r,i){const o=e.add(pt.Split),a=o.offset,l=e.length;this.compileExpr(t,e,n,r,i),e.add(pt.Jump).add(a);const h=e.length;s?o.add(l,h):o.add(h,l)}compileOptional(t,e,s,n,r,i){const o=e.add(pt.Split),a=e.length;this.compileExpr(t,e,n,r,i);const l=e.length;s?o.add(a,l):o.add(l,a)}compileLookAhead(t,e,s,n,r){this.compileExpr(t.expr,e,s,n,r);const i=e.add(pt.Begin).add(0,t.negate?1:0);this.compileExpr(t.cond,e,s,n,r);const o=e.add(pt.End).add(i.offset);i.add(o.offset)}compileLookBack(t,e,s,n,r){this.compileExpr(t.expr,e,s,n,r),a(t.expr.groupIndex>=0,"LookBack Assertion requires expression to have a group Index");const i=e.add(pt.RBegin).add(t.expr.groupIndex,t.negate?1:0);this.compileExpr(t.cond.reverse(),e,s,n,r);const o=e.add(pt.End).add(i.offset);i.add(o.offset)}}class jt extends Error{constructor(t,e,s,n,r=null){super(t),this.offset=e,this.length=s,this.type=n,this.value=r,this.name="TokenizerError",Object.setPrototypeOf(this,new.target.prototype)}}class Vt extends Error{constructor(t,...e){super(`Found Token: ${t?.tag||"EOF"} (${t?.value||""}), Expected: ${e.join(", ")}`),this.foundToken=t,this.name="UnexpectedTokenError",this.expectedTokens=e}}class Gt{constructor(t=!0){this.forward=t,this.index=0}advance(t=1){const e=this.forward?this.index+t:this.index-t;return this.index=e,!0}canAdvance(t=1){const e=this.forward?this.index+t:this.index-t;return this.hasIndex(e)}get hasMore(){const t=this.forward?this.index:this.index-1;return this.hasIndex(t)}get currCh(){return this.charAt(this.index)}get prevCh(){return this.charAt(this.index-(this.forward?1:-1))}get nextCh(){const t=this.index+(this.forward?1:-1);return this.charAt(t)}get currChCode(){return this.hasMore?this.currCh.charCodeAt(0):-1}get currChCodeLower(){return this.hasMore?this.currCh.toLowerCase().charCodeAt(0):-1}get currChCodeUpper(){return this.hasMore?this.currCh.toUpperCase().charCodeAt(0):-1}charCodeAt(t){return this.hasIndex(t)?this.charAt(t).charCodeAt(0):-1}charCodeAtLower(t){return this.hasIndex(t)?this.charAt(t).toLowerCase().charCodeAt(0):-1}charCodeAtUpper(t){return this.hasIndex(t)?this.charAt(t).toUpperCase().charCodeAt(0):-1}}class zt extends Gt{constructor(t,e=!0){super(e),this.forward=e,this._rawInput=t,this.input=[...t]}push(t){this._rawInput+=t,this.input.push(...t)}substring(t,e){return this._rawInput.substring(t,e)}hasIndex(t){return t>=0&&t<this.input.length}charAt(t){return t<0||t>=this.input.length?"":this.input[t]}}class Wt{static advanceAfter(t,e,s=!0){let n=Wt.advanceTo(t,e,s);return n>=0&&(n+=e.length,t.index=n),n}static advanceTo(t,e,s=!0){const n=t.index;for(;t.hasMore;){const n=t.index;if(Wt.matches(t,e)){const e=t.index;t.index=n;let r=0;if(s)for(let s=e-1;s>=0&&"\\"==t.charAt(s);s--)r++;if(r%2==0)return t.index}t.advance(1)}throw t.index=n,new Error(`Unexpected end of input before (${e})`)}static matches(t,e,s=!0){const n=t.index;let r=0,i=!0;for(;r<e.length;r++){if(e[r]!=t.currCh){i=!1;break}t.advance(1)}return s&&i||(t.index=n),i}}class Kt{constructor(t,e,s,n){this.tag=t,this.matchIndex=e,this.start=s,this.end=n,this.id=Kt.idCounter++,this.value=null,this.groups={},this.positions={},this.state=0,this.lookahead=1,this.lookback=1}isOneOf(...t){for(const e of t)if(this.tag==e)return!0;return!1}}Kt.idCounter=0;class Ht{constructor(t,e){this.nextToken=t,this.tokenizerContext=e,this.buffer=[]}next(t){const e=this.peek(t);return null!=e&&this.consume(),e}peek(t,e=0){for(;this.buffer.length<=e;){const e=this.nextToken(t,this.tokenizerContext);if(null==e)return null;this.buffer.push(e)}return this.buffer[e]}match(t,e,s=!1,n=!0,r){const i=this.peek(t);if(null!=i){if(!e(i)){if(s)throw new Vt(i);return null}r&&null!=r&&r(i),n&&this.consume()}else if(s)throw new jt("Unexpected end of input",-1,0,"UnexpectedEndOfInput");return i}consume(){this.buffer.splice(0,1)}consumeIf(t,...e){return this.match(t,t=>t.isOneOf(...e))}expectToken(t,...e){return this.match(t,t=>t.isOneOf(...e),!0,!0)}ensureToken(t,...e){return this.match(t,t=>t.isOneOf(...e),!0,!1)}nextMatches(t,...e){const s=this.peek(t);if(null==s)return null;for(const t of e)if(s.tag==t)return s;return null}}class qt{constructor(){this.value=-1}next(){return++this.value}get current(){return this.value}}function Qt(t){return" "==t||"\t"==t||"\n"==t||"\r"==t}class Jt{constructor(t,e){this.pattern=t,this.counter=new qt,this.unicode=e?.unicode||!1}reduceLeft(t){const e=1==t.length?t[0]:new _t(...t);return t.splice(0),e}throwError(t){throw new SyntaxError(`Error in JS RE '${this.pattern}': ${t}`)}parse(t=0,e=-1){const s=this.pattern,n=[];for(e<0&&(e=s.length-1);t<=e;){const r=s[t];if("."==r)n.push(At.Any()),t++;else if("\\"==r&&s[t+1]>="1"&&s[t+1]<="9"){t++;let r="";for(;t<=e&&s[t]>="0"&&s[t]<="9";)r+=s[t++];const i=parseInt(r);i>this.counter.current+1&&this.throwError("Invalid reference: "+i),n.push(new Rt(i))}else if("\\"==r&&"k"==s[t+1]&&"<"==s[t+2]){let r=t+=3;for(;r<=e&&">"!=s[r];)r++;r>e&&this.throwError("Expected '>' found EOI");const i=s.substring(t,r);""==i.trim()&&this.throwError("Expected name"),n.push(new Ot(i)),t=r+1}else if("["==r){let r=t+1;for(;r<=e&&"]"!=s[r];)"\\"==s[r]&&r++,r++;r>e&&this.throwError("Expected ']' found EOI"),n.push(this.parseCharGroup(t+1,r-1)),t=r+1}else if("^"==r)n.push(new yt),t++;else if("$"==r)n.push(new St),t++;else if("|"==r){if(t+1<=e){const s=this.reduceLeft(n),r=this.parse(t+1,e);return new xt(s,r)}t=e+1}else if("("==r)t=this.parseGroup(n,t,e);else if(")"==r||"]"==r||"}"==r)this.throwError(`Unmatched ${r}. Try using \\${r}`);else if("*"==s[t]||"?"==s[t]||"+"==s[t]||"{"==s[t])t=this.parseQuant(n,t,e);else{const[s,r]=this.parseChar(t,e);n.push(s),t+=r}}return n.length,1==n.length?n[0]:new _t(...n)}parseGroup(t,e,s){let n=e+1,r=0;const i=this.pattern;for(;n<=s&&(")"!=i[n]||r>0);)"("==i[n]?r++:")"==i[n]&&r--,"\\"==i[n]&&n++,n++;if(n>s&&this.throwError("Expected ')' found EOI"),"?"==i[++e])if(":"==i[++e])t.push(this.parse(e+1,n-1));else if("<"==i[e]&&"!"!=i[e+1]&&"="!=i[e+1]){const t=this.counter.next();let r="",o=e+1;for(;o<=s&&">"!=i[o];)r+=i[o],o++;const a=this.parse(o+1,n-1);a.groupIndex=t,r.length>0&&(a.groupName=r)}else{let r=!0;"<"==i[e]&&(e++,r=!1);const o="!"==i[e++],a=this.parse(e,n-1);if(!r){const e=this.parse(n+1,s);return e.groupIndex<0&&(e.groupIndex=this.counter.next(),e.groupIsSilent=!0),t.push(new wt(e,a,o)),s+1}{t.length;const e=new Ct(this.reduceLeft(t),a,o);t.push(e)}}else{const s=this.counter.next();let r=!1;"^"==i[e]&&(r=!0,e++);let o=this.parse(e,n-1);o.groupIndex>=0&&(o=new _t(o)),o.groupIndex=s,t.push(o)}return n+1}parseCharGroup(t,e){const s=[];let n=t,r=!1;const i=this.pattern;for("^"==i[n]&&(r=!0,n++);n<=e;){const[t,r]=this.parseChar(n,e);if(n+=r,n<i.length&&"-"==i[n])if(n++,"]"==i[n]||"["==i[n])s.push(t),s.push(At.Single("-"));else if(n<=e){const[r,i]=this.parseChar(n,e);t.op==mt.SingleChar&&r.op==mt.SingleChar||this.throwError("Char range cannot start or end in a char class"),r.args[0]<t.args[0]&&this.throwError("End cannot be less than start"),s.push(Tt.Range(t,r)),n+=i}else this.throwError("Unterminated char class");else s.push(t)}return Tt.Union(r,s)}parseChar(t=0,e=0){return"\\"==this.pattern[t]?this.parseEscapeChar(t,e):this.parseSingleChar(t,e)}parseSingleChar(t=0,e=0){const s=this.pattern.charCodeAt(t);return[At.Single(s),1]}parsePropertyEscape(t=0,e=0){const s=this.pattern;s[t]+1!="{"&&this.throwError("Invalid property escape");let n=t+=2,r=-1;for(;n<=e&&"}"!=s[n];)"="==s[n]&&(r=n),n++;n>e&&this.throwError("Invalid property escape");const i=s.substring(t,n);let o="General_Category",a=i;if(r>=0){const t=i.split("=");2!=t.length&&this.throwError("Invalid property escape"),o=t[0].trim(),a=t[1].trim()}return[At.PropertyEscape(o,a),2+n+1-t]}parseEscapeChar(t=0,e=0){const s=this.pattern;a("\\"==s[t],"Expected '\\'"),++t>e&&this.throwError("Encounted unexpected end of input after \\");const n=s[t];if(this.unicode&&"p"==n||"P"==n)return this.parsePropertyEscape(t,e);switch(n){case"w":return[At.Class(st.WORD_CHAR),2];case"W":return[At.Class(st.WORD_CHAR,!0),2];case"d":return[At.Class(st.DIGITS),2];case"D":return[At.Class(st.DIGITS,!0),2];case"s":return[At.Class(st.SPACES),2];case"S":return[At.Class(st.SPACES,!0),2];case"0":return s[t+1]>="0"&&s[t+1]<="9"&&this.unicode&&this.throwError("Invalid decimal escape"),[At.Single("\0"),2];case"r":return[At.Single("\r"),2];case"n":return[At.Single("\n"),2];case"f":return[At.Single("\f"),2];case"b":return[At.Single("\b"),2];case"v":return[At.Single("\v"),2];case"t":return[At.Single("\t"),2];case"c":(this.unicode||t>=e)&&this.throwError(`Invalid char sequence at ${t}, ${e}`);const r=s.charCodeAt(t+1)%32;return[At.Single(r),3];case"x":++t>=e&&this.throwError(`Invalid hex sequence at ${t}, ${e}`);const i=s.substring(t,t+2),o=parseInt(i,16);return a(!isNaN(o),`Invalid hex sequence: '${i}'`),[At.Single(o),4];case"u":++t>e-3&&this.throwError(`Invalid unicode sequence at ${t}`);const l=s.substring(t,t+4),h=parseInt(l,16);return isNaN(h)&&this.throwError(`Invalid unicode sequence: '${l}'`),[At.Single(h),6];case"^":case"$":case".":case"*":case"+":case"?":case"\\":case"'":case'"':case"(":case")":case"[":case"]":case"{":case"}":case"|":case"/":return[At.Single(n),2];default:return this.unicode&&this.throwError("Invalid escape character: "+n),[At.Single(n),2]}}parseQuant(t,e,s){const n=this.pattern,r=n[e-1];let i=1,o=1;if("*"==n[e])i=0,o=l;else if("+"==n[e])i=Math.min(i,1),o=l;else if("?"==n[e])i=0,o=Math.max(o,1);else{if("{"!=n[e])throw new Error("Here?");{const r=n.indexOf("}",e+1);(r<=e||r>s)&&this.throwError("Unexpected end of input while looking for '}'");const a=n.substring(e+1,r).trim(),h=a.split(",").map(t=>parseInt(t.trim()));if(e=r,1==h.length){if(isNaN(h[0])){if(a.trim().length>0)return t.push(new It(a.trim())),e+1;this.throwError(`Invalid quantifier: /${a}/`)}i=o=h[0]}else 2==h.length?(i=isNaN(h[0])?0:h[0],o=isNaN(h[1])?l:h[1],i>o&&this.throwError(`Invalid Quant /${a}/: Min must be <= Max`)):h.length>2&&this.throwError(`Invalid quantifier spec: "{${a}}"`)}}t.length<=0&&this.throwError("Quantifier cannot appear before an expression");const a=t[t.length-1];a.tag!=gt.QUANT||"*"!=r&&"?"!=r&&"+"!=r&&"}"!=r||this.throwError("Nothing to repeat"),!this.unicode||a.tag!=gt.LOOK_AHEAD&&a.tag!=gt.LOOK_BACK||this.throwError("Cannot have quantifier on assertion in unicode mode");const h=t[t.length-1]=new vt(a);return h.minCount=i,h.maxCount=o,++e<=s&&"?"==n[e]&&h.greedy&&(e++,h.greedy=!1),e}}function Yt(t,e){const s=t.index;for(let n=0;n<e.length;n++){if(t.currCh!=e.charAt(n))return t.index=s,!1;t.advance(1)}return!0}class Xt{constructor(){this.counter=new qt}parse(t,e=!1,s=0){const n=[];for(;t.hasMore;){const r=t.currCh;if(Yt(t,"."))n.push(At.Any());else if(Yt(t,"^")){const t=new yt;t.multiline=!0,n.push(t)}else if(Yt(t,"$")){const t=new St;t.multiline=!0,n.push(t)}else{if(Yt(t,"|")){const r=this.reduceLeft(n),i=this.parse(t,e,s);return new xt(r,i)}if("["==r)n.push(this.parseCharGroup(t));else if("*"==r||"?"==r||"+"==r||"{"==r)this.parseQuant(t,n);else if(e&&Qt(r))t.advance(1);else if(e&&Yt(t,"/*")){for(;"*"!=t.currCh||"/"!=t.nextCh;)t.hasMore||this.throwError(t,"Unterminated comment"),t.advance(1);t.advance(2)}else{if(Yt(t,"{-}"))throw new Error("Intersection Not yet supported");if(Yt(t,"{+}"))throw new Error("Union Not yet supported");if(Yt(t,"("))if(Yt(t,"?"))if(Yt(t,"#")){for(;t.hasMore&&")"!=t.currCh;)t.advance(1);a(Yt(t,")"),"Expected ')'")}else{let r=!1,i=!1,o=e,l=!1;for(;t.hasMore&&":"!=t.currCh;)"i"==t.currCh?r=!l:"s"==t.currCh?i=!l:"x"==t.currCh?o=!l:"-"==t.currCh&&(l=!0),t.advance(1);a(Yt(t,":"),"Expected ':'");const h=this.counter.next();let u=this.parse(t,o,s+1);u.groupIndex>=0&&(u=new _t(u)),u.dotAll=i,u.ignoreCase=r,u.groupIndex=h,n.push(u),a(Yt(t,")"),"Expected ')'")}else{const r=this.counter.next();let i=this.parse(t,e,s+1);i.groupIndex>=0&&(i=new _t(i)),i.groupIndex=r,n.push(i),a(Yt(t,")"),"Expected ')'")}else{if(")"==r){0==s&&this.throwError(t,`Unmatched ${r}. Try using \\${r}`);break}if("]"==r||"}"==r)this.throwError(t,`Unmatched ${r}. Try using \\${r}`);else{if(Yt(t,"/")){const r=this.reduceLeft(n),i=this.parse(t,e,s);return new Ct(r,i,!1)}if(Yt(t,'"')){for(;'"'!=t.currCh;)t.hasMore||this.throwError(t,"Unterminated string"),n.push(this.parseChar(t));t.advance(1)}else n.push(this.parseChar(t))}}}}}return 1==n.length?n[0]:new _t(...n)}parseQuant(t,e){let s=1,n=1;if(Yt(t,"*"))s=0,n=l;else if(Yt(t,"+"))s=Math.min(s,1),n=l;else if(Yt(t,"?"))s=0,n=Math.max(n,1);else if(Yt(t,"{")){let r=!1,i="",o="";for(;t.hasMore&&"}"!=t.currCh;)","==t.currCh?r=!0:r?o+=t.currCh:i+=t.currCh,t.advance(1);t.hasMore||this.throwError(t,"Invalid property escape"),i=i.trim(),o=o.trim(),t.advance(1);const a=parseInt(i),h=parseInt(o);if(r)s=isNaN(a)?0:a,n=isNaN(h)?l:h,s>n&&this.throwError(t,`Invalid Quant /${i},${o}/: Min must be <= Max`);else if(isNaN(a)){if(i.length>0)return void e.push(new It(i));this.throwError(t,`Invalid quantifier: /${i}/`),s=n=1}else s=n=a}else this.throwError(t,"Expected '{', '*', '?' or '+', Found: "+t.currCh);e.length<=0&&this.throwError(t,"Quantifier cannot appear before an expression");const r=e[e.length-1];let i;r.tag==gt.QUANT&&r.groupIndex<0?(i=r,i.minCount=Math.min(s,i.minCount),i.maxCount=Math.max(n,i.maxCount)):(i=e[e.length-1]=new vt(r),i.minCount=s,i.maxCount=n),i.greedy&&Yt(t,"?")&&(i.greedy=!1)}parseCharGroup(t){const e=[];a(Yt(t,"["),"Expected '['");const s=Yt(t,"^");for(;"]"!=t.currCh;){const s=this.parseChar(t);if(Yt(t,"-"))if(t.hasMore)if("]"==t.currCh||"["==t.currCh)e.push(s),e.push(At.Single("-"));else{const n=this.parseChar(t);s.op==mt.SingleChar&&n.op==mt.SingleChar||this.throwError(t,"Char range cannot start or end in a char class"),n.args[0]<s.args[0]&&this.throwError(t,"End cannot be less than start"),e.push(Tt.Range(s,n))}else this.throwError(t,"Unterminated char class");else e.push(s)}return a(Yt(t,"]"),"']' expected"),Tt.Union(s,e)}parseChar(t){return"\\"==t.currCh?this.parseEscapeChar(t):this.parseSingleChar(t)}parseSingleChar(t){const e=t.currCh;return t.advance(1),At.Single(e)}parsePropertyEscape(t){a(Yt(t,"\\{"),"Invalid property escape"),t.advance(2);let e=!1,s="",n="";for(;t.hasMore&&"}"!=t.currCh;)"="==t.currCh?e=!0:e?n+=t.currCh:s+=t.currCh,t.advance(1);return t.hasMore||this.throwError(t,"Invalid property escape"),s=s.trim(),n=n.trim(),e||(n=s,s="General_Category"),t.advance(1),At.PropertyEscape(s,n)}parseEscapeChar(t){if(a(Yt(t,"\\"),"Expected '\\'"),t.hasMore||this.throwError(t,"Encounted unexpected end of input after \\"),Yt(t,"w"))return At.Class(st.WORD_CHAR);if(Yt(t,"W"))return At.Class(st.WORD_CHAR,!0);if(Yt(t,"d"))return At.Class(st.DIGITS);if(Yt(t,"D"))return At.Class(st.DIGITS,!0);if(Yt(t,"s"))return At.Class(st.SPACES);if(Yt(t,"S"))return At.Class(st.SPACES,!0);if(Yt(t,"0"))return At.Single("\0");if(Yt(t,"r"))return At.Single("\r");if(Yt(t,"n"))return At.Single("\n");if(Yt(t,"f"))return At.Single("\f");if(Yt(t,"b"))return At.Single("\b");if(Yt(t,"v"))return At.Single("\v");if(Yt(t,"t"))return At.Single("\t");if(Yt(t,"\\"))return At.Single("\\");if(Yt(t,"'"))return At.Single("'");if(Yt(t,'"'))return At.Single('"');if(Yt(t,"x")){t.hasMore||this.throwError(t,`Invalid hex sequence at ${t.index}`);const e=t.currCh+t.nextCh,s=parseInt(e,16);return a(!isNaN(s),`Invalid hex sequence: '${e}'`),t.advance(2),At.Single(s)}if(Yt(t,"u")){t.canAdvance(3)||this.throwError(t,`Invalid unicode sequence at ${t.index}`);const e=t.substring(t.index,t.index+4),s=parseInt(e,16);return isNaN(s)&&this.throwError(t,`Invalid unicode sequence: '${e}'`),t.advance(4),At.Single(s)}const e=t.currCh;return t.advance(1),At.Single(e)}reduceLeft(t){const e=1==t.length?t[0]:new _t(...t);return t.splice(0),e}throwError(t,e){throw new Error(e)}}function Zt(t,e){if("string"==typeof t){const s=new kt(ee(t,e),e);return s.pattern=t,s}if("RegExp"==t.constructor.name){const s=new kt(ee(t,e),e);return s.pattern=t.source,s}return new kt(t,e)}function te(t){const e=new Xt;try{const s=e.parse(new zt(t));return null==s.dotAll&&(s.dotAll=!1),null==s.multiline&&(s.multiline=!1),s}catch(e){throw console.log("Error in FLEX RE: ",t),e}}function ee(t,e){e=e||{};const s="string"!=typeof t,n="string"==typeof t?t:t.source;s&&(e.unicode=t.unicode);const r=new Jt(n,e).parse();return"string"!=typeof t&&(r.dotAll=t.dotAll,r.ignoreCase=t.ignoreCase,r.multiline=t.multiline),r}function se(t,...e){return te(String.raw(t,...e))}class ne{constructor(){this._prog=null,this._vm=null,this.onError=null,this.allRules=[],this.onMatchHandlers=[],this.matchHandlersByValue={},this.variables=new Map,this.compiler=new Ft(t=>{let e=this.variables.get(t)||null;if(null==e&&(e=this.findRuleByValue(t)?.expr||null),null==e)throw new Error(`Invalid regex reference: ${t}`);return e})}getVar(t){return this.variables.get(t)||null}addVar(t,e){let s=this.variables.get(t)||null;return s=null==s?e:new xt(s,e),this.variables.set(t,e),this}findRuleByValue(t){return this.allRules.find(e=>e.tag==t)||null}add(t,e,s=null){return"function"==typeof e&&(s=e,e=null),this.addRule(Zt(t,e),s)}addRule(t,e=null){return t.matchIndex=this.allRules.length,this.allRules.push(t),this.onMatchHandlers.push(e),this._prog=null,this._vm=null,this}on(t,e){return this.matchHandlersByValue[t]=e,this}get prog(){if(null==this._prog){const t=this.sortRules();this._prog=this.compiler.compile(t)}return this._prog}get vm(){return null==this._vm&&(this._vm=new Dt(this.prog)),this._vm}sortRules(){const t=this.allRules.map(t=>t);return t.sort((t,e)=>t.priority!=e.priority?e.priority-t.priority:t.matchIndex-e.matchIndex),t}}class re extends ne{constructor(){super(...arguments),this.idCounter=0}getState(){return this.vm.getState()}setState(t){this.vm.setState(t)}reset(){this.idCounter=0,this._vm&&this._vm.setState(0)}next(t,e){if(!t.hasMore)return null;const s=t.index,n=t.currCh,r=this.vm.match(t);if(null==r){let r=null;if(r=t.index==s+1?new jt(`Unexpected Character: ${n}`,s,1,"UnexpectedCharacter",n):new jt(`Unexpected Symbol: ${t.substring(s,t.index)}`,s,t.index-s,"UnexpectedLexeme"),this.onError&&(r=this.onError(r,t,s)),null!=r)throw r;return this.next(t,e)}const i=this.allRules[r.matchIndex];let o=function(t,e,s){const n=new Kt(t,e.matchIndex,e.start,e.end);for(let t=0;t<e.positions.length;t+=2)e.positions[t]>=0&&(n.positions[Math.floor(t/2)]=[e.positions[t],e.positions[t+1]]);for(const[t,s]of e.groups){const e=Math.abs(t);e in n.groups||(n.groups[e]=[]),n.groups[e].push(s)}return null!=s&&(n.value=s.substring(e.start,e.end)),n}(i.tag,r,t);o.id=this.idCounter++;let a=this.onMatchHandlers[r.matchIndex];if(a||(a=this.matchHandlersByValue[i.tag]),a){if(o=a(i,t,o,e),null==o)return this.next(t,e)}else if(i.skip)return this.next(t,e);return o}tokenize(t,e=null){const s=[];"string"==typeof t&&(t=new zt(t));let n=this.next(t,e);for(;n;){s.push(n);try{n=this.next(t,e)}catch(t){s.push({tag:"ERROR",start:t.offset,end:t.offset+t.length,value:t.message});break}}return s}}const ie=se`["]([^"\\\n]|\\.|\\\n)*["]`,oe=se`[']([^'\\\n]|\\.|\\\n)*[']`,ae=String.raw`/(.+?(?<!\\))/([imus]*)`,le=t=>"number"==typeof t?""+t:t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var he,ue,ce,de;!function(t){t.STRING="STRING",t.REGEX="REGEX",t.NUMBER="NUMBER",t.SPACES="SPACES",t.IDENT="IDENT",t.PCT_IDENT="PCT_IDENT",t.STAR="STAR",t.PLUS="PLUS",t.QMARK="QMARK",t.PIPE="PIPE",t.DOLLAR_NUM="DOLLAR_NUM",t.DOLLAR_IDENT="DOLLAR_IDENT",t.OPEN_PAREN="OPEN_PAREN",t.CLOSE_PAREN="CLOSE_PAREN",t.OPEN_BRACE="OPEN_BRACE",t.CLOSE_BRACE="CLOSE_BRACE",t.OPEN_SQ="OPEN_SQ",t.CLOSE_SQ="CLOSE_SQ",t.COMMENT="COMMENT",t.ARROW="ARROW",t.COLCOLHYPHEN="COLCOLHYPHEN",t.COLON="COLON",t.SEMI_COLON="SEMI_COLON"}(he||(he={})),function(t){t.GRAMMAR="GRAMMAR",t.DECL="DECL",t.RULE="RULE",t.PROD_NULL="PROD_NULL",t.PROD_STR="PROD_STR",t.PROD_UNION="PROD_UNION",t.PROD_NAME="PROD_NAME",t.PROD_STRING="PROD_STRING",t.PROD_NUM="PROD_NUM",t.PROD_IDENT="PROD_IDENT",t.PROD_STAR="PROD_STAR",t.PROD_PLUS="PROD_PLUS",t.PROD_OPTIONAL="PROD_OPTIONAL",t.IDENT="IDENT",t.ERROR="ERROR",t.COMMENT="COMMENT"}(ue||(ue={}));class fe{constructor(t,e){this.leftRecursive=!1,this.generatedTokenizer=new re,this.regexSyntax="js",e=e||{},this.symbolsByLabel={},this.grammar=e.grammar||new et,this.leftRecursive=!("leftRecursive"in e)||e.leftRecursive||!1,this.newSymbolCallback=e.newSymbolCallback||null,this.tokenHandlers=e.tokenHandlers||{},this.parse(t)}symbolForLabel(t){return this.symbolsByLabel[t]||null}registerSymbol(t,e){a(!(t in this.symbolsByLabel),`${t} is already registered`),this.symbolsByLabel[t]=e}ensureSymbol(t,e){let s=this.symbolForLabel(t);return null!=s||(this.newSymbolCallback&&(s=this.newSymbolCallback(t,e)||null),null==s&&(s=e?this.grammar.newTerm(t):this.grammar.newNT(t)),this.registerSymbol(t,s)),s}parse(t){const e=function(){const t=new re;return t.add(/->/,{tag:he.ARROW}),t.add(/\[/,{tag:he.OPEN_SQ}),t.add(/\]/,{tag:he.CLOSE_SQ}),t.add(/\(/,{tag:he.OPEN_PAREN}),t.add(/\)/,{tag:he.CLOSE_PAREN}),t.add(/\{/,{tag:he.OPEN_BRACE}),t.add(/\}/,{tag:he.CLOSE_BRACE}),t.add(/\*/,{tag:he.STAR}),t.add(/\+/,{tag:he.PLUS}),t.add(/\?/,{tag:he.QMARK}),t.add(/;/,{tag:he.SEMI_COLON}),t.add(/:/,{tag:he.COLON}),t.add(/\|/,{tag:he.PIPE}),t.add(/\s+/m,{tag:he.SPACES},()=>null),t.add(/\/\*.*?\*\//s,{tag:he.COMMENT},()=>null),t.add(/\/\/.*$/m,{tag:he.COMMENT},()=>null),t.add(oe,{tag:he.STRING},(t,e,s)=>(s.value=e.substring(s.start+1,s.end-1),s)),t.add(ie,{tag:he.STRING},(t,e,s)=>(s.value=e.substring(s.start+1,s.end-1),s)),t.add(ae,{tag:he.REGEX},(t,e,s)=>{const n=e.substring(s.positions[1][0],s.positions[1][1]),r=e.substring(s.positions[3][0],s.positions[3][1]);return s.value=[n,r],s}),t.add(/\d+/,{tag:he.NUMBER},(t,e,s)=>(s.value=parseInt(e.substring(s.start,s.end)),s)),t.add(/%([\w][\w\d_]*)/,{tag:he.PCT_IDENT},(t,e,s)=>(s.value=e.substring(s.start+1,s.end),s)),t.add(/\$\d+/,{tag:he.DOLLAR_NUM},(t,e,s)=>(s.value=parseInt(e.substring(s.start+1,s.end)),s)),t.add(/\$([\w][\w\d_]*)/,{tag:he.DOLLAR_IDENT},(t,e,s)=>(s.value=e.substring(s.start+1,s.end),s)),t.add(/[\w][\w\d_]*/,{tag:he.IDENT}),t}();this.tokenizer=new Ht((t,s)=>e.next(t,this),this),this.parseGrammar(new zt(t))}parseRegex(t,e,s=0,n=""){if(""==n&&(n=this.regexSyntax),"js"==n){const n=this.tokenizer.expectToken(t,he.STRING,he.NUMBER,he.REGEX);let r;if(e&&0!=e.length||(e="/"+n.value[0]+"/"+n.value[1]),n.tag==he.STRING||n.tag==he.NUMBER)r=Zt(le(n.value),{tag:e,priority:s+20});else{if(n.tag!=he.REGEX)throw new Vt(n);{let t=n.value[0];n.value[1].length>0&&(t=new RegExp(n.value[0],n.value[1])),r=Zt(t,{tag:e,priority:s+10})}}return r}{let n="";for(;t.hasMore&&"\n"!=t.currCh;)n+=t.currCh,t.advance();return n=n.trim(),e&&0!=e.length||(e="/"+n+"/"),new kt(te(n),{tag:e,priority:s})}}parseGrammar(t){let e=this.tokenizer.peek(t);for(;null!=e;){if(e.tag==he.IDENT)this.parseDecl(t);else{if(e.tag!=he.PCT_IDENT)throw new SyntaxError(`Declaration must start with IDENT or PCT_IDENT. Found: '${e.value}' instead.`);this.tokenizer.next(t),this.parseDirective(t,e.value)}e=this.tokenizer.peek(t)}}parseDirective(t,e){if("start"==e){const e=this.tokenizer.expectToken(t,he.IDENT);this.grammar.startSymbol=this.ensureSymbol(e.value,!1)}else if("resyntax"==e){const e=this.tokenizer.expectToken(t,he.IDENT);if("js"!=e.value&&"flex"!=e.value)throw new SyntaxError("Invalid regex syntax: "+e.value);this.regexSyntax=e.value}else if(e.startsWith("skip")){const s=this.parseRegex(t,"",30,e.endsWith("flex")?"flex":""),n=this.parseTokenHandler(t);n?this.generatedTokenizer.addRule(s,(t,e,s)=>(n(t,e,s,this),null)):this.generatedTokenizer.addRule(s,()=>null)}else{if(!e.startsWith("token")&&!e.startsWith("define"))throw new Error("Invalid directive: "+e);{const s=e.startsWith("define"),n=this.tokenizer.expectToken(t,he.IDENT,he.STRING);let r=n.value;n.tag!=he.STRING&&n.tag!=he.NUMBER||(r=`"${n.value}"`);const i=this.parseRegex(t,r,0,e.endsWith("flex")?"flex":"");if(s)this.generatedTokenizer.addVar(r,i.expr);else{const e=this.parseTokenHandler(t);this.generatedTokenizer.addRule(i,e),this.ensureSymbol(r,!0)}}}}parseTokenHandler(t){if(!this.tokenizer.consumeIf(t,he.OPEN_BRACE))return null;const e=this.tokenizer.expectToken(t,he.IDENT);return this.tokenizer.expectToken(t,he.CLOSE_BRACE),(t,s,n,r)=>{const i=this.tokenHandlers[e.value];if(!i)throw new Error("Handler method not found: "+e.value);return i(n,s,r)}}parseDecl(t){const e=this.tokenizer.expectToken(t,he.IDENT);if(this.tokenizer.consumeIf(t,he.ARROW,he.COLON)){const s=this.ensureSymbol(e.value,!1);if(s.isTerminal)s.isTerminal=!1;else if(s.isAuxiliary)throw new Error("NT is already auxiliary and cannot be reused.");for(const[e,n]of this.parseProductions(t,this.grammar,s))this.grammar.add(s,e,n);this.tokenizer.expectToken(t,he.SEMI_COLON)}}parseProductions(t,e,s){const n=[];for(;null!=this.tokenizer.peek(t);){const s=this.parseProd(t,e);if(n.push(s),!this.tokenizer.consumeIf(t,he.PIPE)&&this.tokenizer.nextMatches(t,he.CLOSE_SQ,he.CLOSE_PAREN,he.SEMI_COLON))break}return n}parseProd(t,e){const s=new X;for(;!this.tokenizer.nextMatches(t,he.CLOSE_PAREN,he.CLOSE_SQ,he.SEMI_COLON,he.PIPE,he.OPEN_BRACE);){let n=null;if(this.tokenizer.consumeIf(t,he.OPEN_PAREN)){const s=this.parseProductions(t,e,null);0==s.length||(n=1==s.length?s[0][0]:e.anyof(...s.map(t=>t[0]))),this.tokenizer.expectToken(t,he.CLOSE_PAREN)}else if(this.tokenizer.consumeIf(t,he.OPEN_SQ)){const s=this.parseProductions(t,e,null);0==s.length||(n=1==s.length?e.opt(s[0][0]):e.opt(e.anyof(...s.map(t=>t[0])))),this.tokenizer.expectToken(t,he.CLOSE_SQ)}else{if(!this.tokenizer.nextMatches(t,he.IDENT,he.STRING,he.NUMBER,he.REGEX))throw new Vt(this.tokenizer.peek(t));{const e=this.tokenizer.next(t);let s=e.value;if(e.tag==he.STRING||e.tag==he.NUMBER){s=`"${e.value}"`;const t=Zt(le(e.value),{tag:s,priority:20});this.generatedTokenizer.addRule(t)}else if(e.tag==he.REGEX){s="/"+e.value[0]+"/"+e.value[1];let t=e.value[0];e.value[1].length>0&&(t=new RegExp(e.value[0],e.value[1]));const n=Zt(t,{tag:s,priority:10});this.generatedTokenizer.addRule(n)}const r=this.ensureSymbol(s,!0);n=new X(r)}}if(null==n)throw new Error("Could not determine node");this.tokenizer.consumeIf(t,he.STAR)?n=e.atleast0(n,this.leftRecursive):this.tokenizer.consumeIf(t,he.PLUS)?n=e.atleast1(n,this.leftRecursive):this.tokenizer.consumeIf(t,he.QMARK)&&(n=e.opt(n)),s.extend(n)}let n=null;if(this.tokenizer.consumeIf(t,he.OPEN_BRACE)){const e=this.tokenizer.expectToken(t,he.DOLLAR_NUM,he.IDENT);n=new Z(e.value),this.tokenizer.expectToken(t,he.CLOSE_BRACE)}return[s,n]}}class ge{constructor(t,e,s,...n){this.id=t,this.sym=e,this.value=s,this.children=[],this.children=n||[]}get childCount(){return this.children.length}childAt(t){return t<0?this.children[this.children.length+t]:this.children[t]}get isTerminal(){return this.sym.isTerminal}add(t,e=-1){if(this.isTerminal)throw new Error(`Cannot add children (${t.sym.label}) to a terminal node: ${this.sym.label}`);return e<0?this.children.push(t):this.children.splice(e,0,t),this}splice(t,e,...s){return this.children.splice(t,e,...s),this}get reprString(){return this.debugValue(!1).join("\n")}debugValue(t=!0){if(t){const e=[this.sym.label];return this.value&&e.push(this.value),this.children.length>0&&e.push(this.children.map(e=>e.debugValue(t))),e}{const e=[];return this.value,e.push(null==this.value?this.sym.label:this.sym.label+" - "+this.value),this.children.forEach(s=>s.debugValue(t).forEach(t=>e.push(" "+t))),e}}}class me extends ge{constructor(){super(...arguments),this.parent=null}add(t,e=-1){return super.add(t,e),t.parent=this,this}splice(t,e,...s){for(const t of s)t.parent=this;return super.splice(t,e,...s)}}class pe{setTokenizer(t){return this.tokenbuffer=new Ht(t,null),this}getSym(t){const e=this.grammar.getSym(t.tag);if(null==e)throw new Error("Invalid token tag: "+t.tag+", Value: "+t.value);return e}}class be extends pe{parse(t,e=null){return"string"==typeof t&&(t=new zt(t)),this.parseInput(t,e)}}class ye extends Error{constructor(t,e,s=null){super(t),this.type=e,this.value=s,Object.setPrototypeOf(this,new.target.prototype)}get name(){return this.constructor.name}}(de=ce||(ce={}))[de.ACCEPT=0]="ACCEPT",de[de.SHIFT=1]="SHIFT",de[de.REDUCE=2]="REDUCE",de[de.GOTO=3]="GOTO";class Se{constructor(){this.gotoState=null,this.rule=null}toString(){return this.tag==ce.ACCEPT?"Acc":this.tag==ce.SHIFT?"S"+this.gotoState:this.tag==ce.REDUCE?"R "+this.rule.id:""+this.gotoState}equals(t){return this.tag==t.tag&&this.gotoState==t.gotoState&&this.rule==t.rule}static Shift(t){const e=new Se;return e.tag=ce.SHIFT,e.gotoState=t,e}static Reduce(t){const e=new Se;return e.tag=ce.REDUCE,e.rule=t,e}static Goto(t){const e=new Se;return e.tag=ce.GOTO,e.gotoState=t,e}static Accept(){const t=new Se;return t.tag=ce.ACCEPT,t}}class Ee{constructor(t){this.grammar=t,this.conflictActions={},this.actions={}}get hasConflicts(){return Object.keys(this.conflictActions).length>0}getActions(t,e,s=!1){let n;if(t in this.actions)n=this.actions[t];else{if(!s)return[];n=this.actions[t]={}}return e.id in n?n[e.id]:s?n[e.id]=[]:[]}addAction(t,e,s){const n=this.getActions(t,e,!0);return n.findIndex(t=>t.equals(s))<0&&n.push(s),n.length>1&&(this.conflictActions[t]=this.conflictActions[t]||{},this.conflictActions[t][e.label]=!0),this}get debugValue(){const t={};for(const e in this.actions){t[e]={};for(const s in this.actions[e]){const n=this.grammar.getSymById(s),r=this.actions[e][n.id]||[];r.length>0&&(t[e][n.label]=r.map(t=>t.toString()))}}return t}}class Ce{constructor(){this.stateStack=[],this.nodeStack=[]}push(t,e){this.stateStack.push(t),this.nodeStack.push(e)}top(t=0){return[this.stateStack[this.stateStack.length-1-t],this.nodeStack[this.nodeStack.length-1-t]]}pop(){const t=this.top();return this.stateStack.pop(),this.nodeStack.pop(),t}popN(t=1){const e=this.stateStack.length;this.stateStack.splice(e-t,t),this.nodeStack.splice(e-t,t)}get isEmpty(){return 0==this.stateStack.length||0==this.nodeStack.length}}class we extends be{constructor(t,e={}){super(),this.parseTable=t}get grammar(){return this.parseTable.grammar}parseInput(t,e){e=e||{},this.tokenbuffer.tokenizerContext=e.tokenizerContext,0!=e.buildParseTree&&(e.buildParseTree=!0),0!=e.copySingleChild&&(e.copySingleChild=!0);let s=0;const n=new Ce;n.push(0,new me(s++,this.grammar.augStartRule.nt,null));const r=this.tokenbuffer,i=this.grammar;let o=null;function l(t){if(e?.actionResolver)return e.actionResolver(t,n,r);if(t.length>1)throw new Error("Multiple actions found.");return t[0]}function h(){try{return r.peek(t)}catch(s){if(!e?.onTokenError||!e?.onTokenError(s,t))throw s;return h()}}for(;;){let u=h();if(null==u){if(n.isEmpty)break}else e.onNextToken&&(u=e.onNextToken(u));const c=null==u?i.Eof:this.getSym(u),d=null==u?null:u.value;let[f,g]=n.top();const m=this.parseTable.getActions(f,c);if(null==m||0==m.length)throw new ye(`Unexpected Token: '${c.label}'`,"UnexpectedToken",{state:f,token:u,nextSym:c});const p=l(m);if(p.tag==ce.ACCEPT)break;if(p.tag==ce.SHIFT){r.next(t);const e=new me(s++,c,d);n.push(p.gotoState,e)}else{a(null!=p.rule,"Nonterm and ruleindex must be provided for a reduction action");const t=p.rule.rhs.length;let r=new me(s++,p.rule.nt,null);if(e.buildParseTree)for(let s=t-1;s>=0;s--){const t=n.top(s)[1];if(e.beforeAddingChildNode)for(const s of e.beforeAddingChildNode(r,t))r.add(s);else null!=t&&r.add(t)}if(p.rule.action)if(p.rule.action.isFunction){const t=p.rule.action.value,s=e.ruleHandlers[t];if(!s)throw new Error("Action handler not found: "+t);r.value=s(p.rule,r,...r.children)}else r.value=r.children[p.rule.action.value-1].value;else e.onReduction?r=e.onReduction(r,p.rule):1==r.children.length&&e.copySingleChild&&(r.value=r.children[0].value);n.popN(t),[f,g]=n.top();const i=l(this.parseTable.getActions(f,p.rule.nt));a(null!=i&&null!=i.gotoState,"Top item does not have an action."),n.push(i.gotoState,r),o=r}}return o}}class ve{constructor(t,e=0){this.id=0,this.rule=t,this.position=e}advance(){return a(this.position<this.rule.rhs.length),new ve(this.rule,this.position+1)}copy(){return new ve(this.rule,this.position)}get key(){return a(!isNaN(this.rule.id),"Rule's ID is not yet set."),this.rule.id+":"+this.position}compareTo(t){let e=this.rule.id-t.rule.id;return 0==e&&(e=this.position-t.position),e}equals(t){return 0==this.compareTo(t)}get debugString(){const t=this.rule,e=this.position,s=t.rhs.syms.slice(0,e).join(" "),n=t.rhs.syms.slice(e).join(" ");return`${t.id} - ${t.nt} -> ${s} • ${n}`}}class _e{constructor(t,...e){this.id=0,this._key=null,this._lookaheads={},this._hasLookAheads=!1,this.itemGraph=t,this.values=e}copy(){const t=new _e(this.itemGraph,...this.values);return t._lookaheads={...this._lookaheads},t._hasLookAheads=this._hasLookAheads,t}addLookAhead(t,e){t.id in this._lookaheads||(this._lookaheads[t.id]=[]);for(const s of this._lookaheads[t.id])if(s==e)return!1;return this._hasLookAheads=!0,this._key=null,this._lookaheads[t.id].push(e),this._lookaheads[t.id].sort((t,e)=>t.id-e.id),!0}clearLookAheads(){this._lookaheads={}}getLookAheads(t){return this._lookaheads[t.id]||[]}get key(){return null==this._key&&(this._key=this.revalKey()),this._key}revalKey(){return this.hasLookAheads?(this.values.sort(),this.values.map(t=>t+"["+(this._lookaheads[t]||[]).map(t=>t.id).join(",")+"]").join("/")):(this.values.sort(),this.values.join("/"))}has(t){return this.values.indexOf(t)>=0}equals(t){return this.key==t.key}add(t){return this.has(t)||(this.values.push(t),this._key=null),this}get size(){return this.values.length}get debugString(){return this.debugValue.join("\n")}get hasLookAheads(){return this._hasLookAheads}get debugValue(){if(this.hasLookAheads){const t=this.values.map(t=>this.itemGraph.items.get(t));return t.sort((t,e)=>t.compareTo(e)),t.map(t=>{const e=this.getLookAheads(t).map(t=>t.label).sort((t,e)=>t.localeCompare(e)).join(", ");return e.length>0?`${t.debugString} / ( ${e} )`:t.debugString})}{const t=this.values.map(t=>this.itemGraph.items.get(t));return t.sort((t,e)=>t.compareTo(e)),t.map(t=>t.debugString)}}}class xe{constructor(t){this.grammar=t,this.gotoSets={},this.items=new W,this.itemSets=new W}startItem(){return a(null!=this.grammar.startSymbol,"Start symbol must be set"),a(null!=(this.grammar.augStartRule||null),"Grammar is not augmented"),this.items.ensure(new ve(this.grammar.augStartRule))}reset(){this.grammar.refresh(),this.gotoSets={},this.items.clear(),this.itemSets.clear(),this.startSet()}refresh(){return this.reset(),this.grammar.refresh(),this.evalGotoSets(),this}evalGotoSets(){const t=this.itemSets;for(let e=0;e<t.size;e++){const s=t.get(e);for(const t of this.grammar.allSymbols)if(t!=this.grammar.Null){const e=this.goto(s,t);e.size>0&&this.setGoto(s,t,e)}}}goto(t,e){const s=this.newItemSet();for(const n of t.values){const r=this.items.get(n),i=r.rule;r.position<i.rhs.length&&i.rhs.syms[r.position]==e&&this.advanceItemAndAdd(r,t,s)}return this.closure(s)}advanceItemAndAdd(t,e,s){const n=this.items.ensure(t.advance());s.add(n.id);for(const r of e.getLookAheads(t))s.addLookAhead(n,r)}newItemSet(...t){return new _e(this,...t.map(t=>t.id))}get size(){return this.itemSets.size}ensureGotoSet(t){return t.id in this.gotoSets||(this.gotoSets[t.id]={}),this.gotoSets[t.id]}setGoto(t,e,s){this.ensureGotoSet(t)[e.id]=s}getGoto(t,e){return(this.gotoSets[t.id]||{})[e.id]||null}forEachGoto(t,e){const s=this.gotoSets[t.id]||{};for(const t in s)if(0==e(this.grammar.getSymById(t),s[t]))break}gotoSetFor(t){return this.gotoSets[t.id]||{}}get debugValue(){const t={};return this.itemSets.entries.forEach(e=>{t[e.id]={items:[],goto:{}},t[e.id].items=e.debugValue;const s=this.gotoSets[e.id];for(const n in s){const r=this.grammar.getSymById(n);t[e.id].goto=t[e.id].goto||{},t[e.id].goto[r.label]=s[n].id}}),t}}class Ne extends xe{startSet(){const t=this.startItem(),e=this.newItemSet(t);return this.closure(e)}closure(t){const e=new _e(this,...t.values);for(let t=0;t<e.values.length;t++){const s=e.values[t],n=this.items.get(s),r=n.rule;if(n.position<r.rhs.length){const t=r.rhs.syms[n.position];if(!t.isTerminal)for(const s of this.grammar.rulesForNT(t)){const t=this.items.ensure(new ve(s,0));e.add(t.id)}}}return 0==e.size?e:this.itemSets.ensure(e)}}class Ae extends xe{startSet(){const t=this.startItem(),e=this.newItemSet(t);return e.addLookAhead(t,this.grammar.Eof),this.closure(e)}closure(t){const e=t.copy();for(let t=0;t<e.values.length;t++){const s=e.values[t],n=this.items.get(s);if(n.position>=n.rule.rhs.length)continue;const r=n.rule.rhs,i=r.syms[n.position];if(!i.isTerminal)for(const t of e.getLookAheads(n)){const s=r.copy().append(t);this.grammar.firstSets.forEachTermIn(s,n.position+1,t=>{if(null!=t){const s=this.grammar.rulesForNT(i);for(const n of s){const s=this.items.ensure(new ve(n,0));e.add(s.id),e.addLookAhead(s,t)}}})}}return 0==e.size?e:this.itemSets.ensure(e)}}function Te(t){const e=function(t){const e=new Ne(t).refresh();for(const s of e.itemSets.entries)Ie(t,e,s);return e}(t);return[Oe(e,t),e]}function Ie(t,e,s){for(const n of s.values){const r=e.items.get(n),i=r.rule;r.position>=i.rhs.length&&t.followSets.forEachTerm(i.nt,t=>{null!=t&&(a(t.isTerminal),s.addLookAhead(r,t))})}}function Oe(t,e){const s=new Ee(e);for(const n of t.itemSets.entries){for(const r of n.values){const i=t.items.get(r),o=i.rule;if(i.position<o.rhs.length){const e=o.rhs.syms[i.position];if(e.isTerminal){const r=t.getGoto(n,e);r&&s.addAction(n.id,e,Se.Shift(r.id))}}else if(!o.nt.equals(e.augStartRule.nt)){const t=n.getLookAheads(i);for(const e of t)s.addAction(n.id,e,Se.Reduce(o))}}t.forEachGoto(n,(t,e)=>{null==t||t.isTerminal||s.addAction(n.id,t,Se.Goto(e.id))});const r=t.items.ensure(new ve(e.augStartRule,1));n.addLookAhead(r,e.Eof),n.has(r.id)&&s.addAction(n.id,e.Eof,Se.Accept())}return s}function Re(t,e,s,n,r){function i(t,e,n,o){if(e<0)a(null!=(s.gotoSets[n][t.nt.id]||null),"Transition on rule.nt missing from start state"),o.add(n);else{const s=t.rhs.syms[e],l=r[n][s.id]||null;a(null!=l,"Prev set should not be null"),l.forEach(s=>i(t,e-1,s,o))}}n.clearLookAheads();for(const r of n.values){const o=s.items.get(r),l=o.rule;if(o.position>=l.rhs.length){const s=new Set;i(l,l.rhs.length-1,n.id,s),s.forEach(s=>{const r=`[${s}:${l.nt.label}]`,i=e.getSym(r);a(null!=i,"Augmented grammar symbol [p:A] not found"),e.followSets.forEachTerm(i,s=>{if(null!=s&&s!=e.Eof){a(s.isTerminal);const e=s.label.substring(s.label.indexOf(":")+1,s.label.length-1).trim(),r=t.getSym(e);a(null!=r,`T (${e}) in [r:T] cannot be null`),n.addLookAhead(o,r)}})})}}}const ke=Symbol.for("yaml.alias"),Le=Symbol.for("yaml.document"),Me=Symbol.for("yaml.map"),Pe=Symbol.for("yaml.pair"),Be=Symbol.for("yaml.scalar"),$e=Symbol.for("yaml.seq"),De=Symbol.for("yaml.node.type"),Ue=t=>!!t&&"object"==typeof t&&t[De]===ke,Fe=t=>!!t&&"object"==typeof t&&t[De]===Le,je=t=>!!t&&"object"==typeof t&&t[De]===Me,Ve=t=>!!t&&"object"==typeof t&&t[De]===Pe,Ge=t=>!!t&&"object"==typeof t&&t[De]===Be,ze=t=>!!t&&"object"==typeof t&&t[De]===$e;function We(t){if(t&&"object"==typeof t)switch(t[De]){case Me:case $e:return!0}return!1}function Ke(t){if(t&&"object"==typeof t)switch(t[De]){case ke:case Me:case Be:case $e:return!0}return!1}const He=t=>(Ge(t)||We(t))&&!!t.anchor,qe=Symbol("break visit"),Qe=Symbol("skip children"),Je=Symbol("remove node");function Ye(t,e){const s=es(e);Fe(t)?Xe(null,t.contents,s,Object.freeze([t]))===Je&&(t.contents=null):Xe(null,t,s,Object.freeze([]))}function Xe(t,e,s,n){const r=ss(t,e,s,n);if(Ke(r)||Ve(r))return ns(t,n,r),Xe(t,r,s,n);if("symbol"!=typeof r)if(We(e)){n=Object.freeze(n.concat(e));for(let t=0;t<e.items.length;++t){const r=Xe(t,e.items[t],s,n);if("number"==typeof r)t=r-1;else{if(r===qe)return qe;r===Je&&(e.items.splice(t,1),t-=1)}}}else if(Ve(e)){n=Object.freeze(n.concat(e));const t=Xe("key",e.key,s,n);if(t===qe)return qe;t===Je&&(e.key=null);const r=Xe("value",e.value,s,n);if(r===qe)return qe;r===Je&&(e.value=null)}return r}async function Ze(t,e){const s=es(e);Fe(t)?await ts(null,t.contents,s,Object.freeze([t]))===Je&&(t.contents=null):await ts(null,t,s,Object.freeze([]))}async function ts(t,e,s,n){const r=await ss(t,e,s,n);if(Ke(r)||Ve(r))return ns(t,n,r),ts(t,r,s,n);if("symbol"!=typeof r)if(We(e)){n=Object.freeze(n.concat(e));for(let t=0;t<e.items.length;++t){const r=await ts(t,e.items[t],s,n);if("number"==typeof r)t=r-1;else{if(r===qe)return qe;r===Je&&(e.items.splice(t,1),t-=1)}}}else if(Ve(e)){n=Object.freeze(n.concat(e));const t=await ts("key",e.key,s,n);if(t===qe)return qe;t===Je&&(e.key=null);const r=await ts("value",e.value,s,n);if(r===qe)return qe;r===Je&&(e.value=null)}return r}function es(t){return"object"==typeof t&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function ss(t,e,s,n){return"function"==typeof s?s(t,e,n):je(e)?s.Map?.(t,e,n):ze(e)?s.Seq?.(t,e,n):Ve(e)?s.Pair?.(t,e,n):Ge(e)?s.Scalar?.(t,e,n):Ue(e)?s.Alias?.(t,e,n):void 0}function ns(t,e,s){const n=e[e.length-1];if(We(n))n.items[t]=s;else if(Ve(n))"key"===t?n.key=s:n.value=s;else{if(!Fe(n)){const t=Ue(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${t} parent`)}n.contents=s}}Ye.BREAK=qe,Ye.SKIP=Qe,Ye.REMOVE=Je,Ze.BREAK=qe,Ze.SKIP=Qe,Ze.REMOVE=Je;const rs={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},is=t=>t.replace(/[!,[\]{}]/g,t=>rs[t]);class os{constructor(t,e){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},os.defaultYaml,t),this.tags=Object.assign({},os.defaultTags,e)}clone(){const t=new os(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new os(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:os.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},os.defaultTags)}return t}add(t,e){this.atNextDocument&&(this.yaml={explicit:os.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},os.defaultTags),this.atNextDocument=!1);const s=t.trim().split(/[ \t]+/),n=s.shift();switch(n){case"%TAG":{if(2!==s.length&&(e(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[t,n]=s;return this.tags[t]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==s.length)return e(0,"%YAML directive should contain exactly one part"),!1;const[t]=s;return"1.1"===t||"1.2"===t?(this.yaml.version=t,!0):(e(6,`Unsupported YAML version ${t}`,/^\d+\.\d+$/.test(t)),!1)}default:return e(0,`Unknown directive ${n}`,!0),!1}}tagName(t,e){if("!"===t)return"!";if("!"!==t[0])return e(`Not a valid tag: ${t}`),null;if("<"===t[1]){const s=t.slice(2,-1);return"!"===s||"!!"===s?(e(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(">"!==t[t.length-1]&&e("Verbatim tags must end with a >"),s)}const[,s,n]=t.match(/^(.*!)([^!]*)$/s);n||e(`The ${t} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(n)}catch(t){return e(String(t)),null}return"!"===s?t:(e(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[e,s]of Object.entries(this.tags))if(t.startsWith(s))return e+is(t.substring(s.length));return"!"===t[0]?t:`!<${t}>`}toString(t){const e=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let n;if(t&&s.length>0&&Ke(t.contents)){const e={};Ye(t.contents,(t,s)=>{Ke(s)&&s.tag&&(e[s.tag]=!0)}),n=Object.keys(e)}else n=[];for(const[r,i]of s)"!!"===r&&"tag:yaml.org,2002:"===i||t&&!n.some(t=>t.startsWith(i))||e.push(`%TAG ${r} ${i}`);return e.join("\n")}}function as(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){const e=JSON.stringify(t);throw new Error(`Anchor must not contain whitespace or control characters: ${e}`)}return!0}function ls(t,e,s,n){if(n&&"object"==typeof n)if(Array.isArray(n))for(let e=0,s=n.length;e<s;++e){const s=n[e],r=ls(t,n,String(e),s);void 0===r?delete n[e]:r!==s&&(n[e]=r)}else if(n instanceof Map)for(const e of Array.from(n.keys())){const s=n.get(e),r=ls(t,n,e,s);void 0===r?n.delete(e):r!==s&&n.set(e,r)}else if(n instanceof Set)for(const e of Array.from(n)){const s=ls(t,n,e,e);void 0===s?n.delete(e):s!==e&&(n.delete(e),n.add(s))}else for(const[e,s]of Object.entries(n)){const r=ls(t,n,e,s);void 0===r?delete n[e]:r!==s&&(n[e]=r)}return t.call(e,s,n)}function hs(t,e,s){if(Array.isArray(t))return t.map((t,e)=>hs(t,String(e),s));if(t&&"function"==typeof t.toJSON){if(!s||!He(t))return t.toJSON(e,s);const n={aliasCount:0,count:1,res:void 0};s.anchors.set(t,n),s.onCreate=t=>{n.res=t,delete s.onCreate};const r=t.toJSON(e,s);return s.onCreate&&s.onCreate(r),r}return"bigint"!=typeof t||s?.keep?t:Number(t)}os.defaultYaml={explicit:!1,version:"1.2"},os.defaultTags={"!!":"tag:yaml.org,2002:"};class us{constructor(t){Object.defineProperty(this,De,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:e,maxAliasCount:s,onAnchor:n,reviver:r}={}){if(!Fe(t))throw new TypeError("A document argument is required");const i={anchors:new Map,doc:t,keep:!0,mapAsMap:!0===e,mapKeyWarned:!1,maxAliasCount:"number"==typeof s?s:100},o=hs(this,"",i);if("function"==typeof n)for(const{count:t,res:e}of i.anchors.values())n(e,t);return"function"==typeof r?ls(r,{"":o},"",o):o}}class cs extends us{constructor(t){super(ke),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,e){let s,n;e?.aliasResolveCache?s=e.aliasResolveCache:(s=[],Ye(t,{Node:(t,e)=>{(Ue(e)||He(e))&&s.push(e)}}),e&&(e.aliasResolveCache=s));for(const t of s){if(t===this)break;t.anchor===this.source&&(n=t)}return n}toJSON(t,e){if(!e)return{source:this.source};const{anchors:s,doc:n,maxAliasCount:r}=e,i=this.resolve(n,e);if(!i){const t=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(t)}let o=s.get(i);if(o||(hs(i,null,e),o=s.get(i)),void 0===o?.res)throw new ReferenceError("This should not happen: Alias anchor was not resolved?");if(r>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=ds(n,i,s)),o.count*o.aliasCount>r))throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack");return o.res}toString(t,e,s){const n=`*${this.source}`;if(t){if(as(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const t=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(t)}if(t.implicitKey)return`${n} `}return n}}function ds(t,e,s){if(Ue(e)){const n=e.resolve(t),r=s&&n&&s.get(n);return r?r.count*r.aliasCount:0}if(We(e)){let n=0;for(const r of e.items){const e=ds(t,r,s);e>n&&(n=e)}return n}if(Ve(e)){const n=ds(t,e.key,s),r=ds(t,e.value,s);return Math.max(n,r)}return 1}const fs=t=>!t||"function"!=typeof t&&"object"!=typeof t;class gs extends us{constructor(t){super(Be),this.value=t}toJSON(t,e){return e?.keep?this.value:hs(this.value,t,e)}toString(){return String(this.value)}}function ms(t,e,s){if(Fe(t)&&(t=t.contents),Ke(t))return t;if(Ve(t)){const e=s.schema[Me].createNode?.(s.schema,null,s);return e.items.push(t),e}(t instanceof String||t instanceof Number||t instanceof Boolean||"undefined"!=typeof BigInt&&t instanceof BigInt)&&(t=t.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=s;let l;if(n&&t&&"object"==typeof t){if(l=a.get(t),l)return l.anchor??(l.anchor=r(t)),new cs(l.anchor);l={anchor:null,node:null},a.set(t,l)}e?.startsWith("!!")&&(e="tag:yaml.org,2002:"+e.slice(2));let h=function(t,e,s){if(e){const t=s.filter(t=>t.tag===e),n=t.find(t=>!t.format)??t[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return s.find(e=>e.identify?.(t)&&!e.format)}(t,e,o.tags);if(!h){if(t&&"function"==typeof t.toJSON&&(t=t.toJSON()),!t||"object"!=typeof t){const e=new gs(t);return l&&(l.node=e),e}h=t instanceof Map?o[Me]:Symbol.iterator in Object(t)?o[$e]:o[Me]}i&&(i(h),delete s.onTagObj);const u=h?.createNode?h.createNode(s.schema,t,s):"function"==typeof h?.nodeClass?.from?h.nodeClass.from(s.schema,t,s):new gs(t);return e?u.tag=e:h.default||(u.tag=h.tag),l&&(l.node=u),u}function ps(t,e,s){let n=s;for(let t=e.length-1;t>=0;--t){const s=e[t];if("number"==typeof s&&Number.isInteger(s)&&s>=0){const t=[];t[s]=n,n=t}else n=new Map([[s,n]])}return ms(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}gs.BLOCK_FOLDED="BLOCK_FOLDED",gs.BLOCK_LITERAL="BLOCK_LITERAL",gs.PLAIN="PLAIN",gs.QUOTE_DOUBLE="QUOTE_DOUBLE",gs.QUOTE_SINGLE="QUOTE_SINGLE";class bs extends us{constructor(t,e){super(t),Object.defineProperty(this,"schema",{value:e,configurable:!0,enumerable:!1,writable:!0})}clone(t){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(e.schema=t),e.items=e.items.map(e=>Ke(e)||Ve(e)?e.clone(t):e),this.range&&(e.range=this.range.slice()),e}addIn(t,e){if((t=>null==t||"object"==typeof t&&!!t[Symbol.iterator]().next().done)(t))this.add(e);else{const[s,...n]=t,r=this.get(s,!0);if(We(r))r.addIn(n,e);else{if(void 0!==r||!this.schema)throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`);this.set(s,ps(this.schema,n,e))}}}deleteIn(t){const[e,...s]=t;if(0===s.length)return this.delete(e);const n=this.get(e,!0);if(We(n))return n.deleteIn(s);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${s}`)}getIn(t,e){const[s,...n]=t,r=this.get(s,!0);return 0===n.length?!e&&Ge(r)?r.value:r:We(r)?r.getIn(n,e):void 0}hasAllNullValues(t){return this.items.every(e=>{if(!Ve(e))return!1;const s=e.value;return null==s||t&&Ge(s)&&null==s.value&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(t){const[e,...s]=t;if(0===s.length)return this.has(e);const n=this.get(e,!0);return!!We(n)&&n.hasIn(s)}setIn(t,e){const[s,...n]=t;if(0===n.length)this.set(s,e);else{const t=this.get(s,!0);if(We(t))t.setIn(n,e);else{if(void 0!==t||!this.schema)throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`);this.set(s,ps(this.schema,n,e))}}}}const ys=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Ss(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}const Es=(t,e,s)=>t.endsWith("\n")?Ss(s,e):s.includes("\n")?"\n"+Ss(s,e):(t.endsWith(" ")?"":" ")+s,Cs="flow",ws="block",vs="quoted";function _s(t,e,s="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;r<i&&(i=0);const l=Math.max(1+i,1+r-e.length);if(t.length<=l)return t;const h=[],u={};let c,d,f=r-e.length;"number"==typeof n&&(n>r-Math.max(2,i)?h.push(0):f=r-n);let g=!1,m=-1,p=-1,b=-1;s===ws&&(m=xs(t,m,e.length),-1!==m&&(f=m+l));for(let n;n=t[m+=1];){if(s===vs&&"\\"===n){switch(p=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if("\n"===n)s===ws&&(m=xs(t,m,e.length)),f=m+e.length+l,c=void 0;else{if(" "===n&&d&&" "!==d&&"\n"!==d&&"\t"!==d){const e=t[m+1];e&&" "!==e&&"\n"!==e&&"\t"!==e&&(c=m)}if(m>=f)if(c)h.push(c),f=c+l,c=void 0;else if(s===vs){for(;" "===d||"\t"===d;)d=n,n=t[m+=1],g=!0;const e=m>b+1?m-2:p-1;if(u[e])return t;h.push(e),u[e]=!0,f=e+l,c=void 0}else g=!0}d=n}if(g&&a&&a(),0===h.length)return t;o&&o();let y=t.slice(0,h[0]);for(let n=0;n<h.length;++n){const r=h[n],i=h[n+1]||t.length;0===r?y=`\n${e}${t.slice(0,i)}`:(s===vs&&u[r]&&(y+=`${t[r]}\\`),y+=`\n${e}${t.slice(r+1,i)}`)}return y}function xs(t,e,s){let n=e,r=e+1,i=t[r];for(;" "===i||"\t"===i;)if(e<r+s)i=t[++e];else{do{i=t[++e]}while(i&&"\n"!==i);n=e,r=e+1,i=t[r]}return n}const Ns=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),As=t=>/^(%|---|\.\.\.)/m.test(t);function Ts(t,e){const s=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return s;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(As(t)?" ":"");let o="",a=0;for(let t=0,e=s[t];e;e=s[++t])if(" "===e&&"\\"===s[t+1]&&"n"===s[t+2]&&(o+=s.slice(a,t)+"\\ ",t+=1,a=t,e="\\"),"\\"===e)switch(s[t+1]){case"u":{o+=s.slice(a,t);const e=s.substr(t+2,4);switch(e){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===e.substr(0,2)?o+="\\x"+e.substr(2):o+=s.substr(t,6)}t+=5,a=t+1}break;case"n":if(n||'"'===s[t+2]||s.length<r)t+=1;else{for(o+=s.slice(a,t)+"\n\n";"\\"===s[t+2]&&"n"===s[t+3]&&'"'!==s[t+4];)o+="\n",t+=2;o+=i," "===s[t+2]&&(o+="\\"),t+=1,a=t+1}break;default:t+=1}return o=a?o+s.slice(a):s,n?o:_s(o,i,vs,Ns(e,!1))}function Is(t,e){if(!1===e.options.singleQuote||e.implicitKey&&t.includes("\n")||/[ \t]\n|\n[ \t]/.test(t))return Ts(t,e);const s=e.indent||(As(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&\n${s}`)+"'";return e.implicitKey?n:_s(n,s,Cs,Ns(e,!1))}function Os(t,e){const{singleQuote:s}=e.options;let n;if(!1===s)n=Ts;else{const e=t.includes('"'),r=t.includes("'");n=e&&!r?Is:r&&!e?Ts:s?Is:Ts}return n(t,e)}let Rs;try{Rs=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{Rs=/\n+(?!\n|$)/g}function ks({comment:t,type:e,value:s},n,r,i){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(s))return Os(s,n);const h=n.indent||(n.forceBlockIndent||As(s)?" ":""),u="literal"===o||"folded"!==o&&e!==gs.BLOCK_FOLDED&&(e===gs.BLOCK_LITERAL||!function(t,e,s){if(!e||e<0)return!1;const n=e-s,r=t.length;if(r<=n)return!1;for(let e=0,s=0;e<r;++e)if("\n"===t[e]){if(e-s>n)return!0;if(s=e+1,r-s<=n)return!1}return!0}(s,l,h.length));if(!s)return u?"|\n":">\n";let c,d;for(d=s.length;d>0;--d){const t=s[d-1];if("\n"!==t&&"\t"!==t&&" "!==t)break}let f=s.substring(d);const g=f.indexOf("\n");-1===g?c="-":s===f||g!==f.length-1?(c="+",i&&i()):c="",f&&(s=s.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace(Rs,`$&${h}`));let m,p=!1,b=-1;for(m=0;m<s.length;++m){const t=s[m];if(" "===t)p=!0;else{if("\n"!==t)break;b=m}}let y=s.substring(0,b<m?b+1:m);y&&(s=s.substring(y.length),y=y.replace(/\n+/g,`$&${h}`));let S=(p?h?"2":"1":"")+c;if(t&&(S+=" "+a(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){const t=s.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${h}`);let r=!1;const i=Ns(n,!0);"folded"!==o&&e!==gs.BLOCK_FOLDED&&(i.onOverflow=()=>{r=!0});const a=_s(`${y}${t}${f}`,h,ws,i);if(!r)return`>${S}\n${h}${a}`}return`|${S}\n${h}${y}${s=s.replace(/\n+/g,`$&${h}`)}${f}`}function Ls(t,e,s,n){const{implicitKey:r,inFlow:i}=e,o="string"==typeof t.value?t:Object.assign({},t,{value:String(t.value)});let{type:a}=t;a!==gs.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=gs.QUOTE_DOUBLE);const l=t=>{switch(t){case gs.BLOCK_FOLDED:case gs.BLOCK_LITERAL:return r||i?Os(o.value,e):ks(o,e,s,n);case gs.QUOTE_DOUBLE:return Ts(o.value,e);case gs.QUOTE_SINGLE:return Is(o.value,e);case gs.PLAIN:return function(t,e,s,n){const{type:r,value:i}=t,{actualString:o,implicitKey:a,indent:l,indentStep:h,inFlow:u}=e;if(a&&i.includes("\n")||u&&/[[\]{},]/.test(i))return Os(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes("\n")?Os(i,e):ks(t,e,s,n);if(!a&&!u&&r!==gs.PLAIN&&i.includes("\n"))return ks(t,e,s,n);if(As(i)){if(""===l)return e.forceBlockIndent=!0,ks(t,e,s,n);if(a&&l===h)return Os(i,e)}const c=i.replace(/\n+/g,`$&\n${l}`);if(o){const t=t=>t.default&&"tag:yaml.org,2002:str"!==t.tag&&t.test?.test(c),{compat:s,tags:n}=e.doc.schema;if(n.some(t)||s?.some(t))return Os(i,e)}return a?c:_s(c,l,Cs,Ns(e,!1))}(o,e,s,n);default:return null}};let h=l(a);if(null===h){const{defaultKeyType:t,defaultStringType:s}=e.options,n=r&&t||s;if(h=l(n),null===h)throw new Error(`Unsupported default string type ${n}`)}return h}function Ms(t,e,s,n){if(Ve(t))return t.toString(e,s,n);if(Ue(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r;const i=Ke(t)?t:e.doc.createNode(t,{onTagObj:t=>r=t});r??(r=function(t,e){if(e.tag){const s=t.filter(t=>t.tag===e.tag);if(s.length>0)return s.find(t=>t.format===e.format)??s[0]}let s,n;if(Ge(e)){n=e.value;let r=t.filter(t=>t.identify?.(n));if(r.length>1){const t=r.filter(t=>t.test);t.length>0&&(r=t)}s=r.find(t=>t.format===e.format)??r.find(t=>!t.format)}else n=e,s=t.find(t=>t.nodeClass&&n instanceof t.nodeClass);if(!s)throw new Error(`Tag not resolved for ${n?.constructor?.name??(null===n?"null":typeof n)} value`);return s}(e.doc.schema.tags,i));const o=function(t,e,{anchors:s,doc:n}){if(!n.directives)return"";const r=[],i=(Ge(t)||We(t))&&t.anchor;i&&as(i)&&(s.add(i),r.push(`&${i}`));const o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a="function"==typeof r.stringify?r.stringify(i,e,s,n):Ge(i)?Ls(i,e,s,n):i.toString(e,s,n);return o?Ge(i)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${e.indent}${a}`:a}const Ps="<<",Bs={identify:t=>t===Ps||"symbol"==typeof t&&t.description===Ps,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new gs(Symbol(Ps)),{addToJSMap:$s}),stringify:()=>Ps};function $s(t,e,s){if(s=t&&Ue(s)?s.resolve(t.doc):s,ze(s))for(const n of s.items)Ds(t,e,n);else if(Array.isArray(s))for(const n of s)Ds(t,e,n);else Ds(t,e,s)}function Ds(t,e,s){const n=t&&Ue(s)?s.resolve(t.doc):s;if(!je(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,t,Map);for(const[t,s]of r)e instanceof Map?e.has(t)||e.set(t,s):e instanceof Set?e.add(t):Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function Us(t,e,{key:s,value:n}){if(Ke(s)&&s.addToJSMap)s.addToJSMap(t,e,n);else if(((t,e)=>(Bs.identify(e)||Ge(e)&&(!e.type||e.type===gs.PLAIN)&&Bs.identify(e.value))&&t?.doc.schema.tags.some(t=>t.tag===Bs.tag&&t.default))(t,s))$s(t,e,n);else{const r=hs(s,"",t);if(e instanceof Map)e.set(r,hs(n,r,t));else if(e instanceof Set)e.add(r);else{const i=function(t,e,s){if(null===e)return"";if("object"!=typeof e)return String(e);if(Ke(t)&&s?.doc){const e=function(t){const e=Object.assign({blockQuote:!0,commentString:ys,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,{});let s;switch(e.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:t,flowCollectionPadding:e.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof e.indent?" ".repeat(e.indent):" ",inFlow:s,options:e}}(s.doc);e.anchors=new Set;for(const t of s.anchors.keys())e.anchors.add(t.anchor);e.inFlow=!0,e.inStringifyKey=!0;const i=t.toString(e);if(!s.mapKeyWarned){let t=JSON.stringify(i);t.length>40&&(t=t.substring(0,36)+'..."'),r=`Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`,"debug"!==(n=s.doc.options.logLevel)&&"warn"!==n||console.warn(r),s.mapKeyWarned=!0}return i}var n,r;return JSON.stringify(e)}(s,r,t),o=hs(n,i,t);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Fs(t,e,s){const n=ms(t,void 0,s),r=ms(e,void 0,s);return new js(n,r)}class js{constructor(t,e=null){Object.defineProperty(this,De,{value:Pe}),this.key=t,this.value=e}clone(t){let{key:e,value:s}=this;return Ke(e)&&(e=e.clone(t)),Ke(s)&&(s=s.clone(t)),new js(e,s)}toJSON(t,e){return Us(e,e?.mapAsMap?new Map:{},this)}toString(t,e,s){return t?.doc?function({key:t,value:e},s,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:h,indentSeq:u,simpleKeys:c}}=s;let d=Ke(t)&&t.comment||null;if(c){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(We(t)||!Ke(t)&&"object"==typeof t)throw new Error("With simple keys, collection cannot be used as a key value")}let f=!c&&(!t||d&&null==e&&!s.inFlow||We(t)||(Ge(t)?t.type===gs.BLOCK_FOLDED||t.type===gs.BLOCK_LITERAL:"object"==typeof t));s=Object.assign({},s,{allNullValues:!1,implicitKey:!f&&(c||!i),indent:a+l});let g,m,p,b=!1,y=!1,S=Ms(t,s,()=>b=!0,()=>y=!0);if(!f&&!s.inFlow&&S.length>1024){if(c)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(s.inFlow){if(i||null==e)return b&&n&&n(),""===S?"?":f?`? ${S}`:S}else if(i&&!c||null==e&&f)return S=`? ${S}`,d&&!b?S+=Es(S,s.indent,h(d)):y&&r&&r(),S;b&&(d=null),f?(d&&(S+=Es(S,s.indent,h(d))),S=`? ${S}\n${a}:`):(S=`${S}:`,d&&(S+=Es(S,s.indent,h(d)))),Ke(e)?(g=!!e.spaceBefore,m=e.commentBefore,p=e.comment):(g=!1,m=null,p=null,e&&"object"==typeof e&&(e=o.createNode(e))),s.implicitKey=!1,f||d||!Ge(e)||(s.indentAtStart=S.length+1),y=!1,u||!(l.length>=2)||s.inFlow||f||!ze(e)||e.flow||e.tag||e.anchor||(s.indent=s.indent.substring(2));let E=!1;const C=Ms(e,s,()=>E=!0,()=>y=!0);let w=" ";if(d||g||m)w=g?"\n":"",m&&(w+=`\n${Ss(h(m),s.indent)}`),""!==C||s.inFlow?w+=`\n${s.indent}`:"\n"===w&&p&&(w="\n\n");else if(!f&&We(e)){const t=C[0],n=C.indexOf("\n"),r=-1!==n,i=s.inFlow??e.flow??0===e.items.length;if(r||!i){let e=!1;if(r&&("&"===t||"!"===t)){let s=C.indexOf(" ");"&"===t&&-1!==s&&s<n&&"!"===C[s+1]&&(s=C.indexOf(" ",s+1)),(-1===s||n<s)&&(e=!0)}e||(w=`\n${s.indent}`)}}else""!==C&&"\n"!==C[0]||(w="");return S+=w+C,s.inFlow?E&&n&&n():p&&!E?S+=Es(S,s.indent,h(p)):y&&r&&r(),S}(this,t,e,s):JSON.stringify(this)}}function Vs(t,e,s){return(e.inFlow??t.flow?zs:Gs)(t,e,s)}function Gs({comment:t,items:e},s,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:h}}=s,u=Object.assign({},s,{indent:i,type:null});let c=!1;const d=[];for(let t=0;t<e.length;++t){const r=e[t];let o=null;if(Ke(r))!c&&r.spaceBefore&&d.push(""),Ws(s,d,r.commentBefore,c),r.comment&&(o=r.comment);else if(Ve(r)){const t=Ke(r.key)?r.key:null;t&&(!c&&t.spaceBefore&&d.push(""),Ws(s,d,t.commentBefore,c))}c=!1;let a=Ms(r,u,()=>o=null,()=>c=!0);o&&(a+=Es(a,i,h(o))),c&&o&&(c=!1),d.push(n+a)}let f;if(0===d.length)f=r.start+r.end;else{f=d[0];for(let t=1;t<d.length;++t){const e=d[t];f+=e?`\n${l}${e}`:"\n"}}return t?(f+="\n"+Ss(h(t),l),a&&a()):c&&o&&o(),f}function zs({items:t},e,{flowChars:s,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let h=!1,u=0;const c=[];for(let s=0;s<t.length;++s){const r=t[s];let i=null;if(Ke(r))r.spaceBefore&&c.push(""),Ws(e,c,r.commentBefore,!1),r.comment&&(i=r.comment);else if(Ve(r)){const t=Ke(r.key)?r.key:null;t&&(t.spaceBefore&&c.push(""),Ws(e,c,t.commentBefore,!1),t.comment&&(h=!0));const s=Ke(r.value)?r.value:null;s?(s.comment&&(i=s.comment),s.commentBefore&&(h=!0)):null==r.value&&t?.comment&&(i=t.comment)}i&&(h=!0);let o=Ms(r,l,()=>i=null);s<t.length-1&&(o+=","),i&&(o+=Es(o,n,a(i))),!h&&(c.length>u||o.includes("\n"))&&(h=!0),c.push(o),u=c.length}const{start:d,end:f}=s;if(0===c.length)return d+f;if(!h){const t=c.reduce((t,e)=>t+e.length+2,2);h=e.options.lineWidth>0&&t>e.options.lineWidth}if(h){let t=d;for(const e of c)t+=e?`\n${i}${r}${e}`:"\n";return`${t}\n${r}${f}`}return`${d}${o}${c.join(" ")}${o}${f}`}function Ws({indent:t,options:{commentString:e}},s,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const r=Ss(e(n),t);s.push(r.trimStart())}}function Ks(t,e){const s=Ge(e)?e.value:e;for(const n of t)if(Ve(n)){if(n.key===e||n.key===s)return n;if(Ge(n.key)&&n.key.value===s)return n}}class Hs extends bs{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Me,t),this.items=[]}static from(t,e,s){const{keepUndefined:n,replacer:r}=s,i=new this(t),o=(t,o)=>{if("function"==typeof r)o=r.call(e,t,o);else if(Array.isArray(r)&&!r.includes(t))return;(void 0!==o||n)&&i.items.push(Fs(t,o,s))};if(e instanceof Map)for(const[t,s]of e)o(t,s);else if(e&&"object"==typeof e)for(const t of Object.keys(e))o(t,e[t]);return"function"==typeof t.sortMapEntries&&i.items.sort(t.sortMapEntries),i}add(t,e){let s;s=Ve(t)?t:t&&"object"==typeof t&&"key"in t?new js(t.key,t.value):new js(t,t?.value);const n=Ks(this.items,s.key),r=this.schema?.sortMapEntries;if(n){if(!e)throw new Error(`Key ${s.key} already set`);Ge(n.value)&&fs(s.value)?n.value.value=s.value:n.value=s.value}else if(r){const t=this.items.findIndex(t=>r(s,t)<0);-1===t?this.items.push(s):this.items.splice(t,0,s)}else this.items.push(s)}delete(t){const e=Ks(this.items,t);return!!e&&this.items.splice(this.items.indexOf(e),1).length>0}get(t,e){const s=Ks(this.items,t),n=s?.value;return(!e&&Ge(n)?n.value:n)??void 0}has(t){return!!Ks(this.items,t)}set(t,e){this.add(new js(t,e),!0)}toJSON(t,e,s){const n=s?new s:e?.mapAsMap?new Map:{};e?.onCreate&&e.onCreate(n);for(const t of this.items)Us(e,n,t);return n}toString(t,e,s){if(!t)return JSON.stringify(this);for(const t of this.items)if(!Ve(t))throw new Error(`Map items must all be pairs; found ${JSON.stringify(t)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Vs(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:s,onComment:e})}}const qs={collection:"map",default:!0,nodeClass:Hs,tag:"tag:yaml.org,2002:map",resolve:(t,e)=>(je(t)||e("Expected a mapping for this tag"),t),createNode:(t,e,s)=>Hs.from(t,e,s)};class Qs extends bs{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super($e,t),this.items=[]}add(t){this.items.push(t)}delete(t){const e=Js(t);return"number"==typeof e&&this.items.splice(e,1).length>0}get(t,e){const s=Js(t);if("number"!=typeof s)return;const n=this.items[s];return!e&&Ge(n)?n.value:n}has(t){const e=Js(t);return"number"==typeof e&&e<this.items.length}set(t,e){const s=Js(t);if("number"!=typeof s)throw new Error(`Expected a valid index, not ${t}.`);const n=this.items[s];Ge(n)&&fs(e)?n.value=e:this.items[s]=e}toJSON(t,e){const s=[];e?.onCreate&&e.onCreate(s);let n=0;for(const t of this.items)s.push(hs(t,String(n++),e));return s}toString(t,e,s){return t?Vs(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:s,onComment:e}):JSON.stringify(this)}static from(t,e,s){const{replacer:n}=s,r=new this(t);if(e&&Symbol.iterator in Object(e)){let t=0;for(let i of e){if("function"==typeof n){const s=e instanceof Set?i:String(t++);i=n.call(e,s,i)}r.items.push(ms(i,void 0,s))}}return r}}function Js(t){let e=Ge(t)?t.value:t;return e&&"string"==typeof e&&(e=Number(e)),"number"==typeof e&&Number.isInteger(e)&&e>=0?e:null}const Ys={collection:"seq",default:!0,nodeClass:Qs,tag:"tag:yaml.org,2002:seq",resolve:(t,e)=>(ze(t)||e("Expected a sequence for this tag"),t),createNode:(t,e,s)=>Qs.from(t,e,s)},Xs={identify:t=>"string"==typeof t,default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:(t,e,s,n)=>Ls(t,e=Object.assign({actualString:!0},e),s,n)},Zs={identify:t=>null==t,createNode:()=>new gs(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new gs(null),stringify:({source:t},e)=>"string"==typeof t&&Zs.test.test(t)?t:e.options.nullStr},tn={identify:t=>"boolean"==typeof t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new gs("t"===t[0]||"T"===t[0]),stringify:({source:t,value:e},s)=>t&&tn.test.test(t)&&e===("t"===t[0]||"T"===t[0])?t:e?s.options.trueStr:s.options.falseStr};function en({format:t,minFractionDigits:e,tag:s,value:n}){if("bigint"==typeof n)return String(n);const r="number"==typeof n?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!s||"tag:yaml.org,2002:float"===s)&&/^\d/.test(i)){let t=i.indexOf(".");t<0&&(t=i.length,i+=".");let s=e-(i.length-t-1);for(;s-- >0;)i+="0"}return i}const sn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>"nan"===t.slice(-3).toLowerCase()?NaN:"-"===t[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:en},nn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){const e=Number(t.value);return isFinite(e)?e.toExponential():en(t)}},rn=t=>"bigint"==typeof t||Number.isInteger(t),on=(t,e,s,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),s);function an(t,e,s){const{value:n}=t;return rn(n)&&n>=0?s+n.toString(e):en(t)}const ln=[qs,Ys,Xs,Zs,tn,{identify:t=>rn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,s)=>on(t,2,8,s),stringify:t=>an(t,8,"0o")},{identify:rn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,s)=>on(t,0,10,s),stringify:en},{identify:t=>rn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,s)=>on(t,2,16,s),stringify:t=>an(t,16,"0x")},sn,nn,{identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){const e=new gs(parseFloat(t)),s=t.indexOf(".");return-1!==s&&"0"===t[t.length-1]&&(e.minFractionDigits=t.length-s-1),e},stringify:en}];function hn(t){return"bigint"==typeof t||Number.isInteger(t)}const un=({value:t})=>JSON.stringify(t),cn=[qs,Ys].concat([{identify:t=>"string"==typeof t,default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:un},{identify:t=>null==t,createNode:()=>new gs(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:un},{identify:t=>"boolean"==typeof t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>"true"===t,stringify:un},{identify:hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:s})=>s?BigInt(t):parseInt(t,10),stringify:({value:t})=>hn(t)?t.toString():JSON.stringify(t)},{identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:un}],{default:!0,tag:"",test:/^/,resolve:(t,e)=>(e(`Unresolved plain scalar ${JSON.stringify(t)}`),t)}),dn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if("function"==typeof atob){const e=atob(t.replace(/[\n\r]/g,"")),s=new Uint8Array(e.length);for(let t=0;t<e.length;++t)s[t]=e.charCodeAt(t);return s}return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:s},n,r,i){if(!s)return"";const o=s;let a;if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let t="";for(let e=0;e<o.length;++e)t+=String.fromCharCode(o[e]);a=btoa(t)}if(e??(e=gs.BLOCK_LITERAL),e!==gs.QUOTE_DOUBLE){const t=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),s=Math.ceil(a.length/t),r=new Array(s);for(let e=0,n=0;e<s;++e,n+=t)r[e]=a.substr(n,t);a=r.join(e===gs.BLOCK_LITERAL?"\n":" ")}return Ls({comment:t,type:e,value:a},n,r,i)}};function fn(t,e){if(ze(t))for(let s=0;s<t.items.length;++s){let n=t.items[s];if(!Ve(n)){if(je(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const t=n.items[0]||new js(new gs(null));if(n.commentBefore&&(t.key.commentBefore=t.key.commentBefore?`${n.commentBefore}\n${t.key.commentBefore}`:n.commentBefore),n.comment){const e=t.value??t.key;e.comment=e.comment?`${n.comment}\n${e.comment}`:n.comment}n=t}t.items[s]=Ve(n)?n:new js(n)}}else e("Expected a sequence for this tag");return t}function gn(t,e,s){const{replacer:n}=s,r=new Qs(t);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let t of e){let o,a;if("function"==typeof n&&(t=n.call(e,String(i++),t)),Array.isArray(t)){if(2!==t.length)throw new TypeError(`Expected [key, value] tuple: ${t}`);o=t[0],a=t[1]}else if(t&&t instanceof Object){const e=Object.keys(t);if(1!==e.length)throw new TypeError(`Expected tuple with one key, not ${e.length} keys`);o=e[0],a=t[o]}else o=t;r.items.push(Fs(o,a,s))}return r}const mn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:fn,createNode:gn};class pn extends Qs{constructor(){super(),this.add=Hs.prototype.add.bind(this),this.delete=Hs.prototype.delete.bind(this),this.get=Hs.prototype.get.bind(this),this.has=Hs.prototype.has.bind(this),this.set=Hs.prototype.set.bind(this),this.tag=pn.tag}toJSON(t,e){if(!e)return super.toJSON(t);const s=new Map;e?.onCreate&&e.onCreate(s);for(const t of this.items){let n,r;if(Ve(t)?(n=hs(t.key,"",e),r=hs(t.value,n,e)):n=hs(t,"",e),s.has(n))throw new Error("Ordered maps must not include duplicate keys");s.set(n,r)}return s}static from(t,e,s){const n=gn(t,e,s),r=new this;return r.items=n.items,r}}pn.tag="tag:yaml.org,2002:omap";const bn={collection:"seq",identify:t=>t instanceof Map,nodeClass:pn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){const s=fn(t,e),n=[];for(const{key:t}of s.items)Ge(t)&&(n.includes(t.value)?e(`Ordered maps must not include duplicate keys: ${t.value}`):n.push(t.value));return Object.assign(new pn,s)},createNode:(t,e,s)=>pn.from(t,e,s)};function yn({value:t,source:e},s){return e&&(t?Sn:En).test.test(e)?e:t?s.options.trueStr:s.options.falseStr}const Sn={identify:t=>!0===t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new gs(!0),stringify:yn},En={identify:t=>!1===t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new gs(!1),stringify:yn},Cn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>"nan"===t.slice(-3).toLowerCase()?NaN:"-"===t[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:en},wn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){const e=Number(t.value);return isFinite(e)?e.toExponential():en(t)}},vn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){const e=new gs(parseFloat(t.replace(/_/g,""))),s=t.indexOf(".");if(-1!==s){const n=t.substring(s+1).replace(/_/g,"");"0"===n[n.length-1]&&(e.minFractionDigits=n.length)}return e},stringify:en},_n=t=>"bigint"==typeof t||Number.isInteger(t);function xn(t,e,s,{intAsBigInt:n}){const r=t[0];if("-"!==r&&"+"!==r||(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(s){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`}const e=BigInt(t);return"-"===r?BigInt(-1)*e:e}const i=parseInt(t,s);return"-"===r?-1*i:i}function Nn(t,e,s){const{value:n}=t;if(_n(n)){const t=n.toString(e);return n<0?"-"+s+t.substr(1):s+t}return en(t)}const An={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,s)=>xn(t,2,2,s),stringify:t=>Nn(t,2,"0b")},Tn={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,s)=>xn(t,1,8,s),stringify:t=>Nn(t,8,"0")},In={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,s)=>xn(t,0,10,s),stringify:en},On={identify:_n,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,s)=>xn(t,2,16,s),stringify:t=>Nn(t,16,"0x")};class Rn extends Hs{constructor(t){super(t),this.tag=Rn.tag}add(t){let e;e=Ve(t)?t:t&&"object"==typeof t&&"key"in t&&"value"in t&&null===t.value?new js(t.key,null):new js(t,null),Ks(this.items,e.key)||this.items.push(e)}get(t,e){const s=Ks(this.items,t);return!e&&Ve(s)?Ge(s.key)?s.key.value:s.key:s}set(t,e){if("boolean"!=typeof e)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof e);const s=Ks(this.items,t);s&&!e?this.items.splice(this.items.indexOf(s),1):!s&&e&&this.items.push(new js(t))}toJSON(t,e){return super.toJSON(t,e,Set)}toString(t,e,s){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),e,s);throw new Error("Set items must all have null values")}static from(t,e,s){const{replacer:n}=s,r=new this(t);if(e&&Symbol.iterator in Object(e))for(let t of e)"function"==typeof n&&(t=n.call(e,t,t)),r.items.push(Fs(t,null,s));return r}}Rn.tag="tag:yaml.org,2002:set";const kn={collection:"map",identify:t=>t instanceof Set,nodeClass:Rn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,s)=>Rn.from(t,e,s),resolve(t,e){if(je(t)){if(t.hasAllNullValues(!0))return Object.assign(new Rn,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Ln(t,e){const s=t[0],n="-"===s||"+"===s?t.substring(1):t,r=t=>e?BigInt(t):Number(t),i=n.replace(/_/g,"").split(":").reduce((t,e)=>t*r(60)+r(e),r(0));return"-"===s?r(-1)*i:i}function Mn(t){let{value:e}=t,s=t=>t;if("bigint"==typeof e)s=t=>BigInt(t);else if(isNaN(e)||!isFinite(e))return en(t);let n="";e<0&&(n="-",e*=s(-1));const r=s(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(t=>String(t).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const Pn={identify:t=>"bigint"==typeof t||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:s})=>Ln(t,s),stringify:Mn},Bn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Ln(t,!1),stringify:Mn},$n={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){const e=t.match($n.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,s,n,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let h=Date.UTC(s,n-1,r,i||0,o||0,a||0,l);const u=e[8];if(u&&"Z"!==u){let t=Ln(u,!1);Math.abs(t)<30&&(t*=60),h-=6e4*t}return new Date(h)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""},Dn=[qs,Ys,Xs,Zs,Sn,En,An,Tn,In,On,Cn,wn,vn,dn,Bs,bn,mn,kn,Pn,Bn,$n];new Map([["core",ln],["failsafe",[qs,Ys,Xs]],["json",cn],["yaml11",Dn],["yaml-1.1",Dn]]),Error;const Un=Symbol("break visit"),Fn=Symbol("skip children"),jn=Symbol("remove item");function Vn(t,e){"type"in t&&"document"===t.type&&(t={start:t.start,value:t.value}),Gn(Object.freeze([]),t,e)}function Gn(t,e,s){let n=s(e,t);if("symbol"==typeof n)return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let e=0;e<i.items.length;++e){const n=Gn(Object.freeze(t.concat([[r,e]])),i.items[e],s);if("number"==typeof n)e=n-1;else{if(n===Un)return Un;n===jn&&(i.items.splice(e,1),e-=1)}}"function"==typeof n&&"key"===r&&(n=n(e,t))}}return"function"==typeof n?n(e,t):n}var zn;Vn.BREAK=Un,Vn.SKIP=Fn,Vn.REMOVE=jn,Vn.itemAtPath=(t,e)=>{let s=t;for(const[t,n]of e){const e=s?.[t];if(!e||!("items"in e))return;s=e.items[n]}return s},Vn.parentCollection=(t,e)=>{const s=Vn.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=s?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")},new Set("0123456789ABCDEFabcdef"),new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),new Set(",[]{}"),new Set(" ,[]{}\n\r\t"),p.ONE,function(t){t.Kampitham="Kampitham",t.Nokku="Nokku",t.Spuritham="Spuritham",t.Prathyagatham="Prathyagatham",t.Aahaatam_Raavi="Raavi",t.Aahaatam_Kandippu="Kandippu",t.Vaali="Vaali",t.Odukkal="Odukkal",t.Jaaru_Eetra="EetraJaaru",t.Jaaru_Irakka="IrakkaJaaru",t.Orikkai="Orikkai"}(zn||(zn={}));class Wn{constructor(){this.shapeId=Wn.idCounter++,this._x=null,this._y=null,this._width=null,this._height=null,this.parentShape=null,this.children=[]}get bbox(){return this._bbox||(this._bbox=this.refreshBBox()),this._bbox}get minSize(){return this._minSize||(this._minSize=this.refreshMinSize()),this._minSize}invalidateBounds(){this._minSize=null,this._bbox=null}setBounds(t,e,s,n,r=!1){null!=t&&(isNaN(t)?this._x=null:this._x=t),null!=e&&(isNaN(e)?this._y=null:this._y=e),null!=s&&(isNaN(s)?this._width=null:this._width=s),null!=n&&(isNaN(n)?this._height=null:this._height=n);const[i,o,a,l]=this.updateBounds(t,e,s,n);return null!=i&&(isNaN(i)?this._x=null:this._x=i),null!=o&&(isNaN(o)?this._y=null:this._y=o),null!=a&&(isNaN(a)?this._width=null:this._width=a),null!=l&&(isNaN(l)?this._height=null:this._height=l),r&&this.refreshLayout(),[i,o,a,l]}get hasX(){return null!=this._x&&!isNaN(this._x)}get hasY(){return null!=this._y&&!isNaN(this._y)}get hasWidth(){return null!=this._width&&!isNaN(this._width)}get hasHeight(){return null!=this._height&&!isNaN(this._height)}get x(){return this._x||0}set x(t){this.setBounds(null==t?NaN:t,null,null,null)}get y(){return null!=this._y?this._y:0}set y(t){this.setBounds(null,null==t?NaN:t,null,null)}get width(){return null!=this._width?this._width:0}set width(t){this.setBounds(null,null,null==t?NaN:t,null)}get height(){return null!=this._height?this._height:0}set height(t){this.setBounds(null,null,null,null==t?NaN:t)}refreshLayout(){}}Wn.idCounter=0;const Kn=p.ONE,[Hn]=(Kn.timesNum(2),function(t,e=null){const s=e||{},[n,r,i]=function(t,e=null){const s=e||{},[n,r]=function(t,e){const s=new et((e=e||{}).grammar||{}),n=new fe(t,{...e,grammar:s}),r=n.generatedTokenizer.next.bind(n.generatedTokenizer);return(e.debug||"").split("|").findIndex(t=>"all"==t||"lexer"==t)>=0&&console.log("Prog: \n",`${n.generatedTokenizer.vm.prog.debugValue().join("\n")}`),[s,r]}(t,s);n.augmentStartSymbol();const[i,o]=function(t,e="lr1"){switch(e){case"lr1":return function(t){const e=new Ae(t).refresh();return[Oe(e,t),e]}(t);case"lalr":return function(t){const[e,s]=Te(t);if(!e.hasConflicts)return[e,s];const n=function(t,e){const s=new et;function n(t,n){const r=`[${t}:${n.label}]`,i=s.ensureSym(new Y(s,r,n.isTerminal),!1);return 0!=t||e.startSymbol!=n||e.startSymbol==i||n.isTerminal||(s.startSymbol=i),i}for(const s in t.gotoSets){const r=t.gotoSets[s];for(const t in r)n(s,e.getSymById(t))}function r(e,s,r){let i=e;const o=r.rhs.syms.map((e,s)=>{const r=n(i,e),o=t.gotoSets[i][e.id]||null;return a(null!=o,"Next set transition *must* be valid"),i=o.id,r});return new X(...o)}for(const i in t.gotoSets){const o=t.gotoSets[i];for(const t in o){const o=e.getSymById(t),a=i;if(!o.isTerminal){const t=n(a,o);e.forEachRule(o,(e,n)=>{const i=r(a,0,e),o=new tt(t,i);s.addRule(o)})}}}return s}(s,t),r={};for(const t in s.gotoSets)for(const e in s.gotoSets[t]){const n=s.gotoSets[t][e];n.id in r||(r[n.id]={}),e in r[n.id]||(r[n.id][e]=new Set),r[n.id][e].add(t)}for(const i in e.conflictActions){const e=s.itemSets.get(i);Re(t,n,s,e,r)}return[Oe(s,t),s]}(t)}return Te(t)}(n,s.type);return[i,r,o]}(t,s),o=new we(n);return(s.tokenizer||r)&&o.setTokenizer(s.tokenizer||r),(s.debug||"").split("|").findIndex(t=>"all"==t||"parser"==t)>=0&&function(t,e){const s=t.grammar,n=t.parseTable;console.log("===============================\nGrammar (as default): \n",s.debugValue.map((t,e)=>`${e+1} - ${t}`),"===============================\nGrammar (as Bison): \n",s.debugValue.map((t,e)=>`${t.replace("->",":")} ; \n`).join(""),"===============================\nParseTable: \n",JSON.stringify(function(t,e){const s={},n=t.debugValue,r=e?.debugValue;for(const t in n){const i=n[t];if(e){const e=r[t];s[t]={items:e.items,actions:i,goto:e.goto}}else s[t]=i}return s}(n,e),null,4),"===============================\nConflicts: \n",n.conflictActions)}(o,i),[o,r,i]}(String.raw`
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Notations=e():t.Notations=e()}(this,()=>(()=>{"use strict";var t,e,s,n={d:(t,e)=>{for(var s in e)n.o(e,s)&&!n.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},r={};n.d(r,{aq:()=>T,YJ:()=>$});class i{constructor(t=null){if(this.TYPE="Entity",this.uuid=i.counter++,this._parent=null,this._eventsEnabled=!1,(t=t||{}).metadata)throw new Error("See where metadata is being passed")}enableEvents(){return this._eventsEnabled=!0,this}disableEvents(){return this._eventsEnabled=!1,this}get eventsEnabled(){return this._eventsEnabled}get parent(){return this._parent}setParent(t){this._parent=t}debugValue(){return{type:this.TYPE}}toString(){return`Entity(id = ${this.uuid})`}equals(t,e=!1){return this.TYPE==t.TYPE}clone(){const t=this.newInstance();return this.copyTo(t),t}copyTo(t){}newInstance(){return new this.constructor}}i.counter=0;class o extends i{constructor(){super(...arguments),this.TYPE="TimedEntity"}equals(t){return super.equals(t)&&this.duration.equals(t.duration)}}function a(t,e){if(!t)throw new Error(e)}!function(t){t.ADD="add",t.INSERT="insert",t.REMOVE="remove",t.UPDATE="update"}(t||(t={})),function(t){t.ADD="add",t.REMOVE="remove"}(e||(e={})),function(t){t.ADD="add",t.REMOVE="remove"}(s||(s={}));const l=Math.pow(2,32);Math.pow(2,64);class h{constructor(t,e,s){this.uuid=h.counter++,this._spawnedFrom=null,this.sourceState=null,this.cancelled=!1,this.timeStamp=-1,this.children=[],this.name=t,this.source=e,this.payload=s}get spawnedFrom(){return this._spawnedFrom}setSpawnedFrom(t){this._spawnedFrom=t,this._rootEvent=null==t?this:t.rootEvent}spawn(t,e,s){const n=new h(t,e,s);return n.setSpawnedFrom(this),this.children.push(n),n}get rootEvent(){return this._rootEvent}}h.counter=0;class u{constructor(){this.stateData=null,this.id=u.counter++}get name(){return this.constructor.name}enter(t){this.stateData=t}handle(t){}}u.counter=0;class c{constructor(){this._eventHub=new d}get eventHub(){return this._eventHub}set eventHub(t){const e=this._eventHub;this._eventHub=t,this.eventHubChanged(e)}eventHubChanged(t){console.log("WARNING - EventHub Change Listener not implemented: ",this.constructor.name)}}class d{constructor(){this._handlers={},this._events=[],this._inBatchMode=!1}on(t,e){return this._addHandler(t,this._handlers,e)}removeOn(t,e){return this._removeHandler(t,this._handlers,e)}_ensurestrings(t){return"string"==typeof t&&(t=t.split(",")),t.map(function(t){return t.trim()})}_addHandler(t,e,s){return this._ensurestrings(t).forEach(function(t){e[t]=e[t]||[],e[t].push(s)}),this}_removeHandler(t,e,s){return this._ensurestrings(t).forEach(function(t){const n=e[t]||[];for(let t=0;t<n.length;t++)if(n[t]==s){n.splice(t,1);break}}),this}emit(t,e,s){const n=new h(t,e,s);return this._inBatchMode?(this._events.push(n),!0):this.dispatchEvent(n)}dispatchEvent(t){const e=this._handlers[t.name]||[];for(const s of e)if(s(t),t.cancelled)return!1;return!0}startBatchMode(){return this._inBatchMode||(this._inBatchMode=!0),this}cancelBatch(){this._inBatchMode=!1,this._events=[]}commitBatch(){this._inBatchMode=!1,this.emit(d.BATCH_EVENTS,this,this._events),this._events=[]}}d.BATCH_EVENTS="BatchEvents";class f{constructor(...t){this._firstChild=null,this._lastChild=null,this._size=0;for(const e of t)this.pushBack(e)}toJSON(){return Array.from(this.values())}forEach(t){let e=this._firstChild,s=0;for(;null!=e&&0!=t(e);)s++,e=e.nextSibling;return s}equals(t,e){if(this.size!=t.size)return!1;let s=this.first,n=t.first;for(;null!=s&&null!=n;s=s.nextSibling,n=n.nextSibling)if(!e(s,n))return!1;return null==s&&null==n}get isEmpty(){return 0==this._size}get size(){return this._size}get first(){return this._firstChild}get last(){return this._lastChild}*reversedValues(){let t=this._lastChild;for(;null!=t;)yield t,t=t.prevSibling}*values(){let t=this._firstChild;for(;null!=t;)yield t,t=t.nextSibling}add(t,e=null){if(null!=t.nextSibling||null!=t.prevSibling)throw new Error("New node already added to a list. Remove it first");if(t.nextSibling=t.prevSibling=null,this._size++,null==this._firstChild||null==this._lastChild)this._firstChild=this._lastChild=t;else if(null==e)t.prevSibling=this._lastChild,t.nextSibling=null,this._lastChild.nextSibling=t,this._lastChild=t;else if(e==this._firstChild)t.nextSibling=e,t.prevSibling=null,this._firstChild.prevSibling=t,this._firstChild=t;else{const s=e.prevSibling;t.nextSibling=e,e.prevSibling=t,t.prevSibling=s,null!=s&&(s.nextSibling=t)}return this}pushFront(t){return this.add(t,this._firstChild)}pushBack(t){return this.add(t)}remove(t){const e=t.nextSibling,s=t.prevSibling;return null==e?(this._lastChild=s,null==s&&(this._firstChild=null)):e.prevSibling=s,null==s?(this._firstChild=e,null==e&&(this._lastChild=null)):s.nextSibling=e,this._size--,t.prevSibling=t.nextSibling=null,this}popBack(){if(null==this._lastChild)throw new Error("No children");const t=this._lastChild;return this.remove(t),t}popFront(){if(null==this._firstChild)throw new Error("No children");const t=this._firstChild;return this.remove(t),t}}class g{constructor(t=0,e=0){this.width=0,this.height=0,this.width=t,this.height=e}}class m{constructor(t=0,e=0,s=0,n=0){this.x=t,this.y=e,this.width=s,this.height=n}static from(t){return new m(t.x,t.y,t.width,t.height)}copy(){return m.from(this)}union(t){if(t){const e=Math.min(this.x,t.x),s=Math.min(this.y,t.y),n=Math.max(this.x+this.width,t.x+t.width),r=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.y=s,this.width=n-e,this.height=r-s}return this}unionAll(...t){for(const e of t)this.union(e);return this}}class p{}function b(t){var e;const s=m.from(t.getBBox());if(p.IS_SAFARI()){const n=t.getClientRects()[0];if(n){const r=null===(e=t.parentElement)||void 0===e?void 0:e.getBoundingClientRect();s.x=s.x+n.x-((null==r?void 0:r.x)||0),s.width=n.width,s.height=n.height}}return s}function S(t,e){return(e=e||{}).ns="http://www.w3.org/2000/svg",function(t,e){let s;const n=(e=e||{}).ns,r=e.doc||document,i=e.attrs||{},o=e.text||"",a=e.parent||null;s=n?r.createElementNS(n,t):r.createElement(t),null!=a&&a.appendChild(s);for(const t in i||{}){const e=i[t];s.setAttribute(t,e)}return o&&(s.textContent=o),s}(t,e)}function y(t,e){for(t=Math.abs(t),e=Math.abs(e);e>0;){const s=e;e=t%e,t=s}return t}p.IS_EXPLORER=()=>navigator&&navigator.userAgent.indexOf("MSIE")>-1,p.IS_FIREFOX=()=>navigator&&navigator.userAgent.indexOf("Firefox")>-1,p.IS_OPERA=()=>navigator&&navigator.userAgent.toLowerCase().indexOf("op")>-1,p.UAHasChrome=()=>navigator&&navigator.userAgent.indexOf("Chrome")>-1,p.UAHasSafari=()=>navigator&&navigator.userAgent.indexOf("Safari")>-1,p.IS_SAFARI=()=>navigator&&p.UAHasSafari()&&(!p.UAHasChrome()||!p.UAHasSafari()),p.IS_CHROME=()=>navigator&&p.UAHasChrome()&&(!p.UAHasChrome()||!p.IS_OPERA());class E{constructor(t=0,e=1,s=!1){if(isNaN(t)||isNaN(e))throw new Error(`Invalid numerator(${t}) or denminator(${e})`);if(s){const s=y(t,e);t/=s,e/=s}this.num=t,this.den=e}static parse(t,e=!1){const s=t.trim().split("/").map(t=>t.trim());let n=1,r=1;if(1==s.length)n=parseInt(s[0]);else{if(2!=s.length)throw new Error("Invalid fraction string: "+t);s[0].length>0&&(n=parseInt(s[0])),s[1].length>0&&(r=parseInt(s[1]))}if(isNaN(n)||isNaN(r))throw new Error("Invalid fraction string: "+t);return new E(n,r,e)}get isWhole(){return this.num%this.den==0}get isZero(){return 0==this.num}get isInfinity(){return 0==this.den}get isOne(){return this.num==this.den}get ceil(){return this.num%this.den==0?this.num/this.den:1+Math.floor(this.num/this.den)}get floor(){return this.num%this.den==0?this.num/this.den:Math.floor(this.num/this.den)}plus(t,e=!1){return new E(this.num*t.den+this.den*t.num,this.den*t.den,e)}plusNum(t,e=!1){return new E(this.num+this.den*t,this.den,e)}minus(t,e=!1){return new E(this.num*t.den-this.den*t.num,this.den*t.den,e)}minusNum(t,e=!1){return new E(this.num-this.den*t,this.den,e)}times(t,e=!1){return new E(this.num*t.num,this.den*t.den,e)}timesNum(t,e=!1){return new E(this.num*t,this.den,e)}divby(t,e=!1){return new E(this.num*t.den,this.den*t.num,e)}divbyNum(t,e=!1){return new E(this.num,this.den*t,e)}numDivby(t,e=!1){return new E(this.den*t,this.num,e)}mod(t){const e=this.divby(t),s=Math.floor(e.num/e.den);return this.minus(t.timesNum(s))}modNum(t){const e=this.divbyNum(t),s=Math.floor(e.num/e.den);return this.minusNum(t*s)}get inverse(){return new E(this.den,this.num)}get factorized(){const t=y(this.num,this.den);return new E(this.num/t,this.den/t)}equals(t){return this.num*t.den==this.den*t.num}equalsNum(t){return this.num==this.den*t}cmp(t){return this.num*t.den-this.den*t.num}cmpNum(t){return this.num-this.den*t}isLT(t){return this.cmp(t)<0}isLTE(t){return this.cmp(t)<=0}isLTNum(t){return this.cmpNum(t)<0}isLTENum(t){return this.cmpNum(t)<=0}isGT(t){return this.cmp(t)>0}isGTE(t){return this.cmp(t)>=0}isGTNum(t){return this.cmpNum(t)>0}isGTENum(t){return this.cmpNum(t)>=0}toString(){return this.num+"/"+this.den}static max(t,e){return t.cmp(e)>0?t:e}static min(t,e){return t.cmp(e)<0?t:e}}E.ZERO=new E,E.ONE=new E(1,1),E.INFINITY=new E(1,0);const w=(t=0,e=1,s=!1)=>new E(t,e,s),C=E.ZERO;E.ONE;class v{constructor(t,e=0,s=0,n=0){this.cycle=t,this.barIndex=e,this.beatIndex=s,this.instance=n}get next(){const t=this.cycle.bars[this.barIndex],e=[[this.barIndex,this.beatIndex,this.instance],t.beatLengths[this.beatIndex]];return this.instance++,(!t.beatCounts[this.beatIndex]||this.instance>=t.beatCounts[this.beatIndex])&&(this.instance=0,this.beatIndex++,this.beatIndex>=t.beatLengths.length&&(this.beatIndex=0,this.barIndex++,this.barIndex>=this.cycle.bars.length&&(this.barIndex=0))),e}get prev(){const t=this.cycle.bars[this.barIndex],e=[[this.barIndex,this.beatIndex,this.instance],t.beatLengths[this.beatIndex]];return this.instance--,this.instance<0&&(this.beatIndex--,this.beatIndex<0&&(this.barIndex--,this.barIndex<0&&(this.barIndex=this.cycle.bars.length-1),this.beatIndex=this.cycle.bars[this.barIndex].beatCount-1),this.instance=(this.cycle.bars[this.barIndex].beatCounts[this.beatIndex]||1)-1),e}}class x extends o{constructor(t=null){super(t=t||{}),this.TYPE="Bar",this.beatLengths=[],this.beatCounts=[],this.name=t.name||"";for(const e of t.beatLengths||[])"number"==typeof e?this.beatLengths.push(w(e)):this.beatLengths.push(e);for(const e of t.beatCounts||[])this.beatCounts.push(e);for(;this.beatCounts.length<this.beatLengths.length;)this.beatCounts.push(1)}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{name,beatLengths:this.beatLengths})}equals(t){if(!super.equals(t))return!1;if(this.beatLengths.length!=t.beatLengths.length)return!1;if(this.beatCounts.length!=t.beatCounts.length)return!1;for(let e=0;e<this.beatLengths.length;e++)if(!this.beatLengths[e].equals(t.beatLengths[e]))return!1;for(let e=0;e<this.beatCounts.length;e++)if(this.beatCounts[e]!=t.beatCounts[e])return!1;return!0}copyTo(t){super.copyTo(t),t.name=this.name,t.beatLengths=[...this.beatLengths],t.beatCounts=[...this.beatCounts]}instanceCount(t){return t>this.beatCounts.length?1:this.beatCounts[t]}get beatCount(){return this.beatLengths.length}get totalBeatCount(){let t=0;for(let e=0;e<this.beatLengths.length;e++)t+=this.beatCounts[e]||1;return t}get duration(){let t=C;for(let e=0;e<this.beatLengths.length;e++)t=t.plus(this.beatLengths[e].timesNum(this.beatCounts[e]||1));return t}}class _ extends o{constructor(t=null){super(t=t||{}),this.TYPE="Cycle",this.name=t.name||"",this.bars=t.bars||[]}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{name,bars:this.bars.map(t=>t.debugValue())})}children(){return this.bars}equals(t){if(!super.equals(t))return!1;if(this.bars.length!=t.bars.length)return!1;for(let e=0;e<this.bars.length;e++)if(!this.bars[e].equals(t.bars[e]))return!1;return!0}getAtIndex(t){let e=0;for(;t<0;)t+=this.totalBeatCount,e--;t>=this.totalBeatCount&&(e=Math.floor(t/this.totalBeatCount)),t%=this.totalBeatCount;let s=C;for(let n=0;n<this.bars.length;n++){const r=this.bars[n];if(t>=r.totalBeatCount)t-=r.totalBeatCount,s=s.plus(r.duration);else for(let i=0;i<r.beatCount;i++){const o=r.beatLengths[i],a=r.beatCounts[i]||1;if(!(t>=a)){const r=t;return[e,[n,i,r],s.plus(o.timesNum(r))]}t-=a,s=s.plus(o.timesNum(a))}}throw new Error("Should not be here!")}getPosition(t){const e=this.duration;let s=0;if(t.isLT(C))for(;t.isLT(C);)s--,t=t.plus(e);else if(t.isGTE(e)){const n=t.mod(e);a((t=t.minus(n).divby(e)).isWhole),s=t.floor,t=n}let n=0;for(let e=0;e<this.bars.length;e++){const r=this.bars[e],i=r.duration;if(t.isGTE(i))t=t.minus(i);else for(let i=0;i<r.beatCount;i++){const o=r.beatLengths[i],a=r.beatCounts[i]||1;for(let r=0;r<a;r++,n++){if(!t.isGTE(o))return[s,[e,i,r],t,n];t=t.minus(o)}}n+=r.totalBeatCount}throw new Error("Should not be here!")}*iterateBeats(t=0,e=0,s=0){let n=t,r=e,i=s;for(;;){const t=this.bars[n];yield[[n,r,i],t.beatLengths[r]],i++,(!t.beatCounts[r]||i>=t.beatCounts[r])&&(i=0,r++,r>=t.beatLengths.length&&(r=0,n++,n>=this.bars.length&&(n=0)))}}copyTo(t){super.copyTo(t),t.name=this.name,t.bars=this.bars.map(t=>t.clone())}get beatCount(){let t=0;for(const e of this.bars)t+=e.beatCount;return t}get totalBeatCount(){let t=0;for(const e of this.bars)t+=e.totalBeatCount;return t}get duration(){return this.bars.reduce((t,e)=>t.plus(e.duration),C)}}_.DEFAULT=new _({name:"Adi Thalam",bars:[new x({name:"Laghu",beatLengths:[1,1,1,1]}),new x({name:"Dhrutam",beatLengths:[1,1]}),new x({name:"Dhrutam",beatLengths:[1,1]})]});const A=E.ZERO,N=E.ONE;var T,I;(I=T||(T={})).NOTE="Note",I.LITERAL="Literal",I.SYLLABLE="Syllable",I.SPACE="Space",I.GROUP="Group",I.LABEL="Label",I.REST="Rest",I.MARKER="Marker";class O extends o{constructor(t=N){super(),this.TYPE="Atom",this.nextSibling=null,this.prevSibling=null,this.parentGroup=null,this.isContinuation=!1,this._duration=t||N}debugValue(){const t=super.debugValue();return this.duration.isOne||(t.duration=this.duration.factorized.toString()),this.isContinuation&&(t.isContinuation=!0),(this.markersBefore||[]).length>0&&(t.mbef=this.markersBefore.map(t=>t.debugValue())),(this.markersAfter||[]).length>0&&(t.maft=this.markersAfter.map(t=>t.debugValue())),t}copyTo(t){super.copyTo(t),t._duration=new E(this.duration.num,this.duration.den)}get duration(){return this._duration}set duration(t){this._duration=t}}class R extends O{constructor(){super(...arguments),this.TYPE="LeafAtom",this.beforeRest=!1}splitAt(t){if(this.duration.cmp(t)>0){const e=this.createSpilloverSpace(this.duration.minus(t));return e.isContinuation=!0,this.duration=t,e}return null}createSpilloverSpace(t){return new L(t)}debugValue(){return this.beforeRest?Object.assign(Object.assign({},super.debugValue()),{beforeRest:!0}):super.debugValue()}}class k extends i{constructor(t,e=!0){super(),this.text=t,this.isBefore=e,this.TYPE="Marker"}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{text:this.text,before:this.isBefore})}toString(){return`Marker(${this.text}-${this.isBefore})`}}class L extends R{constructor(t=N,e=!1){super(t),this.TYPE="Space",this.isSilent=!1,this.isSilent=e}debugValue(){return Object.assign(Object.assign({},super.debugValue()),{isSilent:this.isSilent})}toString(){return`Space(${this.duration}-${this.isSilent})`}copyTo(t){super.copyTo(t),t.isSilent=this.isSilent}equals(t){return super.equals(t)&&this.isSilent==t.isSilent}createSpilloverSpace(t){const e=super.createSpilloverSpace(t);return e.isSilent=this.isSilent,e}}class M extends R{constructor(t,e=N){super(e),this.value=t,this.TYPE="Literal",this.embelishments=[]}debugValue(){const t=Object.assign(Object.assign({},super.debugValue()),{value:this.value});return this.embelishments.length>0&&(t.embs=this.embelishments.map(t=>"debugValue"in t?t.debugValue():t)),t}toString(){return`Lit(${this.duration}-${this.value})`}equals(t){return super.equals(t)&&this.value==t.value}copyTo(t){super.copyTo(t),t.value=this.value}}class P extends M{constructor(){super(...arguments),this.TYPE="Syllable"}static fromLit(t){if(t.TYPE==T.SYLLABLE)return t;const e=new P(t.value,t.duration);return e.embelishments=t.embelishments,e.beforeRest=t.beforeRest,e}toString(){return`Syll(${this.duration}-${this.value})`}}class B extends M{constructor(t,e=N,s=0,n=0){super(t,e),this.TYPE="Note",this.octave=0,this.shift=0,this.octave=s,this.shift=n}static fromLit(t){if(t.TYPE==T.NOTE)return t;const e=new B(t.value,t.duration);return e.embelishments=t.embelishments,e.beforeRest=t.beforeRest,e}debugValue(){const t=Object.assign({},super.debugValue());return 0!=this.octave&&(t.octave=this.octave),0!=this.shift&&(t.shift=this.shift),t}toString(){return`Note(${this.duration}-${this.value}-${this.octave})`}equals(t){return super.equals(t)&&this.octave==t.octave&&this.shift==t.shift}copyTo(t){super.copyTo(t),t.octave=this.octave,t.shift=this.shift}}class $ extends O{constructor(...t){super(0==t.length?A:N),this.TYPE="Group",this.durationIsSpeedMultiplier=!1,this.atoms=new f,this._observers=[],this.addAtoms(!1,...t)}addObserver(t){return this._observers.push(t),()=>this.removeObserver(t)}removeObserver(t){const e=this._observers.indexOf(t);e>=0&&this._observers.splice(e,1)}notifyObservers(e,s,n){var r,i,o;if(this._eventsEnabled)for(const a of this._observers)switch(e){case t.ADD:null===(r=a.onAtomsAdded)||void 0===r||r.call(a,this,s,n);break;case t.INSERT:null===(i=a.onAtomsInserted)||void 0===i||i.call(a,this,s,n);break;case t.REMOVE:null===(o=a.onAtomsRemoved)||void 0===o||o.call(a,this,s)}}equals(t,e=!1){return!!super.equals(t)&&this.atoms.equals(t.atoms,(t,e)=>t.equals(e))}copyTo(t){super.copyTo(t),t.durationIsSpeedMultiplier=this.durationIsSpeedMultiplier;for(const e of this.atoms.values())t.atoms.add(e.clone())}get duration(){return this.durationIsSpeedMultiplier?this.totalChildDuration.divby(this._duration):this._duration}setDurationAsMultiplier(t=!0){return this.durationIsSpeedMultiplier=t,this}setDuration(t,e=!1){return this._duration=t,this.durationIsSpeedMultiplier=e,this}debugValue(){const t=Object.assign(Object.assign({},super.debugValue()),{atoms:Array.from(this.atoms.values(),t=>t.debugValue())});return this.durationIsSpeedMultiplier&&(t.durationIsSpeedMultiplier=!0),t}splitAt(t){if(this.duration.isLTE(t)||t.isLTE(A))return null;const e=new $;this.durationIsSpeedMultiplier&&(e.durationIsSpeedMultiplier=!0,e._duration=this._duration);let s=this.duration;const n=this.totalChildDuration,r=this.durationIsSpeedMultiplier?N.divby(this._duration):this._duration.divby(n,!0);for(;s.isGT(t)&&this.atoms.last;){const n=this.atoms.last,i=n.duration.times(r),o=s.minus(i);if(!o.isGTE(t)){const s=t.minus(o,!0).divby(r,!0),i=n.splitAt(s);if(null==i)throw new Error("Spill over cannot be null here");if(this.durationIsSpeedMultiplier){if(this._duration.isZero)throw new Error("How can this be?")}else this._duration=t;return i.isContinuation=!0,e.insertAtomsAt(e.atoms.first,!0,i),e}if(this.removeAtoms(!0,n),e.insertAtomsAt(e.atoms.first,!0,n),o.equals(t))return e;s=o}return e}get totalChildDuration(){let t=A;for(const e of this.atoms.values())t=t.plus(e.duration);return t}insertAtomsAt(e,s=!1,...n){const r=(s=s&&!this.durationIsSpeedMultiplier)?this.totalChildDuration:N;let i;if(e){i=0;for(const t of this.atoms.values()){if(t===e)break;i++}}else i=this.atoms.size;const o=[];for(const t of n){if(null!=t.parentGroup){if(t.parentGroup!=this)throw new Error("Atom belongs to another parent. Remove it first");t.parentGroup.removeAtoms(!1,t)}if(t.TYPE==T.REST){const t=this.atoms.last;t&&t.TYPE!=T.GROUP&&t.TYPE!=T.LABEL&&(t.beforeRest=!0)}else t.parentGroup=this,this.atoms.add(t,e),o.push(t)}if(s)if(this._duration.isZero){if(this.durationIsSpeedMultiplier)throw new Error("How can this be?");this._duration=this.totalChildDuration}else{const t=this.totalChildDuration.divby(r);this._duration=this._duration.times(t,!0)}if(o.length>0){const s=e?t.INSERT:t.ADD;this.notifyObservers(s,o,i)}return this}addAtoms(t=!1,...e){return this.insertAtomsAt(null,t,...e)}removeAtoms(e=!1,...s){const n=(e=e&&!this.durationIsSpeedMultiplier)?this.totalChildDuration:N,r=[];for(const t of s)if(t.parentGroup==this)this.atoms.remove(t),t.parentGroup=null,r.push(t);else if(null!=t.parentGroup)throw new Error("Atom cannot be removed as it does not belong to this group");if(e)if(this._duration.isZero){if(this.durationIsSpeedMultiplier)throw new Error("How can this be?");this._duration=this.totalChildDuration}else{const t=this.totalChildDuration.divby(n);this._duration=this._duration.times(t,!0)}return r.length>0&&this.notifyObservers(t.REMOVE,r,-1),this}}const D=E.ZERO;class V{constructor(t){this.uuid=V.counter++,t=t||{},this.beatDuration=t.beatDuration||1,"cycle"in t&&(this.cycle=t.cycle),this.cycle&&!this.cycle.duration.isZero||(this.cycle=_.DEFAULT),this._rowStartOffsets=[],this._rowEndOffsets=[],this._rowDurations=[],this._totalLayoutDuration=D,this._totalBeats=0,this._beatLayouts=[],this.lineBreaks=t.lineBreaks||t.layout||[]}equals(t){return this.beatDuration==t.beatDuration&&this.cycle.equals(t.cycle)&&this.lineBreaksEqual(t._lineBreaks)}lineBreaksEqual(t){return this._lineBreaks.length==t.length&&this._lineBreaks.every((e,s)=>e==t[s])}debugValue(){var t;return{cycle:null===(t=this.cycle)||void 0===t?void 0:t.debugValue(),beatDuration:this.beatDuration,lineBreaks:this._lineBreaks}}getBeatLocation(t){const e=t.index%this.totalBeats;let s=0;for(let n=0;n<this._lineBreaks.length;n++){if(e<s+this._lineBreaks[n]){let r=D;if(e>s){const n=new v(this.cycle,t.barIndex,t.beatIndex,t.instance);let[,i]=n.prev;for(let t=s;t<e;t++)[,i]=n.prev,r=r.plus(i.timesNum(this.beatDuration))}return[n,e-s,r]}s+=this._lineBreaks[n]}throw new Error("Invalid beat index: "+t.index)}get lineBreaks(){return this._lineBreaks&&0!=this._lineBreaks.length||(this.lineBreaks=[this.cycle.beatCount]),this._lineBreaks}set lineBreaks(t){this._lineBreaks=t,this.refreshLayout()}get beatLayouts(){return(!this._beatLayouts||this._beatLayouts.length<this.lineBreaks.length)&&this.refreshLayout(),this._beatLayouts}get totalBeats(){return this.beatLayouts,this._totalBeats}get totalLayoutDuration(){return this.beatLayouts,this._totalLayoutDuration}refreshLayout(){const t=this.cycle.iterateBeats(),e=this.beatDuration;this._beatLayouts=this.lineBreaks.map((s,n)=>{const r=[];for(let n=0;n<s;n++){const s=t.next().value;s[1]=s[1].timesNum(e),r.push(s)}return r}),this._totalBeats=this.lineBreaks.reduce((t,e)=>t+e,0),this._rowDurations=this._beatLayouts.map(t=>t.reduce((t,e)=>t.plus(e[1]),D)),this._rowDurations.forEach((t,e)=>{this._rowStartOffsets[e]=0==e?D:this._rowStartOffsets[e-1].plus(t)}),this._rowEndOffsets=this._rowDurations.map((t,e)=>this._rowStartOffsets[e].plus(t)),this._totalLayoutDuration=this._rowDurations.reduce((t,e)=>t.plus(e),D)}}V.counter=0;class U extends c{constructor(){super(...arguments),this.uuid=U.idCounter++,this.lastUpdatedAt=0,this.rows=[],this.rowAligns=new Map,this.colAligns=new Map}debugValue(){return{rows:this.rows.map(t=>t.debugValue()),lastUpdatedAt:this.lastUpdatedAt}}get firstRow(){for(const t of this.rows)if(t.numCells>0)return t.rowIndex;return-1}get firstCol(){let t=-1;for(const e of this.rows){const s=e.firstCol;s>=0&&(t<0||s<t)&&(t=s)}return t}cellsInRow(t){const e=[],s=this.rows[t];if(s)for(const t of s.cells)(null==t?void 0:t.value)&&e.push(t);return e}cellsInCol(t){const e=[];for(const s of this.rows){const n=s.cellAt(t);(null==n?void 0:n.value)&&e.push(n)}return e}addRowAlign(t){this.rowAligns.set(t.uuid,t)}addColAlign(t){this.colAligns.set(t.uuid,t)}addRows(t=-1,e=1){t<0&&(t=this.rows.length);let s=this.rows[t]||null;const n=this.rows[t-1]||null;for(let r=e-1;r>=0;r--){const e=new G(this,t+r);this.rows.splice(t,0,e),null!=s&&e.defaultRowAlign.addSuccessor(s.defaultRowAlign),0==r&&t>0&&n.defaultRowAlign.addSuccessor(e.defaultRowAlign),s=e}for(let s=t+e;s<this.rows.length;s++)this.rows[s].rowIndex+=e;return this}getRow(t){return t>=this.rows.length&&this.addRows(-1,1+t-this.rows.length),this.rows[t]}setValue(t,e,s,n){var r,i;const o=this.getRow(t);if(n||(n=(t,e)=>new j(t,e)),null==s){const t=o.clearCellAt(e);return null!=t&&(null===(r=this.eventHub)||void 0===r||r.emit(F.CLEARED,this,{loc:t.location})),t}{const t=o.cellAt(e,n),r=t.value;return null===(i=this.eventHub)||void 0===i||i.emit(F.UPDATED,this,{loc:t.location,cell:t,oldValue:t.value}),t.value=s,r}}eventHubChanged(){console.log("Event Hub Changed for GridModel")}}var F;U.idCounter=0,function(t){t.ADDED="CellAdded",t.CLEARED="CellCleared",t.REMOVED="CellRemoved",t.UPDATED="CellUpdated",t.MOVED="CellMoved"}(F||(F={}));class j{constructor(t,e,s=null){this.gridRow=t,this.colIndex=e,this.value=s,this.uuid=j.idCounter++,this.rowAlign=t.defaultRowAlign}get rowAlign(){return this._rowAlign}set rowAlign(t){t.addCell(this),this._rowAlign=t}get colAlign(){return this._colAlign}set colAlign(t){t.addCell(this),this._colAlign=t}get location(){return this.gridRow.rowIndex+":"+this.colIndex}get grid(){return this.gridRow.grid}get rowIndex(){return this.gridRow.rowIndex}debugValue(){const t={r:this.gridRow.rowIndex,c:this.colIndex,value:this.value,y:this.rowAlign.coordOffset,h:this.rowAlign.maxLength};return this.colAlign&&(t.x=this.colAlign.coordOffset,t.w=this.colAlign.maxLength),t}}j.idCounter=0;class G{constructor(t,e){this.grid=t,this.rowIndex=e,this.cells=[],this.defaultRowAlign=new W,this.grid.addRowAlign(this.defaultRowAlign)}get firstCol(){var t;for(let e=0;e<this.cells.length;e++)if(null===(t=this.cells[e])||void 0===t?void 0:t.value)return e;return-1}get numCols(){return this.cells.length}get numCells(){let t=0;for(const e of this.cells)null!=e&&null!=e.value&&t++;return t}cellAt(t,e){let s=this.cells[t]||null;return!s&&e&&(this.cells[t]=s=e(this,t),s.gridRow=this,s.colIndex=t,s.rowAlign&&this.grid.addRowAlign(s.rowAlign),s.colAlign&&this.grid.addColAlign(s.colAlign)),s}clearCellAt(t){const e=this.cells[t]||null;return e&&(this.cells[t]=null),e}debugValue(){return{r:this.rowIndex,cells:this.cells.filter(t=>t).map(t=>null==t?void 0:t.debugValue())}}}class z{constructor(){this.uuid=z.idCounter++,this.needsLayout=!1,this._coordOffset=0,this._maxLength=0,this.paddingBefore=5,this.paddingAfter=5,this.cells=[],this.prevLines=[],this.nextLines=[]}get coordOffset(){return this._coordOffset}get maxLength(){return this._maxLength+this.paddingBefore+this.paddingAfter}setMaxLength(t){this._maxLength=t}setPadding(t,e){t>=0&&(this.paddingBefore=t),e>=0&&(this.paddingAfter=e)}addCell(t){return this.beforeAddingCell(t)&&this.cells.push(t),this}removeCell(t){if(this.beforeRemovingCell(t))for(let e=0;e<this.cells.length;e++)if(this.cells[e].uuid==t.uuid){this.cells.splice(e,1);break}return this}addSuccessor(t){for(const e of this.nextLines)if(e==t)return;this.nextLines.push(t),t.prevLines.push(this)}}z.idCounter=0;class W extends z{setOffset(t){this._coordOffset=t;for(const e of this.cells)if(e.value){const s=this.getCellView(e);this._maxLength<=0&&this.evalMaxLength(),s.setBounds(null,t,null,this.maxLength,!0)}}evalMaxLength(t=[]){this._maxLength=0;for(const t of this.cells)if(t.value){const e=this.getCellView(t);this._maxLength=Math.max(e.minSize.height,this._maxLength)}return this._maxLength}beforeAddingCell(t){return t.rowAlign&&t.rowAlign!=this&&t.rowAlign.removeCell(t),t.rowAlign!=this}beforeRemovingCell(t){return t.rowAlign==this}}E.ZERO;const K=E.ONE;class H{constructor(t,e,s,n,r,i,o,a,l){this.index=t,this.role=e,this.offset=s,this.duration=n,this.barIndex=r,this.beatIndex=i,this.instance=o,this.prevBeat=a,this.nextBeat=l,this.uuid=H.idCounter++,this.atomIsPlaceholder=!1}debugValue(){return{index:this.index,role:this.role.name,offset:this.offset.toString(),duration:this.duration.toString(),barIndex:this.barIndex,beatIndex:this.beatIndex,instance:this.instance,atom:this.atom.debugValue()}}get endOffset(){return this.offset.plus(this.duration)}get filled(){return this.remaining.isZero}get remaining(){return this.atom?this.duration.minus(this.atom.duration,!0):this.duration}add(t){return!(this.remaining.cmp(t.duration)<0||(this.atom?(this.atomIsPlaceholder||(this.atomIsPlaceholder=!0,this.atom=new $(this.atom).setDuration(K,!0)),this.atom.addAtoms(!0,t)):this.atom=t,0))}get preMarkers(){const t=[];let e=this.atom;for(;null!=e;){for(const s of e.markersBefore||[])t.push(s);e=e.TYPE==T.GROUP?e.atoms.first:null}return t}get postMarkers(){const t=[];let e=this.atom;for(;null!=e;)t.splice(0,0,...e.markersAfter||[]),e=e.TYPE==T.GROUP?e.atoms.last:null;return t}}function q(t,e,s){const n=[],r={};return t.forEach(t=>{if(!(e(t)in r)){const i=t,o={};let l=[[t,[]]];for(;l.length>0;){const t=[];for(let h=0;h<l.length;h++){const[u,c]=l[h];a(null!=u);const d=s(u);let f=[...c];for(const[s,a]of d)s==i?(f.push([a,s]),f.forEach(([t,e],s)=>r[e]=!0),n.push([i,f]),f=f.slice(0,f.length-1)):e(s)in o||(o[e(s)]=!0,t.push([s,[...f,[a,s]]]))}l=t}}}),n}H.idCounter=0;const Q=t=>t.key;class Y{constructor(t=Q){this._entries=[],this._entriesByKey={},this.keyFunc=t}clear(){this._entries=[],this._entriesByKey={}}remove(t){const e=[];this._entriesByKey={};let s=!1;for(let n=0;n<this._entries.length;n++){const r=this._entries[n];t(r)?s=!0:(r.id=e.length,e.push(r),this._entriesByKey[this.keyFunc(r)]=r)}return this._entries=e,s}get entries(){return this._entries}get(t){return a(t>=0&&t<this._entries.length),this._entries[t]}getByKey(t){return this._entriesByKey[t]||null}ensure(t,e=!1){if(this.has(t)){if(e)throw new Error(`Entry ${this.keyFunc(t)} already exists`);return this._entriesByKey[this.keyFunc(t)]}return this._entriesByKey[this.keyFunc(t)]=t,t.id=this._entries.length,this._entries.push(t),t}has(t){return this.keyFunc(t)in this._entriesByKey}get size(){return this._entries.length}}class J{constructor(t,e=!0){this.entries=new Set,this.hasNull=!1,this.grammar=t,this.enforceSymbolType=e}get debugString(){return"<"+this.labels().sort().join(", ")+">"}labels(t=!1){const e=[];for(const s of this.entries){const n=this.grammar.getSymById(s);a(null!=n),t&&n.isAuxiliary||e.push(n.label)}return this.hasNull&&e.push(""),e}addFrom(t,e=!0){return t.addTo(this,e)}addTo(t,e=!0){const s=t.entries.size;for(const e of this.entries)t.entries.add(e);return e&&(t.hasNull=this.hasNull||t.hasNull),t.entries.size-s}has(t){return this.entries.has(t.id)}add(t){return a(null==this.enforceSymbolType||this.enforceSymbolType==t.isTerminal,`Terminal types being enforced: ${this.enforceSymbolType}`),this.entries.add(t.id),this}delete(t){return this.entries.delete(t.id)}get size(){return this.entries.size+(this.hasNull?1:0)}}class Z{constructor(t){this.grammar=t,this.refresh()}get nonterms(){const t=[];return this.entries.forEach(e=>{const s=this.grammar.getSymById(e);a(null!=s&&!s.isTerminal),t.push(s)}),t}refresh(){this.entries=new Set,this.visited={};let t=0;do{t=this.entries.size,this.grammar.allNonTerminals.forEach(t=>this.visit(t))}while(t!=this.entries.size)}visit(t){for(const e of this.grammar.rulesForNT(t))if(this.isStrNullable(e.rhs)){this.add(t);break}}isNullable(t){return!t.isTerminal&&this.entries.has(t.id)}isStrNullable(t,e=0,s=null){null==s&&(s=t.length-1);for(let n=e;n<=s;n++)if(!this.isNullable(t.syms[n]))return!1;return!0}add(t){a(!t.isTerminal),this.entries.add(t.id)}}class X{constructor(t){this.entries={},this._count=0,this.grammar=t}refresh(){this.entries={},this._count=0}forEachTerm(t,e){const s=this.entriesFor(t);s.entries.forEach(t=>{const s=this.grammar.getSymById(t);a(null!=s&&s.isTerminal),e(s)}),s.hasNull&&e(null)}get debugValue(){const t={};for(const e in this.entries)t[this.grammar.getSymById(e).label]=this.entries[e].debugString;return t}get count(){let t=0;for(const e in this.entries)t+=this.entries[e].size;return t}entriesFor(t){if(t.id in this.entries)return this.entries[t.id];{const e=new J(this.grammar);return this.entries[t.id]=e,e}}addNull(t){const e=this.entriesFor(t);return!e.hasNull&&(e.hasNull=!0,!0)}add(t,e,s=!0){t.isTerminal&&a(!1,"Should not be here");const n=this.entriesFor(t);if(e.isTerminal){if(n.has(e))return!1;n.add(e),this._count++}else{const n=this.entriesFor(e),r=this.entriesFor(t),i=n.addTo(r,s);this._count+=i}return!0}}class tt extends X{constructor(t,e){super(t),e||(e=new Z(t)),this.nullables=e,this.refresh()}forEachTermIn(t,e=0,s){const n=t.syms,r={};let i=!0;for(let t=e;i&&t<n.length;t++){const e=n[t];if(e.isTerminal)s(e),i=!1;else{const t=e;this.forEachTerm(t,t=>{null==t||t.id in r||(r[t.id]=!0,s(t))}),this.nullables.isNullable(e)||(i=!1)}}i&&s(null)}refresh(){super.refresh();let t=0;do{t=this.count,this.grammar.forEachRule(null,t=>{this.processRule(t)})}while(t!=this.count)}processRule(t){const e=this.nullables;let s=!0;for(const n of t.rhs.syms)if(this.add(t.nt,n,!1),n.isTerminal||!e.isNullable(n)){s=!1;break}s&&this.addNull(t.nt)}}class et extends X{constructor(t,e){super(t),this.firstSets=e||new tt(t),this.refresh()}get nullables(){return this.firstSets.nullables}refresh(){super.refresh();const t=this.grammar;a(null!=t.startSymbol,"Select start symbol of the grammar"),this.add(t.startSymbol,t.Eof);let e=0;do{e=this.count,this.grammar.forEachRule(null,t=>this.processRule(t))}while(e!=this.count)}processRule(t){const e=t.rhs.syms,s=this.firstSets,n=this.firstSets.nullables;for(let n=0;n<e.length;n++){const r=e[n];r.isTerminal||s.forEachTermIn(t.rhs,n+1,t=>{null!=t&&this.add(r,t)})}for(let s=e.length-1;s>=0;s--){if(e[s].isTerminal)continue;let r=!0;for(let t=s+1;t<e.length;t++){const s=e[t];if(s.isTerminal||!n.isNullable(s)){r=!1;break}}r&&this.add(e[s],t.nt)}}}class st{constructor(t,e,s,n=null){this.grammar=t,this.label=e,this.isTerminal=s,this.isAuxiliary=!1,this.auxType=null,this.precedence=1,this.assocLeft=!0,this.creationId=-1,this.isTerminal=s,this.label=e,this.id=null==n?st.idCounter--:n}compareTo(t){return this.label.localeCompare(t.label)}equals(t){return this.label==t.label}toString(){return this.label}}st.idCounter=-1;class nt{constructor(...t){this.syms=t||[]}append(...t){for(const e of t)this.syms.push(e);return this}extend(...t){for(const e of t)this.append(...e.syms);return this}copy(){return new nt(...this.syms)}add(t){this.syms.push(t)}isTerminal(t){return this.syms[t].isTerminal}get length(){return this.syms.length}toString(){return this.syms.map(t=>t.toString()).join(" ")}slice(t,e){return new nt(...this.syms.slice(t,e))}splice(t,e,...s){return this.syms.splice(t,e,...s),this}compareTo(t){for(let e=0;e<this.syms.length&&e<t.syms.length;e++){const s=this.syms[e].compareTo(t.syms[e]);if(0!=s)return s}return this.syms.length-t.syms.length}equals(t){return 0==this.compareTo(t)}containsAt(t,e){let s=0;for(;s<e.length&&t+s<this.syms.length;s++)if(!this.syms[t+s].equals(e.syms[s]))return!1;return s==e.length}get debugString(){return this.syms.map(t=>t.label).join(" ")}}class rt{constructor(t){this.value=t}get isFunction(){return"string"==typeof this.value}get isChildPosition(){return"number"==typeof this.value}}class it{constructor(t,e,s=null){if(this.nt=t,this.rhs=e,this.action=s,t.isTerminal)throw new Error("Cannot add rules to a terminal")}get debugString(){return`${this.nt.label} -> ${this.rhs.debugString}`}equals(t){return 0==this.compareTo(t)}compareTo(t){a(!isNaN(this.id));const e=this.nt.compareTo(t.nt);return 0==e&&this.rhs.compareTo(t.rhs),e}}class ot{static make(t){const e=new ot;return t(e),e}constructor(t){this.startSymbol=null,this.modified=!0,this.symbolSet=new Y(t=>t.label),this.allRules=[],this._rulesForNT=null,this._followSets=null,this._hasNull=!1,this.auxNTCount=0,t=t||{},this.auxNTPrefix=t.auxNTPrefix||"$",this.Null=this.newTerm(""),this.Eof=this.newTerm("$end")}rulesForNT(t){if(a(!t.isTerminal),null==this._rulesForNT){this._rulesForNT={};for(const t of this.allRules)t.nt.label in this._rulesForNT||(this._rulesForNT[t.nt.label]=[]),this._rulesForNT[t.nt.label].push(t)}return t.label in this._rulesForNT||(this._rulesForNT[t.label]=[]),this._rulesForNT[t.label]}get nullables(){return this.firstSets.nullables}get firstSets(){return this.followSets.firstSets}get followSets(){return(this.modified||null==this._followSets)&&this.refresh(),a(null!=this._followSets),this._followSets}get augStartRule(){return this._AugStartRule}augmentStartSymbol(t="$accept"){a(null==this._AugStartRule,"Ensure this grammar has not yet been augmented."),a(null!=this.startSymbol,"Start symbol not yet set");const e=this.newNT(t);return this._AugStartRule=new it(e,new nt(this.startSymbol)),this.addRule(this._AugStartRule,0),this}refresh(){return this.symbolSet.entries.forEach((t,e)=>t.id=e),this._rulesForNT=null,this.allRules.forEach((t,e)=>{t.id=e}),this._followSets=new et(this),this.modified=!1,this}addTerminals(...t){for(const e of t)this.newTerm(e)}get terminals(){return this.symbolSet.entries.filter(t=>t.isTerminal)}get allNonTerminals(){return this.symbolSet.entries.filter(t=>!t.isTerminal)}get nonTerminals(){return this.symbolSet.entries.filter(t=>!t.isTerminal&&!t.isAuxiliary)}get auxNonTerminals(){return this.symbolSet.entries.filter(t=>t.isAuxiliary)}get allSymbols(){return this.symbolSet.entries}forEachNT(t){for(const e of this.symbolSet.entries)if(!e.isTerminal&&0==t(e))return}forEachRule(t,e){const s=null==t?this.allRules:this.rulesForNT(t)||[];for(let t=0;t<s.length;t++)if(0==e(s[t],t))return!1;return!0}getRule(t,e){return"string"==typeof t&&(t=this.getSym(t)),a(null!=t),this.rulesForNT(t)[e]}findRule(t,e){return this.rulesForNT(t).findIndex(s=>s.nt==t&&s.rhs.equals(e))}add(t,e,s=null){let n=null;return"string"==typeof t?(n=this.getSym(t),null==n&&(n=this.newNT(t))):n=this.ensureSym(t),this.addRule(new it(n,e,s))}addRule(t,e=-1){if(this.findRule(t.nt,t.rhs)>=0)throw new Error("Duplicate rule: "+t.debugString);return t.id=this.allRules.length,0==t.rhs.length&&(this._hasNull=!0),e<0?this.allRules.push(t):this.allRules.splice(e,0,t),this._rulesForNT=null,this.modified=!0,t}removeRules(t){return this.allRules=this.allRules.filter(e=>!t(e)),this._rulesForNT=null,this.modified=!0,!0}removeSymbols(t){let e=!1;const s=[];return this.allRules.forEach(n=>{if(!t(n.nt))if(0==n.rhs.length)s.push(n);else{const r=new nt(...n.rhs.syms.filter(e=>!t(e)));e=e||n.rhs.length!=r.length,r.length>0&&s.push(new it(n.nt,r))}}),this.allRules=s,e=this.symbolSet.remove(t)||e,this.modified=this.modified||e,e}getSymById(t){return this.symbolSet.get(t)}getSym(t){return this.symbolSet.getByKey(t)}ensureSym(t,e=!1){const s=this.symbolSet.ensure(t,e);return t==s?s.creationId<0&&(s.creationId=this.symbolSet.size):a(!e,"Should have already thrown error"),s}T(t,e=!1){let s=this.getSym(t);if(null!=s){if(e)throw new Error(`Terminal ${t} is already exists`);if(!s.isTerminal)throw new Error(`Symbol (${t}) already exists as a non-terminal`)}else s=new st(this,t,!0),s=this.ensureSym(s,!0);return s}NT(t,e=!1,s=!1){let n=this.getSym(t);if(null!=n){if(s)throw new Error(`Non-terminal ${t} is already exists`);if(n.isTerminal)throw new Error(`Symbol (${t}) already exists as a terminal`)}else n=new st(this,t,!1),n.isAuxiliary=e,n=this.ensureSym(n,!0),e||null!=this.startSymbol||(this.startSymbol=n);return n}newTerm(t){return this.T(t,!0)}newNT(t,e=!1){return this.NT(t,e,!0)}isTerminal(t){const e=this.getSym(t);return null!=e&&e.isTerminal}isNT(t){const e=this.getSym(t);return null!=e&&!e.isTerminal&&!e.isAuxiliary}isAuxNT(t){const e=this.getSym(t);return null!=e&&!e.isTerminal&&e.isAuxiliary}seq(...t){if(1==t.length)return this.normalizeRule(t[0]);{const e=new nt;for(const s of t){const t=this.normalizeRule(s);for(let s=0;s<t.length;s++)e.add(t.syms[s])}return e}}anyof(...t){return 1==t.length?this.normalizeRule(t[0]):new nt(this.ensureAuxNT(...t.map(t=>this.normalizeRule(t))))}opt(t){const e=this.anyof(t,new nt),s=e.syms[0];return a(1==e.syms.length&&s.isAuxiliary,"NT must be an auxiliary symbol"),s.auxType="opt",e}atleast0(t,e=!0){const s=this.normalizeRule(t);let n=this.findAuxNT(e=>{const n=this.rulesForNT(e);if(2!=n.length)return!1;let r=0;if(0==n[0].rhs.length)r=1;else{if(0!=n[1].rhs.length)return!1;r=0}const i=n[r].rhs;return i.length==1+t.length&&(i.syms[0].equals(e)?i.containsAt(1,s):!!i.syms[i.length-1].equals(e)&&i.containsAt(0,s))});return null==n&&(n=this.newAuxNT(),n.auxType=e?"atleast0:left":"atleast0",this.add(n,new nt),e?this.add(n,new nt(n).extend(s)):this.add(n,s.copy().append(n))),new nt(n)}atleast1(t,e=!0){const s=this.normalizeRule(t);let n=this.findAuxNT(e=>{const n=this.rulesForNT(e);if(2!=n.length)return!1;let r=0;if(n[0].rhs.equals(s))r=1;else{if(!n[1].rhs.equals(s))return!1;r=0}const i=n[r].rhs;return i.length==1+t.length&&(i.syms[0].equals(e)?i.containsAt(1,s):!!i.syms[i.length-1].equals(e)&&i.containsAt(0,s))});return null==n&&(n=this.newAuxNT(),n.auxType=e?"atleast1:left":"atleast1",this.add(n,s),e?this.add(n,new nt(n).extend(s)):this.add(n,s.copy().append(n))),new nt(n)}normalizeRule(t){if("string"==typeof t){const e=this.getSym(t);if(null==e)throw new Error(`Invalid symbol: '${t}'`);return new nt(e)}return t}newAuxNTName(){return this.auxNTPrefix+this.auxNTCount++}newAuxNT(t=""){return""==t&&(t=this.newAuxNTName()),this.newNT(t,!0)}ensureAuxNT(...t){let e=this.findAuxNTByRules(...t);if(null==e){e=this.newAuxNT(),e.auxType="anyof";for(const s of t)this.add(e,s)}return e}findAuxNT(t){for(const e of this.symbolSet.entries)if(e.isAuxiliary&&t(e))return e;return null}findAuxNTByRules(...t){return this.findAuxNT(e=>{const s=this.rulesForNT(e);if(s.length!=t.length)return!1;for(let e=0;e<s.length;e++)if(!s[e].rhs.equals(t[e]))return!1;return!0})}print(t=null){const e=(t=t||{}).ruleSep||"->",s=t.includeSemiColon||!1,n=t.lambdaSymbol||"",r=[];return this.forEachRule(null,(t,i)=>{let o=`${t.nt.label} ${e} `;t.rhs.length>0?o+=t.rhs.debugString:o+=n,s&&(o+=" ;"),r.push(o)}),r}get debugValue(){const t=[];return this.forEachRule(null,(e,s)=>{t.push(`${e.nt.label} -> ${e.rhs.debugString}`)}),t}get terminalDerivingSymbols(){const t=new J(this,null);let e=-1,s=!0;for(;0!=e;){e=0;for(const n of this.allRules){s=!0;for(const r of n.rhs.syms)t.has(r)||(r.isTerminal?(t.add(r),e++):s=!1);s&&!t.has(n.nt)&&(t.add(n.nt),e++)}}return t}reachableSymbols(t=null){null==t&&(t=this._AugStartRule?this._AugStartRule.nt:this.startSymbol),a(null!=t,"Start symbol does not exist");const e=new J(this,!1).add(t);let s=[t];for(;s.length>0;){const t=[];for(const n of s)for(const s of this.rulesForNT(n))for(const n of s.rhs.syms)n.isTerminal||e.has(n)||(t.push(n),e.add(n));s=t}return e}get cycles(){return q(this.allNonTerminals,t=>t.label,t=>{const e=[];return this.forEachRule(t,(s,n)=>{s.rhs.syms.forEach((r,i)=>{r.isTerminal||this.nullables.isStrNullable(s.rhs,0,i-1)&&this.nullables.isStrNullable(s.rhs,i+1)&&e.push([r,[t,n]])})}),e})}get leftRecursion(){return q(this.allNonTerminals,t=>t.id,t=>{const e=[];return this.forEachRule(t,(t,s)=>{t.rhs.syms.forEach((t,n)=>{if(!t.isTerminal)return e.push([t,s]),this.nullables.isNullable(t)})}),e})}}var at;!function(t){t[t.WORD_CHAR=0]="WORD_CHAR",t[t.DIGITS=1]="DIGITS",t[t.SPACES=2]="SPACES"}(at||(at={}));const lt="0".charCodeAt(0),ht="9".charCodeAt(0),ut="a".charCodeAt(0),ct="z".charCodeAt(0),dt="A".charCodeAt(0),ft="Z".charCodeAt(0),gt="_".charCodeAt(0);class mt{matches(t,e){const s=this.match(t);return e?!s:s}}const pt=[new class extends mt{match(t){return t==gt||t>=lt&&t<=ht||t>=ut&&t<=ct||t>=dt&&t<=ft}reString(t){return t?"\\W":"\\w"}},new class extends mt{match(t){return t>=lt&&t<=ht}reString(t){return t?"\\D":"\\d"}},new class extends mt{match(t){if(t>=8192&&t<=8202)return!0;for(let e=0;e<14;e++)if(" \f\n\r\t\v  \u2028\u2029   \ufeff".charCodeAt(e)==t)return!0;return!1}reString(t){return t?"\\S":"\\s"}}];var bt,St,yt,Et,wt;!function(t){t[t.gc=0]="gc",t[t.General_Category=0]="General_Category",t[t.sc=1]="sc",t[t.Script=1]="Script",t[t.scx=2]="scx",t[t.Script_Extension=2]="Script_Extension",t[t.Any=3]="Any",t[t.ASCII=4]="ASCII",t[t.AHex=5]="AHex",t[t.ASCII_Hex_Digit=5]="ASCII_Hex_Digit",t[t.Alpha=6]="Alpha",t[t.Alphabetic=6]="Alphabetic",t[t.Bidi_M=7]="Bidi_M",t[t.Bidi_Mirrored=7]="Bidi_Mirrored",t[t.Bidi_C=8]="Bidi_C",t[t.Bidi_Control=8]="Bidi_Control",t[t.CI=9]="CI",t[t.Case_Ignorable=9]="Case_Ignorable",t[t.Cased=10]="Cased",t[t.CWCF=11]="CWCF",t[t.Changes_When_Casefolded=11]="Changes_When_Casefolded",t[t.CWCM=12]="CWCM",t[t.Changes_When_Casemapped=12]="Changes_When_Casemapped",t[t.CWL=13]="CWL",t[t.Changes_When_Lowercased=13]="Changes_When_Lowercased",t[t.CWKCF=14]="CWKCF",t[t.Changes_When_NFKC_Casefolded=14]="Changes_When_NFKC_Casefolded",t[t.CWT=15]="CWT",t[t.Changes_When_Titlecased=15]="Changes_When_Titlecased",t[t.CWU=16]="CWU",t[t.Changes_When_Uppercased=16]="Changes_When_Uppercased",t[t.Dash=17]="Dash",t[t.DI=18]="DI",t[t.Default_Ignorable_Code_Point=18]="Default_Ignorable_Code_Point",t[t.Dep=19]="Dep",t[t.Deprecated=19]="Deprecated",t[t.Dia=20]="Dia",t[t.Diacritic=20]="Diacritic",t[t.Emoji=21]="Emoji",t[t.Emoji_Component=22]="Emoji_Component",t[t.Emoji_Modifier=23]="Emoji_Modifier",t[t.Emoji_Modifier_Base=24]="Emoji_Modifier_Base",t[t.Emoji_Presentation=25]="Emoji_Presentation",t[t.Ext=26]="Ext",t[t.Extender=26]="Extender",t[t.Gr_Base=27]="Gr_Base",t[t.Grapheme_Base=27]="Grapheme_Base",t[t.Gr_Ext=28]="Gr_Ext",t[t.Grapheme_Extend=28]="Grapheme_Extend",t[t.Hex=29]="Hex",t[t.Hex_Digit=29]="Hex_Digit",t[t.IDSB=30]="IDSB",t[t.IDS_Binary_Operator=30]="IDS_Binary_Operator",t[t.IDST=31]="IDST",t[t.IDS_Trinary_Operator=31]="IDS_Trinary_Operator",t[t.IDC=32]="IDC",t[t.ID_Continue=32]="ID_Continue",t[t.IDS=33]="IDS",t[t.ID_Start=33]="ID_Start",t[t.Ideo=34]="Ideo",t[t.Ideographic=34]="Ideographic",t[t.Join_C=35]="Join_C",t[t.Join_Control=35]="Join_Control",t[t.LOE=36]="LOE",t[t.Logical_Order_Exception=36]="Logical_Order_Exception",t[t.Lower=37]="Lower",t[t.Lowercase=37]="Lowercase",t[t.Math=38]="Math",t[t.NChar=39]="NChar",t[t.Noncharacter_Code_Point=39]="Noncharacter_Code_Point",t[t.Pat_Syn=40]="Pat_Syn",t[t.Pattern_Syntax=40]="Pattern_Syntax",t[t.Pat_WS=41]="Pat_WS",t[t.Pattern_White_Space=41]="Pattern_White_Space",t[t.QMark=42]="QMark",t[t.Quotation_Mark=42]="Quotation_Mark",t[t.Radical=43]="Radical",t[t.RI=44]="RI",t[t.Regional_Indicator=44]="Regional_Indicator",t[t.STerm=45]="STerm",t[t.Sentence_Terminal=45]="Sentence_Terminal",t[t.SD=46]="SD",t[t.Soft_Dotted=46]="Soft_Dotted",t[t.Term=47]="Term",t[t.Terminal_Punctuation=47]="Terminal_Punctuation",t[t.UIdeo=48]="UIdeo",t[t.Unified_Ideograph=48]="Unified_Ideograph",t[t.Upper=49]="Upper",t[t.Uppercase=49]="Uppercase",t[t.VS=50]="VS",t[t.Variation_Selector=50]="Variation_Selector",t[t.space=51]="space",t[t.White_Space=51]="White_Space",t[t.XIDC=52]="XIDC",t[t.XID_Continue=52]="XID_Continue",t[t.XIDS=53]="XIDS",t[t.XID_Start=53]="XID_Start"}(bt||(bt={})),function(t){t[t.LC=0]="LC",t[t.Cased_Letter=0]="Cased_Letter",t[t.Pe=1]="Pe",t[t.Close_Punctuation=1]="Close_Punctuation",t[t.Pc=2]="Pc",t[t.Connector_Punctuation=2]="Connector_Punctuation",t[t.Cc=3]="Cc",t[t.cntrl=3]="cntrl",t[t.Control=3]="Control",t[t.Sc=4]="Sc",t[t.Currency_Symbol=4]="Currency_Symbol",t[t.Pd=5]="Pd",t[t.Dash_Punctuation=5]="Dash_Punctuation",t[t.Nd=6]="Nd",t[t.digit=6]="digit",t[t.Decimal_Number=6]="Decimal_Number",t[t.Me=7]="Me",t[t.Enclosing_Mark=7]="Enclosing_Mark",t[t.Pf=8]="Pf",t[t.Final_Punctuation=8]="Final_Punctuation",t[t.Cf=9]="Cf",t[t.Format=9]="Format",t[t.Pi=10]="Pi",t[t.Initial_Punctuation=10]="Initial_Punctuation",t[t.L=11]="L",t[t.Letter=11]="Letter",t[t.Nl=12]="Nl",t[t.Letter_Number=12]="Letter_Number",t[t.Zl=13]="Zl",t[t.Line_Separator=13]="Line_Separator",t[t.Ll=14]="Ll",t[t.Lowercase_Letter=14]="Lowercase_Letter",t[t.M=15]="M",t[t.Combining_Mark=15]="Combining_Mark",t[t.Mark=16]="Mark",t[t.Sm=17]="Sm",t[t.Math_Symbol=17]="Math_Symbol",t[t.Lm=18]="Lm",t[t.Modifier_Letter=18]="Modifier_Letter",t[t.Sk=19]="Sk",t[t.Modifier_Symbol=19]="Modifier_Symbol",t[t.Mn=20]="Mn",t[t.Nonspacing_Mark=20]="Nonspacing_Mark",t[t.N=21]="N",t[t.Number=21]="Number",t[t.Ps=22]="Ps",t[t.Open_Punctuation=22]="Open_Punctuation",t[t.C=23]="C",t[t.Other=23]="Other",t[t.Lo=24]="Lo",t[t.Other_Letter=24]="Other_Letter",t[t.No=25]="No",t[t.Other_Number=25]="Other_Number",t[t.Po=26]="Po",t[t.Other_Punctuation=26]="Other_Punctuation",t[t.So=27]="So",t[t.Other_Symbol=27]="Other_Symbol",t[t.Zp=28]="Zp",t[t.Paragraph_Separator=28]="Paragraph_Separator",t[t.Co=29]="Co",t[t.Private_Use=29]="Private_Use",t[t.P=30]="P",t[t.punct=30]="punct",t[t.Punctuation=30]="Punctuation",t[t.Z=31]="Z",t[t.Separator=31]="Separator",t[t.Zs=32]="Zs",t[t.Space_Separator=32]="Space_Separator",t[t.Mc=33]="Mc",t[t.Spacing_Mark=33]="Spacing_Mark",t[t.Cs=34]="Cs",t[t.Surrogate=34]="Surrogate",t[t.S=35]="S",t[t.Symbol=35]="Symbol",t[t.Lt=36]="Lt",t[t.Titlecase_Letter=36]="Titlecase_Letter",t[t.Cn=37]="Cn",t[t.Unassigned=37]="Unassigned",t[t.Lu=38]="Lu",t[t.Uppercase_Letter=38]="Uppercase_Letter"}(St||(St={})),function(t){t[t.START_OF_INPUT=0]="START_OF_INPUT",t[t.END_OF_INPUT=1]="END_OF_INPUT",t[t.START_OF_WORD=2]="START_OF_WORD",t[t.END_OF_WORD=3]="END_OF_WORD",t[t.UNION=4]="UNION",t[t.CAT=5]="CAT",t[t.VAR=6]="VAR",t[t.BACK_NAMED_REF=7]="BACK_NAMED_REF",t[t.BACK_NUM_REF=8]="BACK_NUM_REF",t[t.QUANT=9]="QUANT",t[t.LOOK_AHEAD=10]="LOOK_AHEAD",t[t.LOOK_BACK=11]="LOOK_BACK",t[t.CHAR=12]="CHAR"}(yt||(yt={}));class Ct{constructor(){this.parent=null,this.reString=null,this.groupIndex=-1,this.groupName=null,this.groupIsSilent=!1,this.ignoreCase=null,this.dotAll=null,this.multiline=null}setOptions(t){return"dotAll"in t&&(this.dotAll=t.dotAll),"ignoreCase"in t&&(this.ignoreCase=t.ignoreCase),"groupIndex"in t&&(this.groupIndex=t.groupIndex),"multiline"in t&&(this.multiline=t.multiline),this}debugValue(){const t={};return this.dotAll&&(t.dotAll=!0),this.ignoreCase&&(t.ignoreCase=!0),this.multiline&&(t.multiline=!0),this.groupIndex>=0&&(t.groupIndex=this.groupIndex),t}get isVariable(){return!1}get toString(){return null==this.reString&&(this.reString=this.evalREString()),this.reString}get modifiers(){let t="";return this.dotAll&&(t+="d"),this.ignoreCase&&(t+="i"),this.multiline&&(t+="m"),this.groupIndex>=0&&(t+="g:"+this.groupIndex),0==t.length?t:"<"+t+">"}}class vt extends Ct{constructor(){super(...arguments),this.tag=yt.START_OF_INPUT}debugValue(){return"^"}reverse(){return this}evalREString(){return"^"}}class xt extends Ct{constructor(){super(...arguments),this.tag=yt.END_OF_INPUT}debugValue(){return"$"}evalREString(){return"$"}reverse(){return this}}class _t extends Ct{constructor(t,e,s=!1){super(),this.expr=t,this.cond=e,this.negate=s}}class At extends _t{constructor(){super(...arguments),this.tag=yt.LOOK_AHEAD}evalREString(){return`${this.expr.toString}(?${this.negate?"!":"="}${this.cond.toString})`}debugValue(){return["LookAhead",{...super.debugValue(),negate:this.negate,expr:this.expr.debugValue(),cond:this.cond.debugValue()}]}reverse(){return new Nt(this.expr.reverse(),this.cond.reverse(),this.negate)}}class Nt extends _t{constructor(){super(...arguments),this.tag=yt.LOOK_BACK}evalREString(){return`(?<${this.negate?"!":"="}${this.cond.toString})${this.expr.toString}`}debugValue(){return["LookBack",{...super.debugValue(),negate:this.negate,expr:this.expr.debugValue(),cond:this.cond.debugValue()}]}reverse(){return new At(this.expr.reverse(),this.cond.reverse(),this.negate)}}class Tt extends Ct{constructor(t,e=1,s=1,n=!0){super(),this.expr=t,this.minCount=e,this.maxCount=s,this.greedy=n,this.tag=yt.QUANT}get isUnlimited(){return this.maxCount<0||this.maxCount==l}get isVariable(){return this.minCount!=this.maxCount||!this.expr.isVariable}reverse(){return new Tt(this.expr.reverse(),this.minCount,this.maxCount,this.greedy)}evalREString(){let t="*";return 1==this.minCount&&this.isUnlimited?t="+":0==this.minCount&&this.isUnlimited?t="*":0==this.minCount&&1==this.maxCount?t="?":1==this.minCount&&1==this.maxCount||(t=this.minCount==this.maxCount?`{${this.minCount}}`:`{${this.minCount},${this.isUnlimited?"":this.maxCount}}`),`${this.expr.toString}${t}`}debugValue(){let t="*";return 1==this.minCount&&this.isUnlimited?t=this.greedy?"+?":"+":0==this.minCount&&this.isUnlimited?t=this.greedy?"*?":"*":0==this.minCount&&1==this.maxCount?t=this.greedy?"??":"?":1==this.minCount&&1==this.maxCount||(t=this.minCount==this.maxCount?`{${this.minCount}}`+(this.greedy?"?":""):`{${this.minCount},${this.maxCount}}`+(this.greedy?"?":"")),[t,super.debugValue(),this.expr.debugValue()]}}class It extends Ct{constructor(...t){super(),this.tag=yt.CAT,this.children=[];for(const e of t)this.add(e)}get isVariable(){for(const t of this.children)if(t.isVariable)return!0;return!1}evalREString(){const t=this.children.map(t=>t.toString).join("");return this.children.length>1?"("+t+")":t}reverse(){const t=this.children.map(t=>t.reverse());return t.reverse(),new It(...t)}add(t){if(t.tag!=yt.CAT||t.groupIndex>=0)this.children.push(t);else for(const e of t.children)this.add(e);return this}debugValue(){return["Cat",{...super.debugValue()},this.children.map(t=>t.debugValue())]}}class Ot extends Ct{constructor(...t){super(),this.tag=yt.UNION,this.options=[];for(const e of t)this.add(e)}get isVariable(){for(const t of this.options)if(t.isVariable)return!0;return!1}evalREString(){const t=this.options.map(t=>t.toString).join("|");return this.options.length>1?"("+t+")":t}reverse(){const t=this.options.map(t=>t.reverse());return new Ot(...t)}add(t){if(t.tag!=yt.UNION||t.groupIndex>=0)this.options.push(t);else for(const e of t.options)this.add(e);return this}debugValue(){return["Union",{...super.debugValue()},this.options.map(t=>t.debugValue())]}}!function(t){t[t.AnyChar=1]="AnyChar",t[t.SingleChar=2]="SingleChar",t[t.CharRange=3]="CharRange",t[t.PropertyEscape=4]="PropertyEscape",t[t.CharClass=5]="CharClass",t[t.Union=6]="Union",t[t.Intersection=7]="Intersection"}(Et||(Et={}));class Rt extends Ct{constructor(t,e=!1){super(),this.op=t,this.neg=e,this.tag=yt.CHAR}match(t){const e=this.matchChar(t);return e&&!this.neg||this.neg&&!e}reverse(){return this}debugValue(){return this.toString+this.modifiers}}class kt extends Rt{constructor(t,e=!1,s=[]){super(t,e),this.op=t,this.neg=e,this.args=s}static Any(t=!1){return new kt(Et.AnyChar,t)}static Class(t,e=!1){return new kt(Et.CharClass,e,[t])}static Single(t,e=!1){return"string"==typeof t&&(t=t.charCodeAt(0)),new kt(Et.SingleChar,e,[t])}static PropertyEscape(t,e,s=!1){return"string"==typeof t&&(t=function(t){if(!((t=t.trim())in bt))throw new SyntaxError("Invalid property name: "+t);return bt[t]}(t)),"string"==typeof e&&(e=function(t){if(!((t=t.trim())in St))throw new SyntaxError("Invalid property value: "+t);return St[t]}(e)),new kt(Et.PropertyEscape,s,[t,e])}matchChar(t){const e=this.args;switch(this.op){case Et.SingleChar:return t==this.args[0];case Et.CharClass:return pt[e[0]].matches(t,!1);case Et.PropertyEscape:throw new Error("Property Escape Matching - TBD");default:throw new Error("Custom Chars - TBD i: "+this.op)}return!1}compareTo(t){if(this.op!=t.op)return this.op-t.op;for(let e=0;e<this.args.length&&e<t.args.length;e++)if(this.args[e]!=t.args[e])return this.args[e]-t.args[e];return this.args.length-t.args.length}evalREString(){return this.op==Et.AnyChar?".":this.op==Et.SingleChar?(t=this.args[0],String.fromCharCode(t).replace("\n","\\n").replace("\0","\\0").replace("\r","\\r").replace("\t","\\t").replace("\f","\\f").replace("\b","\\b")):this.op==Et.CharClass?pt[this.args[0]].reString(this.neg):this.op==Et.PropertyEscape?this.neg?"\\P{":"\\p{}":"Custom "+this.args.join(" ");var t}}class Lt extends Rt{constructor(t,e=!1,s=[]){super(t,e),this.op=t,this.neg=e,this.chars=s}compareTo(t){if(this.op!=t.op)return this.op-t.op;for(let e=0;e<this.chars.length&&e<t.chars.length;e++){const s=this.chars[e].compareTo(t.chars[e]);if(0!=s)return s}return this.chars.length-t.chars.length}matchChar(t){const e=this.chars;switch(this.op){case Et.CharRange:return t>=e[0].args[0]&&t<=e[1].args[0];case Et.Union:for(let s=0;s<e.length;s++)if(e[s].match(t))return!0;return!1;case Et.Intersection:for(let s=0;s<e.length;s++)if(!e[s].match(t))return!1;return!0;default:throw new Error("Custom CharGroup - TBD i: "+this.op)}return!1}evalREString(){const t=this.chars.map(t=>t.debugValue()).join("");return this.op==Et.CharRange?`${this.chars[0].toString}-${this.chars[1].toString}`:this.op==Et.Union||this.op==Et.Intersection?t.length>1?(this.neg?"[^":"[")+t+"]":t:"Custom "+this.chars.join(" ")}static Range(t,e,s=!1){return new Lt(Et.CharRange,s,[t,e])}static Union(t=!1,e){return new Lt(Et.Union,t,e)}static Intersection(t=!1,e){return new Lt(Et.Intersection,t,e)}}class Mt extends Ct{constructor(t,e=!1){super(),this.name=t,this.reversed=e,this.tag=yt.VAR}reverse(){return new Mt(this.name,!this.reversed)}evalREString(){return"<"+this.name+">"}debugValue(){return["V:"+this.name,{...super.debugValue()}]}}class Pt extends Ct{constructor(t,e=!1){super(),this.name=t,this.reversed=e,this.tag=yt.BACK_NAMED_REF}reverse(){return new Pt(this.name,!this.reversed)}evalREString(){return"\\k<"+this.name+">"}debugValue(){return{...super.debugValue,BackRef:this.name}}}class Bt extends Ct{constructor(t,e=!1){super(),this.num=t,this.reversed=e,this.tag=yt.BACK_NUM_REF}reverse(){return new Bt(this.num,!this.reversed)}evalREString(){return"\\"+this.num}debugValue(){return"\\"+this.num}}class $t{constructor(t,e){this.expr=t,this.skip=!1,e=e||{},this.tag=e.tag||null,0==e.priority?this.priority=0:this.priority=e.priority||10,0==e.matchIndex?this.matchIndex=0:this.matchIndex=e.matchIndex||-1,this.skip=e.skip||!1,this.activeStates=e.activeStates||null}stateCanActivate(t){return null==this.activeStates||0==this.activeStates.size||this.activeStates.has("*")||this.activeStates.has(t)}get needsSpecificStates(){return null!=this.activeStates&&this.activeStates.size>0&&!this.activeStates.has("*")}}function Dt(t){return"\r"==t||"\n"==t||"\u2028"==t||"\u2029"==t}class Vt{constructor(t=10,e=-1,s=-1,n=-1){this.priority=t,this.matchIndex=e,this.start=s,this.end=n,this.groups=[],this.positions=[]}}!function(t){t[t.Any=0]="Any",t[t.AnyNonNL=1]="AnyNonNL",t[t.Char=2]="Char",t[t.CIChar=3]="CIChar",t[t.Match=4]="Match",t[t.Noop=5]="Noop",t[t.Save=6]="Save",t[t.Split=7]="Split",t[t.Jump=8]="Jump",t[t.Begin=9]="Begin",t[t.RBegin=10]="RBegin",t[t.End=11]="End",t[t.StartingChar=12]="StartingChar",t[t.EndingChar=13]="EndingChar",t[t.MLStartingChar=14]="MLStartingChar",t[t.MLEndingChar=15]="MLEndingChar",t[t.StartOfWord=16]="StartOfWord",t[t.EndOfWord=17]="EndOfWord",t[t.GroupStart=18]="GroupStart",t[t.GroupEnd=19]="GroupEnd",t[t.EnsureState=20]="EnsureState"}(wt||(wt={}));class Ut{constructor(t="INITIAL",e=!0){this.startCondition=t,this.scIsInclusive=e,this.instrs=[],this.stateMapping=new Map,this.registerState("INITIAL"),this.registerState(t)}get length(){return this.instrs.length}registerState(t){return this.stateMapping.has(t)||this.stateMapping.set(t,this.stateMapping.size),this.stateMapping.get(t)||-1}add(t,e=null,...s){const n=new Ft(t,e).add(...s);return n.offset=this.instrs.length,this.instrs.push(n),n}static with(t){const e=new Ut;return t(e),e}debugValue(t=zt){return t?this.instrs.map((e,s)=>e.comment.trim().length>0?`L${s}: ${t(e)} # ${e.comment}`:`L${s}: ${t(e)}`):this.instrs.map((t,e)=>`L${e}: ${t.debugValue}`)}}class Ft{constructor(t,e=null){this.opcode=t,this.char=e,this.offset=0,this.comment="",this.args=[],this.char=e}add(...t){return this.args.push(...t),this}get debugValue(){let t=this.comment.trim();return t.length>0&&(t=" # "+t),`${this.opcode} ${this.args.join(" ")} ${this.char||""} ${t}`}}class jt{constructor(t=0,e=0){this.offset=t,this.gen=e,this.parentId=-1,this.id=0,this.priority=0,this.groups=[],this.positions=[],this.registers={}}regIncr(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);this.registers[t]++}regAcquire(t){if(t in this.registers)throw new Error(`Register at offset ${t} already acquired. Release it first`);this.registers[t]=0}regRelease(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);delete this.registers[t]}regValue(t){if(!(t in this.registers))throw new Error(`Register at offset ${t} is invalid`);return this.registers[t]}}class Gt{getState(){return this.currState}setState(t){this.currState=t}constructor(t,e=0,s=-1,n=!0,r={}){this.prog=t,this.start=e,this.end=s,this.forward=n,this.threadCounter=0,this.currThreads=[],this.nextThreads=[],this.startPos=0,this.currState=0,this.gen=0,this.genForOffset={},s<0&&(s=t.length-1),this.end=s}savePosition(t,e,s){for(;t.positions.length<=e;)t.positions.push(-1);t.positions[e]=s}jumpBy(t,e=1){return this.jumpTo(t,t.offset+e)}jumpTo(t,e){const s=new jt(e,this.gen);return s.id=t.id,s.parentId=t.parentId,s.priority=t.priority,s.positions=t.positions,s.groups=t.groups,s.registers=t.registers,s}forkTo(t,e){const s=new jt(e,this.gen);return s.id=++this.threadCounter,s.parentId=t.id,s.priority=t.priority,s.positions=[...t.positions],s.groups=[...t.groups],s.registers={...t.registers},s}startGroup(t,e,s){const n=this.forkTo(t,t.offset+1);return n.groups.push([e,s]),n}endGroup(t,e,s){const n=this.forkTo(t,t.offset+1);return n.groups.push([-e,s]),n}addThread(t,e,s,n=0){if(t.offset<this.start||t.offset>this.end||this.genForOffset[t.offset-this.start]==this.gen)return;this.genForOffset[t.offset-this.start]=this.gen;const r=this.prog.instrs[t.offset];let i,o,a;const l=r.opcode;switch(l){case wt.Jump:a=this.jumpTo(t,r.args[0]),this.addThread(a,e,s,n);break;case wt.Split:for(let i=0;i<r.args.length;i++){const o=r.args[i],a=0==i?this.jumpTo(t,o):this.forkTo(t,o);this.addThread(a,e,s,n)}break;case wt.Save:a=this.jumpTo(t,t.offset+1),this.savePosition(a,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case wt.GroupStart:a=this.startGroup(t,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case wt.GroupEnd:a=this.endGroup(t,r.args[0],s.index+n),this.tracer&&this.tracer.threadQueued(t,s.index+n),this.addThread(a,e,s,n);break;case wt.StartingChar:case wt.MLStartingChar:o=this.prevCh(s),(0==s.index||l==wt.MLStartingChar&&Dt(o))&&this.addThread(this.jumpBy(t,1),e,s,n);break;case wt.EndingChar:case wt.MLEndingChar:i=this.nextCh(s),(""==i||l==wt.MLEndingChar&&Dt(i))&&this.addThread(this.jumpBy(t,1),e,s,n);break;case wt.StartOfWord:case wt.EndOfWord:break;case wt.RBegin:{const[i,o,a]=r.args,l=2*(1+i),h=t.positions[l],[u,c]=this.recurseMatch(s,h-1,r.offset+1,a,!1,1==o);u&&this.addThread(this.jumpTo(t,a+1),e,s,n)}break;case wt.Begin:const[h,u,c]=r.args;if(1==h)this.tracer&&this.tracer.threadQueued(t,s.index),e.push(t);else{const[i,o]=this.recurseMatch(s,s.index+1,r.offset+1,c,!0,1==u);i&&this.addThread(this.jumpTo(t,c+1),e,s,n)}break;case wt.EnsureState:const d=r.args;for(const r of d)if(this.currState==r){this.addThread(this.jumpBy(t,1),e,s,n);break}break;default:this.tracer&&this.tracer.threadQueued(t,s.index),e.push(t)}}matchCurrPos(t,e,s=!1){return s?e.match(t.currChCodeLower)||e.match(t.currChCodeUpper):e.match(t.currChCode)}hasMore(t){return this.forward?t.hasMore:t.index>=0}nextCh(t){const e=t.index+(this.forward?1:-1);return t.charAt(e)}prevCh(t){return t.charAt(t.index-(this.forward?1:-1))}match(t){if(this.end<this.start)return null;this.startMatching(t);let e=null;for(;this.currThreads.length>0;)e=this.stepChar(t,e);return null!=e&&(t.index=e.end),e}recurseMatch(t,e,s,n,r=!0,i=!1){const o=t.index;if(!t.canAdvance(r?1:-1))return[i,-1];t.index=e;const a=new Gt(this.prog,s,n,r).match(t),l=t.index;return t.index=o,[null!=a&&!i||null==a&&i,l]}startMatching(t){this.currThreads=[],this.nextThreads=[],this.gen++,this.addThread(new jt(this.start,this.gen),this.currThreads,t),this.startPos=t.index}stepChar(t,e=null){this.gen++;for(let s=0;s<this.currThreads.length;s++){const n=this.currThreads[s],r=this.stepThread(t,n);if(null!=r&&(null==e||r.priority>e.priority||r.priority==e.priority&&r.end>e.end)){e=r;break}}return this.hasMore(t)&&t.advance(this.forward?1:-1),this.currThreads=this.nextThreads,this.nextThreads=[],e}stepThread(t,e){this.tracer&&this.tracer.threadStepped(e,t.index,this.gen);let s=null;const n=this.prog.instrs[e.offset],r=n.opcode,i=(n.args,this.forward?1:-1);let o=!1;switch(r){case wt.RBegin:throw new Error("Invalid state. Reverse matches must be handled in addThread");case wt.Begin:const[i,l,h]=n.args;a(1==i,"Plain lookahead cannot be here");const[u,c]=this.recurseMatch(t,t.index,n.offset+1,h,!0,1==l);u&&this.addThread(this.jumpTo(e,h+1),this.nextThreads,t);break;case wt.End:const d=new Vt(-1,-1,this.startPos,t.index);return d.groups=e.groups,d.positions=e.positions,d;case wt.Match:if(t.index>this.startPos){const r=n.args[0],i=n.args[1];s=new Vt,s.start=this.startPos,s.end=t.index,s.priority=r,s.matchIndex=i,s.groups=e.groups,s.positions=e.positions}break;case wt.Char:case wt.CIChar:this.hasMore(t)&&(o=this.matchCurrPos(t,n.char,r==wt.CIChar));break;case wt.AnyNonNL:case wt.Any:this.hasMore(t)&&(o=r==wt.Any||!Dt(t.currCh))}return o&&this.addThread(this.jumpBy(e,1),this.nextThreads,t,i),s}}function zt(t){switch(t.opcode){case wt.Match:return`Match ${t.args[0]} ${t.args[1]}`;case wt.Char:case wt.CIChar:{let e=`${wt[t.opcode].toString()} `;return e+=`${t.char.debugValue()}`,e}case wt.Any:return".";case wt.AnyNonNL:return"NL.";case wt.StartingChar:return"^";case wt.MLStartingChar:return"NL^";case wt.EndingChar:return"$NL";case wt.MLEndingChar:return"$NL_MultiLine";case wt.Save:return`Save ${t.args[0]}`;case wt.GroupStart:return`GroupStart ${t.args[0]}`;case wt.GroupEnd:return`GroupEnd ${t.args[0]}`;case wt.Split:return`Split ${t.args.join(", ")}`;case wt.Jump:return`Jump ${t.args[0]}`;case wt.Begin:return`Begin ${t.args.join(" ")}`;case wt.RBegin:return`RBegin ${t.args.join(" ")}`;case wt.End:return`End ${t.args.join(" ")}`;case wt.EnsureState:return`EnsureState ${t.args.join(" ")}`;default:throw new Error("Invalid Opcode: "+t.opcode)}}class Wt{constructor(t,e=null){this.regexResolver=t,this.listener=e,this.emitGroups=!1,this.emitPosition=!0}compile(t){const e=new Ut,s=t.length<=1?new Ft(wt.Split):e.add(wt.Split,null);return t.forEach((t,n)=>{s.add(e.instrs.length);const r=null!=t.expr.ignoreCase&&t.expr.ignoreCase,i=null==t.expr.dotAll||t.expr.dotAll,o=null==t.expr.multiline||t.expr.multiline;if(t.needsSpecificStates&&null!=t.activeStates){const s=e.add(wt.EnsureState,null);t.activeStates.forEach(t=>{const n=e.registerState(t);s.add(n)})}this.compileExpr(t.expr,e,r,i,o),e.add(wt.Match,null).add(t.priority,t.matchIndex>=0?t.matchIndex:n)}),e}compileExpr(t,e,s,n,r){const i=e.length,o=e.length;if(t.groupIndex>=0&&(this.emitPosition&&e.add(wt.Save).add(2*(1+t.groupIndex)),this.emitGroups&&e.add(wt.GroupStart).add(1+t.groupIndex)),t.tag==yt.CHAR)this.compileChar(t,e,s,n,r);else if(t.tag==yt.START_OF_INPUT){const s=null==t.multiline?r:t.multiline;e.add(s?wt.MLStartingChar:wt.StartingChar)}else if(t.tag==yt.END_OF_INPUT){const s=null==t.multiline?r:t.multiline;e.add(s?wt.MLEndingChar:wt.EndingChar)}else if(t.tag==yt.START_OF_WORD)e.add(wt.StartOfWord);else if(t.tag==yt.END_OF_WORD)e.add(wt.EndOfWord);else if(t.tag==yt.CAT)this.compileCat(t,e,s,n,r);else if(t.tag==yt.UNION)this.compileUnion(t,e,s,n,r);else if(t.tag==yt.QUANT)this.compileQuant(t,e,s,n,r);else if(t.tag==yt.VAR)this.compileVar(t,e,s,n,r);else if(t.tag==yt.BACK_NAMED_REF)this.compileBackNamedRef(t,e,s,n,r);else if(t.tag==yt.BACK_NUM_REF)this.compileBackNumRef(t,e,s,n,r);else if(t.tag==yt.LOOK_AHEAD)this.compileLookAhead(t,e,s,n,r);else{if(t.tag!=yt.LOOK_BACK)throw new Error("Regex Type not yet supported: "+t.tag);this.compileLookBack(t,e,s,n,r)}return t.groupIndex>=0&&(this.emitGroups&&e.add(wt.GroupEnd).add(1+t.groupIndex),this.emitPosition&&e.add(wt.Save).add(2*(1+t.groupIndex)+1)),this.listener&&e.length>o&&this.listener(t,e,o,e.length-o),e.length-i}compileChar(t,e,s,n,r){t.op==Et.AnyChar?e.add(n?wt.Any:wt.AnyNonNL):e.add(s?wt.CIChar:wt.Char).char=t}compileCat(t,e,s,n,r){for(const i of t.children)this.compileExpr(i,e,s,n,r)}compileBackNumRef(t,e,s,n,r){throw new Error("BackNumRef Not Implemented")}compileBackNamedRef(t,e,s,n,r){throw new Error("BackNameRef Not Implemented")}compileVar(t,e,s,n,r){const i=t.name.trim(),o=this.regexResolver?this.regexResolver(i):null;if(null==o)throw new Error(`Cannot find expression: ${i}`);this.compileExpr(o,e,s,n,r)}compileUnion(t,e,s,n,r){const i=e.add(wt.Split),o=[];for(let a=0;a<t.options.length;a++)i.add(e.length),this.compileExpr(t.options[a],e,s,n,r),a<t.options.length-1&&o.push(e.add(wt.Jump));for(const t of o)t.add(e.length)}compileQuant(t,e,s,n,r){if(0==t.minCount&&t.maxCount==l)this.compileAtleast0(t.expr,e,t.greedy,s,n,r);else if(1==t.minCount&&t.maxCount==l)this.compileAtleast1(t.expr,e,t.greedy,s,n,r);else if(0==t.minCount&&1==t.maxCount)this.compileOptional(t.expr,e,t.greedy,s,n,r);else{for(let i=0;i<t.minCount;i++)this.compileExpr(t.expr,e,s,n,r);if(t.isUnlimited)this.compileAtleast0(t.expr,e,t.greedy,s,n,r);else for(let i=t.minCount;i<t.maxCount;i++)this.compileOptional(t.expr,e,t.greedy,s,n,r)}}compileAtleast1(t,e,s=!0,n,r,i){const o=e.length;this.compileExpr(t,e,n,r,i);const a=e.add(wt.Split),l=e.length;s?a.add(o,l):a.add(l,o)}compileAtleast0(t,e,s,n,r,i){const o=e.add(wt.Split),a=o.offset,l=e.length;this.compileExpr(t,e,n,r,i),e.add(wt.Jump).add(a);const h=e.length;s?o.add(l,h):o.add(h,l)}compileOptional(t,e,s,n,r,i){const o=e.add(wt.Split),a=e.length;this.compileExpr(t,e,n,r,i);const l=e.length;s?o.add(a,l):o.add(l,a)}compileLookAhead(t,e,s,n,r){this.compileExpr(t.expr,e,s,n,r);const i=e.add(wt.Begin).add(0,t.negate?1:0);this.compileExpr(t.cond,e,s,n,r);const o=e.add(wt.End).add(i.offset);i.add(o.offset)}compileLookBack(t,e,s,n,r){this.compileExpr(t.expr,e,s,n,r),a(t.expr.groupIndex>=0,"LookBack Assertion requires expression to have a group Index");const i=e.add(wt.RBegin).add(t.expr.groupIndex,t.negate?1:0);this.compileExpr(t.cond.reverse(),e,s,n,r);const o=e.add(wt.End).add(i.offset);i.add(o.offset)}}class Kt extends Error{constructor(t,e,s,n,r=null){super(t),this.offset=e,this.length=s,this.type=n,this.value=r,this.name="TokenizerError",Object.setPrototypeOf(this,new.target.prototype)}}class Ht extends Error{constructor(t,...e){super(`Found Token: ${t?.tag||"EOF"} (${t?.value||""}), Expected: ${e.join(", ")}`),this.foundToken=t,this.name="UnexpectedTokenError",this.expectedTokens=e}}class qt{constructor(t=!0){this.forward=t,this.index=0}advance(t=1){const e=this.forward?this.index+t:this.index-t;return this.index=e,!0}canAdvance(t=1){const e=this.forward?this.index+t:this.index-t;return this.hasIndex(e)}get hasMore(){const t=this.forward?this.index:this.index-1;return this.hasIndex(t)}get currCh(){return this.charAt(this.index)}get prevCh(){return this.charAt(this.index-(this.forward?1:-1))}get nextCh(){const t=this.index+(this.forward?1:-1);return this.charAt(t)}get currChCode(){return this.hasMore?this.currCh.charCodeAt(0):-1}get currChCodeLower(){return this.hasMore?this.currCh.toLowerCase().charCodeAt(0):-1}get currChCodeUpper(){return this.hasMore?this.currCh.toUpperCase().charCodeAt(0):-1}charCodeAt(t){return this.hasIndex(t)?this.charAt(t).charCodeAt(0):-1}charCodeAtLower(t){return this.hasIndex(t)?this.charAt(t).toLowerCase().charCodeAt(0):-1}charCodeAtUpper(t){return this.hasIndex(t)?this.charAt(t).toUpperCase().charCodeAt(0):-1}}class Qt extends qt{constructor(t,e=!0){super(e),this.forward=e,this._rawInput=t,this.input=[...t]}push(t){this._rawInput+=t,this.input.push(...t)}substring(t,e){return this._rawInput.substring(t,e)}hasIndex(t){return t>=0&&t<this.input.length}charAt(t){return t<0||t>=this.input.length?"":this.input[t]}}class Yt{static advanceAfter(t,e,s=!0){let n=Yt.advanceTo(t,e,s);return n>=0&&(n+=e.length,t.index=n),n}static advanceTo(t,e,s=!0){const n=t.index;for(;t.hasMore;){const n=t.index;if(Yt.matches(t,e)){const e=t.index;t.index=n;let r=0;if(s)for(let s=e-1;s>=0&&"\\"==t.charAt(s);s--)r++;if(r%2==0)return t.index}t.advance(1)}throw t.index=n,new Error(`Unexpected end of input before (${e})`)}static matches(t,e,s=!0){const n=t.index;let r=0,i=!0;for(;r<e.length;r++){if(e[r]!=t.currCh){i=!1;break}t.advance(1)}return s&&i||(t.index=n),i}}class Jt{constructor(t,e,s,n){this.tag=t,this.matchIndex=e,this.start=s,this.end=n,this.id=Jt.idCounter++,this.value=null,this.groups={},this.positions={},this.state=0,this.lookahead=1,this.lookback=1}isOneOf(...t){for(const e of t)if(this.tag==e)return!0;return!1}}Jt.idCounter=0;class Zt{constructor(t,e){this.nextToken=t,this.tokenizerContext=e,this.buffer=[]}next(t){const e=this.peek(t);return null!=e&&this.consume(),e}peek(t,e=0){for(;this.buffer.length<=e;){const e=this.nextToken(t,this.tokenizerContext);if(null==e)return null;this.buffer.push(e)}return this.buffer[e]}match(t,e,s=!1,n=!0,r){const i=this.peek(t);if(null!=i){if(!e(i)){if(s)throw new Ht(i);return null}r&&null!=r&&r(i),n&&this.consume()}else if(s)throw new Kt("Unexpected end of input",-1,0,"UnexpectedEndOfInput");return i}consume(){this.buffer.splice(0,1)}consumeIf(t,...e){return this.match(t,t=>t.isOneOf(...e))}expectToken(t,...e){return this.match(t,t=>t.isOneOf(...e),!0,!0)}ensureToken(t,...e){return this.match(t,t=>t.isOneOf(...e),!0,!1)}nextMatches(t,...e){const s=this.peek(t);if(null==s)return null;for(const t of e)if(s.tag==t)return s;return null}}class Xt{constructor(){this.value=-1}next(){return++this.value}get current(){return this.value}}function te(t){return" "==t||"\t"==t||"\n"==t||"\r"==t}class ee{constructor(t,e){this.pattern=t,this.counter=new Xt,this.unicode=e?.unicode||!1}reduceLeft(t){const e=1==t.length?t[0]:new It(...t);return t.splice(0),e}throwError(t){throw new SyntaxError(`Error in JS RE '${this.pattern}': ${t}`)}parse(t=0,e=-1){const s=this.pattern,n=[];for(e<0&&(e=s.length-1);t<=e;){const r=s[t];if("."==r)n.push(kt.Any()),t++;else if("\\"==r&&s[t+1]>="1"&&s[t+1]<="9"){t++;let r="";for(;t<=e&&s[t]>="0"&&s[t]<="9";)r+=s[t++];const i=parseInt(r);i>this.counter.current+1&&this.throwError("Invalid reference: "+i),n.push(new Bt(i))}else if("\\"==r&&"k"==s[t+1]&&"<"==s[t+2]){let r=t+=3;for(;r<=e&&">"!=s[r];)r++;r>e&&this.throwError("Expected '>' found EOI");const i=s.substring(t,r);""==i.trim()&&this.throwError("Expected name"),n.push(new Pt(i)),t=r+1}else if("["==r){let r=t+1;for(;r<=e&&"]"!=s[r];)"\\"==s[r]&&r++,r++;r>e&&this.throwError("Expected ']' found EOI"),n.push(this.parseCharGroup(t+1,r-1)),t=r+1}else if("^"==r)n.push(new vt),t++;else if("$"==r)n.push(new xt),t++;else if("|"==r){if(t+1<=e){const s=this.reduceLeft(n),r=this.parse(t+1,e);return new Ot(s,r)}t=e+1}else if("("==r)t=this.parseGroup(n,t,e);else if(")"==r||"]"==r||"}"==r)this.throwError(`Unmatched ${r}. Try using \\${r}`);else if("*"==s[t]||"?"==s[t]||"+"==s[t]||"{"==s[t])t=this.parseQuant(n,t,e);else{const[s,r]=this.parseChar(t,e);n.push(s),t+=r}}return n.length,1==n.length?n[0]:new It(...n)}parseGroup(t,e,s){let n=e+1,r=0;const i=this.pattern;for(;n<=s&&(")"!=i[n]||r>0);)"("==i[n]?r++:")"==i[n]&&r--,"\\"==i[n]&&n++,n++;if(n>s&&this.throwError("Expected ')' found EOI"),"?"==i[++e])if(":"==i[++e])t.push(this.parse(e+1,n-1));else if("<"==i[e]&&"!"!=i[e+1]&&"="!=i[e+1]){const t=this.counter.next();let r="",o=e+1;for(;o<=s&&">"!=i[o];)r+=i[o],o++;const a=this.parse(o+1,n-1);a.groupIndex=t,r.length>0&&(a.groupName=r)}else{let r=!0;"<"==i[e]&&(e++,r=!1);const o="!"==i[e++],a=this.parse(e,n-1);if(!r){const e=this.parse(n+1,s);return e.groupIndex<0&&(e.groupIndex=this.counter.next(),e.groupIsSilent=!0),t.push(new Nt(e,a,o)),s+1}{t.length;const e=new At(this.reduceLeft(t),a,o);t.push(e)}}else{const s=this.counter.next();let r=!1;"^"==i[e]&&(r=!0,e++);let o=this.parse(e,n-1);o.groupIndex>=0&&(o=new It(o)),o.groupIndex=s,t.push(o)}return n+1}parseCharGroup(t,e){const s=[];let n=t,r=!1;const i=this.pattern;for("^"==i[n]&&(r=!0,n++);n<=e;){const[t,r]=this.parseChar(n,e);if(n+=r,n<i.length&&"-"==i[n])if(n++,"]"==i[n]||"["==i[n])s.push(t),s.push(kt.Single("-"));else if(n<=e){const[r,i]=this.parseChar(n,e);t.op==Et.SingleChar&&r.op==Et.SingleChar||this.throwError("Char range cannot start or end in a char class"),r.args[0]<t.args[0]&&this.throwError("End cannot be less than start"),s.push(Lt.Range(t,r)),n+=i}else this.throwError("Unterminated char class");else s.push(t)}return Lt.Union(r,s)}parseChar(t=0,e=0){return"\\"==this.pattern[t]?this.parseEscapeChar(t,e):this.parseSingleChar(t,e)}parseSingleChar(t=0,e=0){const s=this.pattern.charCodeAt(t);return[kt.Single(s),1]}parsePropertyEscape(t=0,e=0){const s=this.pattern;s[t]+1!="{"&&this.throwError("Invalid property escape");let n=t+=2,r=-1;for(;n<=e&&"}"!=s[n];)"="==s[n]&&(r=n),n++;n>e&&this.throwError("Invalid property escape");const i=s.substring(t,n);let o="General_Category",a=i;if(r>=0){const t=i.split("=");2!=t.length&&this.throwError("Invalid property escape"),o=t[0].trim(),a=t[1].trim()}return[kt.PropertyEscape(o,a),2+n+1-t]}parseEscapeChar(t=0,e=0){const s=this.pattern;a("\\"==s[t],"Expected '\\'"),++t>e&&this.throwError("Encounted unexpected end of input after \\");const n=s[t];if(this.unicode&&"p"==n||"P"==n)return this.parsePropertyEscape(t,e);switch(n){case"w":return[kt.Class(at.WORD_CHAR),2];case"W":return[kt.Class(at.WORD_CHAR,!0),2];case"d":return[kt.Class(at.DIGITS),2];case"D":return[kt.Class(at.DIGITS,!0),2];case"s":return[kt.Class(at.SPACES),2];case"S":return[kt.Class(at.SPACES,!0),2];case"0":return s[t+1]>="0"&&s[t+1]<="9"&&this.unicode&&this.throwError("Invalid decimal escape"),[kt.Single("\0"),2];case"r":return[kt.Single("\r"),2];case"n":return[kt.Single("\n"),2];case"f":return[kt.Single("\f"),2];case"b":return[kt.Single("\b"),2];case"v":return[kt.Single("\v"),2];case"t":return[kt.Single("\t"),2];case"c":(this.unicode||t>=e)&&this.throwError(`Invalid char sequence at ${t}, ${e}`);const r=s.charCodeAt(t+1)%32;return[kt.Single(r),3];case"x":++t>=e&&this.throwError(`Invalid hex sequence at ${t}, ${e}`);const i=s.substring(t,t+2),o=parseInt(i,16);return a(!isNaN(o),`Invalid hex sequence: '${i}'`),[kt.Single(o),4];case"u":++t>e-3&&this.throwError(`Invalid unicode sequence at ${t}`);const l=s.substring(t,t+4),h=parseInt(l,16);return isNaN(h)&&this.throwError(`Invalid unicode sequence: '${l}'`),[kt.Single(h),6];case"^":case"$":case".":case"*":case"+":case"?":case"\\":case"'":case'"':case"(":case")":case"[":case"]":case"{":case"}":case"|":case"/":return[kt.Single(n),2];default:return this.unicode&&this.throwError("Invalid escape character: "+n),[kt.Single(n),2]}}parseQuant(t,e,s){const n=this.pattern,r=n[e-1];let i=1,o=1;if("*"==n[e])i=0,o=l;else if("+"==n[e])i=Math.min(i,1),o=l;else if("?"==n[e])i=0,o=Math.max(o,1);else{if("{"!=n[e])throw new Error("Here?");{const r=n.indexOf("}",e+1);(r<=e||r>s)&&this.throwError("Unexpected end of input while looking for '}'");const a=n.substring(e+1,r).trim(),h=a.split(",").map(t=>parseInt(t.trim()));if(e=r,1==h.length){if(isNaN(h[0])){if(a.trim().length>0)return t.push(new Mt(a.trim())),e+1;this.throwError(`Invalid quantifier: /${a}/`)}i=o=h[0]}else 2==h.length?(i=isNaN(h[0])?0:h[0],o=isNaN(h[1])?l:h[1],i>o&&this.throwError(`Invalid Quant /${a}/: Min must be <= Max`)):h.length>2&&this.throwError(`Invalid quantifier spec: "{${a}}"`)}}t.length<=0&&this.throwError("Quantifier cannot appear before an expression");const a=t[t.length-1];a.tag!=yt.QUANT||"*"!=r&&"?"!=r&&"+"!=r&&"}"!=r||this.throwError("Nothing to repeat"),!this.unicode||a.tag!=yt.LOOK_AHEAD&&a.tag!=yt.LOOK_BACK||this.throwError("Cannot have quantifier on assertion in unicode mode");const h=t[t.length-1]=new Tt(a);return h.minCount=i,h.maxCount=o,++e<=s&&"?"==n[e]&&h.greedy&&(e++,h.greedy=!1),e}}function se(t,e){const s=t.index;for(let n=0;n<e.length;n++){if(t.currCh!=e.charAt(n))return t.index=s,!1;t.advance(1)}return!0}class ne{constructor(){this.counter=new Xt}parse(t,e=!1,s=0){const n=[];for(;t.hasMore;){const r=t.currCh;if(se(t,"."))n.push(kt.Any());else if(se(t,"^")){const t=new vt;t.multiline=!0,n.push(t)}else if(se(t,"$")){const t=new xt;t.multiline=!0,n.push(t)}else{if(se(t,"|")){const r=this.reduceLeft(n),i=this.parse(t,e,s);return new Ot(r,i)}if("["==r)n.push(this.parseCharGroup(t));else if("*"==r||"?"==r||"+"==r||"{"==r)this.parseQuant(t,n);else if(e&&te(r))t.advance(1);else if(e&&se(t,"/*")){for(;"*"!=t.currCh||"/"!=t.nextCh;)t.hasMore||this.throwError(t,"Unterminated comment"),t.advance(1);t.advance(2)}else{if(se(t,"{-}"))throw new Error("Intersection Not yet supported");if(se(t,"{+}"))throw new Error("Union Not yet supported");if(se(t,"("))if(se(t,"?"))if(se(t,"#")){for(;t.hasMore&&")"!=t.currCh;)t.advance(1);a(se(t,")"),"Expected ')'")}else{let r=!1,i=!1,o=e,l=!1;for(;t.hasMore&&":"!=t.currCh;)"i"==t.currCh?r=!l:"s"==t.currCh?i=!l:"x"==t.currCh?o=!l:"-"==t.currCh&&(l=!0),t.advance(1);a(se(t,":"),"Expected ':'");const h=this.counter.next();let u=this.parse(t,o,s+1);u.groupIndex>=0&&(u=new It(u)),u.dotAll=i,u.ignoreCase=r,u.groupIndex=h,n.push(u),a(se(t,")"),"Expected ')'")}else{const r=this.counter.next();let i=this.parse(t,e,s+1);i.groupIndex>=0&&(i=new It(i)),i.groupIndex=r,n.push(i),a(se(t,")"),"Expected ')'")}else{if(")"==r){0==s&&this.throwError(t,`Unmatched ${r}. Try using \\${r}`);break}if("]"==r||"}"==r)this.throwError(t,`Unmatched ${r}. Try using \\${r}`);else{if(se(t,"/")){const r=this.reduceLeft(n),i=this.parse(t,e,s);return new At(r,i,!1)}if(se(t,'"')){for(;'"'!=t.currCh;)t.hasMore||this.throwError(t,"Unterminated string"),n.push(this.parseChar(t));t.advance(1)}else n.push(this.parseChar(t))}}}}}return 1==n.length?n[0]:new It(...n)}parseQuant(t,e){let s=1,n=1;if(se(t,"*"))s=0,n=l;else if(se(t,"+"))s=Math.min(s,1),n=l;else if(se(t,"?"))s=0,n=Math.max(n,1);else if(se(t,"{")){let r=!1,i="",o="";for(;t.hasMore&&"}"!=t.currCh;)","==t.currCh?r=!0:r?o+=t.currCh:i+=t.currCh,t.advance(1);t.hasMore||this.throwError(t,"Invalid property escape"),i=i.trim(),o=o.trim(),t.advance(1);const a=parseInt(i),h=parseInt(o);if(r)s=isNaN(a)?0:a,n=isNaN(h)?l:h,s>n&&this.throwError(t,`Invalid Quant /${i},${o}/: Min must be <= Max`);else if(isNaN(a)){if(i.length>0)return void e.push(new Mt(i));this.throwError(t,`Invalid quantifier: /${i}/`),s=n=1}else s=n=a}else this.throwError(t,"Expected '{', '*', '?' or '+', Found: "+t.currCh);e.length<=0&&this.throwError(t,"Quantifier cannot appear before an expression");const r=e[e.length-1];let i;r.tag==yt.QUANT&&r.groupIndex<0?(i=r,i.minCount=Math.min(s,i.minCount),i.maxCount=Math.max(n,i.maxCount)):(i=e[e.length-1]=new Tt(r),i.minCount=s,i.maxCount=n),i.greedy&&se(t,"?")&&(i.greedy=!1)}parseCharGroup(t){const e=[];a(se(t,"["),"Expected '['");const s=se(t,"^");for(;"]"!=t.currCh;){const s=this.parseChar(t);if(se(t,"-"))if(t.hasMore)if("]"==t.currCh||"["==t.currCh)e.push(s),e.push(kt.Single("-"));else{const n=this.parseChar(t);s.op==Et.SingleChar&&n.op==Et.SingleChar||this.throwError(t,"Char range cannot start or end in a char class"),n.args[0]<s.args[0]&&this.throwError(t,"End cannot be less than start"),e.push(Lt.Range(s,n))}else this.throwError(t,"Unterminated char class");else e.push(s)}return a(se(t,"]"),"']' expected"),Lt.Union(s,e)}parseChar(t){return"\\"==t.currCh?this.parseEscapeChar(t):this.parseSingleChar(t)}parseSingleChar(t){const e=t.currCh;return t.advance(1),kt.Single(e)}parsePropertyEscape(t){a(se(t,"\\{"),"Invalid property escape"),t.advance(2);let e=!1,s="",n="";for(;t.hasMore&&"}"!=t.currCh;)"="==t.currCh?e=!0:e?n+=t.currCh:s+=t.currCh,t.advance(1);return t.hasMore||this.throwError(t,"Invalid property escape"),s=s.trim(),n=n.trim(),e||(n=s,s="General_Category"),t.advance(1),kt.PropertyEscape(s,n)}parseEscapeChar(t){if(a(se(t,"\\"),"Expected '\\'"),t.hasMore||this.throwError(t,"Encounted unexpected end of input after \\"),se(t,"w"))return kt.Class(at.WORD_CHAR);if(se(t,"W"))return kt.Class(at.WORD_CHAR,!0);if(se(t,"d"))return kt.Class(at.DIGITS);if(se(t,"D"))return kt.Class(at.DIGITS,!0);if(se(t,"s"))return kt.Class(at.SPACES);if(se(t,"S"))return kt.Class(at.SPACES,!0);if(se(t,"0"))return kt.Single("\0");if(se(t,"r"))return kt.Single("\r");if(se(t,"n"))return kt.Single("\n");if(se(t,"f"))return kt.Single("\f");if(se(t,"b"))return kt.Single("\b");if(se(t,"v"))return kt.Single("\v");if(se(t,"t"))return kt.Single("\t");if(se(t,"\\"))return kt.Single("\\");if(se(t,"'"))return kt.Single("'");if(se(t,'"'))return kt.Single('"');if(se(t,"x")){t.hasMore||this.throwError(t,`Invalid hex sequence at ${t.index}`);const e=t.currCh+t.nextCh,s=parseInt(e,16);return a(!isNaN(s),`Invalid hex sequence: '${e}'`),t.advance(2),kt.Single(s)}if(se(t,"u")){t.canAdvance(3)||this.throwError(t,`Invalid unicode sequence at ${t.index}`);const e=t.substring(t.index,t.index+4),s=parseInt(e,16);return isNaN(s)&&this.throwError(t,`Invalid unicode sequence: '${e}'`),t.advance(4),kt.Single(s)}const e=t.currCh;return t.advance(1),kt.Single(e)}reduceLeft(t){const e=1==t.length?t[0]:new It(...t);return t.splice(0),e}throwError(t,e){throw new Error(e)}}function re(t,e){if("string"==typeof t){const s=new $t(oe(t,e),e);return s.pattern=t,s}if("RegExp"==t.constructor.name){const s=new $t(oe(t,e),e);return s.pattern=t.source,s}return new $t(t,e)}function ie(t){const e=new ne;try{const s=e.parse(new Qt(t));return null==s.dotAll&&(s.dotAll=!1),null==s.multiline&&(s.multiline=!1),s}catch(e){throw console.log("Error in FLEX RE: ",t),e}}function oe(t,e){e=e||{};const s="string"!=typeof t,n="string"==typeof t?t:t.source;s&&(e.unicode=t.unicode);const r=new ee(n,e).parse();return"string"!=typeof t&&(r.dotAll=t.dotAll,r.ignoreCase=t.ignoreCase,r.multiline=t.multiline),r}function ae(t,...e){return ie(String.raw(t,...e))}class le{constructor(){this._prog=null,this._vm=null,this.onError=null,this.allRules=[],this.onMatchHandlers=[],this.matchHandlersByValue={},this.variables=new Map,this.compiler=new Wt(t=>{let e=this.variables.get(t)||null;if(null==e&&(e=this.findRuleByValue(t)?.expr||null),null==e)throw new Error(`Invalid regex reference: ${t}`);return e})}getVar(t){return this.variables.get(t)||null}addVar(t,e){let s=this.variables.get(t)||null;return s=null==s?e:new Ot(s,e),this.variables.set(t,e),this}findRuleByValue(t){return this.allRules.find(e=>e.tag==t)||null}add(t,e,s=null){return"function"==typeof e&&(s=e,e=null),this.addRule(re(t,e),s)}addRule(t,e=null){return t.matchIndex=this.allRules.length,this.allRules.push(t),this.onMatchHandlers.push(e),this._prog=null,this._vm=null,this}on(t,e){return this.matchHandlersByValue[t]=e,this}get prog(){if(null==this._prog){const t=this.sortRules();this._prog=this.compiler.compile(t)}return this._prog}get vm(){return null==this._vm&&(this._vm=new Gt(this.prog)),this._vm}sortRules(){const t=this.allRules.map(t=>t);return t.sort((t,e)=>t.priority!=e.priority?e.priority-t.priority:t.matchIndex-e.matchIndex),t}}class he extends le{constructor(){super(...arguments),this.idCounter=0}getState(){return this.vm.getState()}setState(t){this.vm.setState(t)}reset(){this.idCounter=0,this._vm&&this._vm.setState(0)}next(t,e){if(!t.hasMore)return null;const s=t.index,n=t.currCh,r=this.vm.match(t);if(null==r){let r=null;if(r=t.index==s+1?new Kt(`Unexpected Character: ${n}`,s,1,"UnexpectedCharacter",n):new Kt(`Unexpected Symbol: ${t.substring(s,t.index)}`,s,t.index-s,"UnexpectedLexeme"),this.onError&&(r=this.onError(r,t,s)),null!=r)throw r;return this.next(t,e)}const i=this.allRules[r.matchIndex];let o=function(t,e,s){const n=new Jt(t,e.matchIndex,e.start,e.end);for(let t=0;t<e.positions.length;t+=2)e.positions[t]>=0&&(n.positions[Math.floor(t/2)]=[e.positions[t],e.positions[t+1]]);for(const[t,s]of e.groups){const e=Math.abs(t);e in n.groups||(n.groups[e]=[]),n.groups[e].push(s)}return null!=s&&(n.value=s.substring(e.start,e.end)),n}(i.tag,r,t);o.id=this.idCounter++;let a=this.onMatchHandlers[r.matchIndex];if(a||(a=this.matchHandlersByValue[i.tag]),a){if(o=a(i,t,o,e),null==o)return this.next(t,e)}else if(i.skip)return this.next(t,e);return o}tokenize(t,e=null){const s=[];"string"==typeof t&&(t=new Qt(t));let n=this.next(t,e);for(;n;){s.push(n);try{n=this.next(t,e)}catch(t){s.push({tag:"ERROR",start:t.offset,end:t.offset+t.length,value:t.message});break}}return s}}const ue=ae`["]([^"\\\n]|\\.|\\\n)*["]`,ce=ae`[']([^'\\\n]|\\.|\\\n)*[']`,de=String.raw`/(.+?(?<!\\))/([imus]*)`,fe=t=>"number"==typeof t?""+t:t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var ge,me,pe,be;!function(t){t.STRING="STRING",t.REGEX="REGEX",t.NUMBER="NUMBER",t.SPACES="SPACES",t.IDENT="IDENT",t.PCT_IDENT="PCT_IDENT",t.STAR="STAR",t.PLUS="PLUS",t.QMARK="QMARK",t.PIPE="PIPE",t.DOLLAR_NUM="DOLLAR_NUM",t.DOLLAR_IDENT="DOLLAR_IDENT",t.OPEN_PAREN="OPEN_PAREN",t.CLOSE_PAREN="CLOSE_PAREN",t.OPEN_BRACE="OPEN_BRACE",t.CLOSE_BRACE="CLOSE_BRACE",t.OPEN_SQ="OPEN_SQ",t.CLOSE_SQ="CLOSE_SQ",t.COMMENT="COMMENT",t.ARROW="ARROW",t.COLCOLHYPHEN="COLCOLHYPHEN",t.COLON="COLON",t.SEMI_COLON="SEMI_COLON"}(ge||(ge={})),function(t){t.GRAMMAR="GRAMMAR",t.DECL="DECL",t.RULE="RULE",t.PROD_NULL="PROD_NULL",t.PROD_STR="PROD_STR",t.PROD_UNION="PROD_UNION",t.PROD_NAME="PROD_NAME",t.PROD_STRING="PROD_STRING",t.PROD_NUM="PROD_NUM",t.PROD_IDENT="PROD_IDENT",t.PROD_STAR="PROD_STAR",t.PROD_PLUS="PROD_PLUS",t.PROD_OPTIONAL="PROD_OPTIONAL",t.IDENT="IDENT",t.ERROR="ERROR",t.COMMENT="COMMENT"}(me||(me={}));class Se{constructor(t,e){this.leftRecursive=!1,this.generatedTokenizer=new he,this.regexSyntax="js",e=e||{},this.symbolsByLabel={},this.grammar=e.grammar||new ot,this.leftRecursive=!("leftRecursive"in e)||e.leftRecursive||!1,this.newSymbolCallback=e.newSymbolCallback||null,this.tokenHandlers=e.tokenHandlers||{},this.parse(t)}symbolForLabel(t){return this.symbolsByLabel[t]||null}registerSymbol(t,e){a(!(t in this.symbolsByLabel),`${t} is already registered`),this.symbolsByLabel[t]=e}ensureSymbol(t,e){let s=this.symbolForLabel(t);return null!=s||(this.newSymbolCallback&&(s=this.newSymbolCallback(t,e)||null),null==s&&(s=e?this.grammar.newTerm(t):this.grammar.newNT(t)),this.registerSymbol(t,s)),s}parse(t){const e=function(){const t=new he;return t.add(/->/,{tag:ge.ARROW}),t.add(/\[/,{tag:ge.OPEN_SQ}),t.add(/\]/,{tag:ge.CLOSE_SQ}),t.add(/\(/,{tag:ge.OPEN_PAREN}),t.add(/\)/,{tag:ge.CLOSE_PAREN}),t.add(/\{/,{tag:ge.OPEN_BRACE}),t.add(/\}/,{tag:ge.CLOSE_BRACE}),t.add(/\*/,{tag:ge.STAR}),t.add(/\+/,{tag:ge.PLUS}),t.add(/\?/,{tag:ge.QMARK}),t.add(/;/,{tag:ge.SEMI_COLON}),t.add(/:/,{tag:ge.COLON}),t.add(/\|/,{tag:ge.PIPE}),t.add(/\s+/m,{tag:ge.SPACES},()=>null),t.add(/\/\*.*?\*\//s,{tag:ge.COMMENT},()=>null),t.add(/\/\/.*$/m,{tag:ge.COMMENT},()=>null),t.add(ce,{tag:ge.STRING},(t,e,s)=>(s.value=e.substring(s.start+1,s.end-1),s)),t.add(ue,{tag:ge.STRING},(t,e,s)=>(s.value=e.substring(s.start+1,s.end-1),s)),t.add(de,{tag:ge.REGEX},(t,e,s)=>{const n=e.substring(s.positions[1][0],s.positions[1][1]),r=e.substring(s.positions[3][0],s.positions[3][1]);return s.value=[n,r],s}),t.add(/\d+/,{tag:ge.NUMBER},(t,e,s)=>(s.value=parseInt(e.substring(s.start,s.end)),s)),t.add(/%([\w][\w\d_]*)/,{tag:ge.PCT_IDENT},(t,e,s)=>(s.value=e.substring(s.start+1,s.end),s)),t.add(/\$\d+/,{tag:ge.DOLLAR_NUM},(t,e,s)=>(s.value=parseInt(e.substring(s.start+1,s.end)),s)),t.add(/\$([\w][\w\d_]*)/,{tag:ge.DOLLAR_IDENT},(t,e,s)=>(s.value=e.substring(s.start+1,s.end),s)),t.add(/[\w][\w\d_]*/,{tag:ge.IDENT}),t}();this.tokenizer=new Zt((t,s)=>e.next(t,this),this),this.parseGrammar(new Qt(t))}parseRegex(t,e,s=0,n=""){if(""==n&&(n=this.regexSyntax),"js"==n){const n=this.tokenizer.expectToken(t,ge.STRING,ge.NUMBER,ge.REGEX);let r;if(e&&0!=e.length||(e="/"+n.value[0]+"/"+n.value[1]),n.tag==ge.STRING||n.tag==ge.NUMBER)r=re(fe(n.value),{tag:e,priority:s+20});else{if(n.tag!=ge.REGEX)throw new Ht(n);{let t=n.value[0];n.value[1].length>0&&(t=new RegExp(n.value[0],n.value[1])),r=re(t,{tag:e,priority:s+10})}}return r}{let n="";for(;t.hasMore&&"\n"!=t.currCh;)n+=t.currCh,t.advance();return n=n.trim(),e&&0!=e.length||(e="/"+n+"/"),new $t(ie(n),{tag:e,priority:s})}}parseGrammar(t){let e=this.tokenizer.peek(t);for(;null!=e;){if(e.tag==ge.IDENT)this.parseDecl(t);else{if(e.tag!=ge.PCT_IDENT)throw new SyntaxError(`Declaration must start with IDENT or PCT_IDENT. Found: '${e.value}' instead.`);this.tokenizer.next(t),this.parseDirective(t,e.value)}e=this.tokenizer.peek(t)}}parseDirective(t,e){if("start"==e){const e=this.tokenizer.expectToken(t,ge.IDENT);this.grammar.startSymbol=this.ensureSymbol(e.value,!1)}else if("resyntax"==e){const e=this.tokenizer.expectToken(t,ge.IDENT);if("js"!=e.value&&"flex"!=e.value)throw new SyntaxError("Invalid regex syntax: "+e.value);this.regexSyntax=e.value}else if(e.startsWith("skip")){const s=this.parseRegex(t,"",30,e.endsWith("flex")?"flex":""),n=this.parseTokenHandler(t);n?this.generatedTokenizer.addRule(s,(t,e,s)=>(n(t,e,s,this),null)):this.generatedTokenizer.addRule(s,()=>null)}else{if(!e.startsWith("token")&&!e.startsWith("define"))throw new Error("Invalid directive: "+e);{const s=e.startsWith("define"),n=this.tokenizer.expectToken(t,ge.IDENT,ge.STRING);let r=n.value;n.tag!=ge.STRING&&n.tag!=ge.NUMBER||(r=`"${n.value}"`);const i=this.parseRegex(t,r,0,e.endsWith("flex")?"flex":"");if(s)this.generatedTokenizer.addVar(r,i.expr);else{const e=this.parseTokenHandler(t);this.generatedTokenizer.addRule(i,e),this.ensureSymbol(r,!0)}}}}parseTokenHandler(t){if(!this.tokenizer.consumeIf(t,ge.OPEN_BRACE))return null;const e=this.tokenizer.expectToken(t,ge.IDENT);return this.tokenizer.expectToken(t,ge.CLOSE_BRACE),(t,s,n,r)=>{const i=this.tokenHandlers[e.value];if(!i)throw new Error("Handler method not found: "+e.value);return i(n,s,r)}}parseDecl(t){const e=this.tokenizer.expectToken(t,ge.IDENT);if(this.tokenizer.consumeIf(t,ge.ARROW,ge.COLON)){const s=this.ensureSymbol(e.value,!1);if(s.isTerminal)s.isTerminal=!1;else if(s.isAuxiliary)throw new Error("NT is already auxiliary and cannot be reused.");for(const[e,n]of this.parseProductions(t,this.grammar,s))this.grammar.add(s,e,n);this.tokenizer.expectToken(t,ge.SEMI_COLON)}}parseProductions(t,e,s){const n=[];for(;null!=this.tokenizer.peek(t);){const s=this.parseProd(t,e);if(n.push(s),!this.tokenizer.consumeIf(t,ge.PIPE)&&this.tokenizer.nextMatches(t,ge.CLOSE_SQ,ge.CLOSE_PAREN,ge.SEMI_COLON))break}return n}parseProd(t,e){const s=new nt;for(;!this.tokenizer.nextMatches(t,ge.CLOSE_PAREN,ge.CLOSE_SQ,ge.SEMI_COLON,ge.PIPE,ge.OPEN_BRACE);){let n=null;if(this.tokenizer.consumeIf(t,ge.OPEN_PAREN)){const s=this.parseProductions(t,e,null);0==s.length||(n=1==s.length?s[0][0]:e.anyof(...s.map(t=>t[0]))),this.tokenizer.expectToken(t,ge.CLOSE_PAREN)}else if(this.tokenizer.consumeIf(t,ge.OPEN_SQ)){const s=this.parseProductions(t,e,null);0==s.length||(n=1==s.length?e.opt(s[0][0]):e.opt(e.anyof(...s.map(t=>t[0])))),this.tokenizer.expectToken(t,ge.CLOSE_SQ)}else{if(!this.tokenizer.nextMatches(t,ge.IDENT,ge.STRING,ge.NUMBER,ge.REGEX))throw new Ht(this.tokenizer.peek(t));{const e=this.tokenizer.next(t);let s=e.value;if(e.tag==ge.STRING||e.tag==ge.NUMBER){s=`"${e.value}"`;const t=re(fe(e.value),{tag:s,priority:20});this.generatedTokenizer.addRule(t)}else if(e.tag==ge.REGEX){s="/"+e.value[0]+"/"+e.value[1];let t=e.value[0];e.value[1].length>0&&(t=new RegExp(e.value[0],e.value[1]));const n=re(t,{tag:s,priority:10});this.generatedTokenizer.addRule(n)}const r=this.ensureSymbol(s,!0);n=new nt(r)}}if(null==n)throw new Error("Could not determine node");this.tokenizer.consumeIf(t,ge.STAR)?n=e.atleast0(n,this.leftRecursive):this.tokenizer.consumeIf(t,ge.PLUS)?n=e.atleast1(n,this.leftRecursive):this.tokenizer.consumeIf(t,ge.QMARK)&&(n=e.opt(n)),s.extend(n)}let n=null;if(this.tokenizer.consumeIf(t,ge.OPEN_BRACE)){const e=this.tokenizer.expectToken(t,ge.DOLLAR_NUM,ge.IDENT);n=new rt(e.value),this.tokenizer.expectToken(t,ge.CLOSE_BRACE)}return[s,n]}}class ye{constructor(t,e,s,...n){this.id=t,this.sym=e,this.value=s,this.children=[],this.children=n||[]}get childCount(){return this.children.length}childAt(t){return t<0?this.children[this.children.length+t]:this.children[t]}get isTerminal(){return this.sym.isTerminal}add(t,e=-1){if(this.isTerminal)throw new Error(`Cannot add children (${t.sym.label}) to a terminal node: ${this.sym.label}`);return e<0?this.children.push(t):this.children.splice(e,0,t),this}splice(t,e,...s){return this.children.splice(t,e,...s),this}get reprString(){return this.debugValue(!1).join("\n")}debugValue(t=!0){if(t){const e=[this.sym.label];return this.value&&e.push(this.value),this.children.length>0&&e.push(this.children.map(e=>e.debugValue(t))),e}{const e=[];return this.value,e.push(null==this.value?this.sym.label:this.sym.label+" - "+this.value),this.children.forEach(s=>s.debugValue(t).forEach(t=>e.push(" "+t))),e}}}class Ee extends ye{constructor(){super(...arguments),this.parent=null}add(t,e=-1){return super.add(t,e),t.parent=this,this}splice(t,e,...s){for(const t of s)t.parent=this;return super.splice(t,e,...s)}}class we{setTokenizer(t){return this.tokenbuffer=new Zt(t,null),this}getSym(t){const e=this.grammar.getSym(t.tag);if(null==e)throw new Error("Invalid token tag: "+t.tag+", Value: "+t.value);return e}}class Ce extends we{parse(t,e=null){return"string"==typeof t&&(t=new Qt(t)),this.parseInput(t,e)}}class ve extends Error{constructor(t,e,s=null){super(t),this.type=e,this.value=s,Object.setPrototypeOf(this,new.target.prototype)}get name(){return this.constructor.name}}(be=pe||(pe={}))[be.ACCEPT=0]="ACCEPT",be[be.SHIFT=1]="SHIFT",be[be.REDUCE=2]="REDUCE",be[be.GOTO=3]="GOTO";class xe{constructor(){this.gotoState=null,this.rule=null}toString(){return this.tag==pe.ACCEPT?"Acc":this.tag==pe.SHIFT?"S"+this.gotoState:this.tag==pe.REDUCE?"R "+this.rule.id:""+this.gotoState}equals(t){return this.tag==t.tag&&this.gotoState==t.gotoState&&this.rule==t.rule}static Shift(t){const e=new xe;return e.tag=pe.SHIFT,e.gotoState=t,e}static Reduce(t){const e=new xe;return e.tag=pe.REDUCE,e.rule=t,e}static Goto(t){const e=new xe;return e.tag=pe.GOTO,e.gotoState=t,e}static Accept(){const t=new xe;return t.tag=pe.ACCEPT,t}}class _e{constructor(t){this.grammar=t,this.conflictActions={},this.actions={}}get hasConflicts(){return Object.keys(this.conflictActions).length>0}getActions(t,e,s=!1){let n;if(t in this.actions)n=this.actions[t];else{if(!s)return[];n=this.actions[t]={}}return e.id in n?n[e.id]:s?n[e.id]=[]:[]}addAction(t,e,s){const n=this.getActions(t,e,!0);return n.findIndex(t=>t.equals(s))<0&&n.push(s),n.length>1&&(this.conflictActions[t]=this.conflictActions[t]||{},this.conflictActions[t][e.label]=!0),this}get debugValue(){const t={};for(const e in this.actions){t[e]={};for(const s in this.actions[e]){const n=this.grammar.getSymById(s),r=this.actions[e][n.id]||[];r.length>0&&(t[e][n.label]=r.map(t=>t.toString()))}}return t}}class Ae{constructor(){this.stateStack=[],this.nodeStack=[]}push(t,e){this.stateStack.push(t),this.nodeStack.push(e)}top(t=0){return[this.stateStack[this.stateStack.length-1-t],this.nodeStack[this.nodeStack.length-1-t]]}pop(){const t=this.top();return this.stateStack.pop(),this.nodeStack.pop(),t}popN(t=1){const e=this.stateStack.length;this.stateStack.splice(e-t,t),this.nodeStack.splice(e-t,t)}get isEmpty(){return 0==this.stateStack.length||0==this.nodeStack.length}}class Ne extends Ce{constructor(t,e={}){super(),this.parseTable=t}get grammar(){return this.parseTable.grammar}parseInput(t,e){e=e||{},this.tokenbuffer.tokenizerContext=e.tokenizerContext,0!=e.buildParseTree&&(e.buildParseTree=!0),0!=e.copySingleChild&&(e.copySingleChild=!0);let s=0;const n=new Ae;n.push(0,new Ee(s++,this.grammar.augStartRule.nt,null));const r=this.tokenbuffer,i=this.grammar;let o=null;function l(t){if(e?.actionResolver)return e.actionResolver(t,n,r);if(t.length>1)throw new Error("Multiple actions found.");return t[0]}function h(){try{return r.peek(t)}catch(s){if(!e?.onTokenError||!e?.onTokenError(s,t))throw s;return h()}}for(;;){let u=h();if(null==u){if(n.isEmpty)break}else e.onNextToken&&(u=e.onNextToken(u));const c=null==u?i.Eof:this.getSym(u),d=null==u?null:u.value;let[f,g]=n.top();const m=this.parseTable.getActions(f,c);if(null==m||0==m.length)throw new ve(`Unexpected Token: '${c.label}'`,"UnexpectedToken",{state:f,token:u,nextSym:c});const p=l(m);if(p.tag==pe.ACCEPT)break;if(p.tag==pe.SHIFT){r.next(t);const e=new Ee(s++,c,d);n.push(p.gotoState,e)}else{a(null!=p.rule,"Nonterm and ruleindex must be provided for a reduction action");const t=p.rule.rhs.length;let r=new Ee(s++,p.rule.nt,null);if(e.buildParseTree)for(let s=t-1;s>=0;s--){const t=n.top(s)[1];if(e.beforeAddingChildNode)for(const s of e.beforeAddingChildNode(r,t))r.add(s);else null!=t&&r.add(t)}if(p.rule.action)if(p.rule.action.isFunction){const t=p.rule.action.value,s=e.ruleHandlers[t];if(!s)throw new Error("Action handler not found: "+t);r.value=s(p.rule,r,...r.children)}else r.value=r.children[p.rule.action.value-1].value;else e.onReduction?r=e.onReduction(r,p.rule):1==r.children.length&&e.copySingleChild&&(r.value=r.children[0].value);n.popN(t),[f,g]=n.top();const i=l(this.parseTable.getActions(f,p.rule.nt));a(null!=i&&null!=i.gotoState,"Top item does not have an action."),n.push(i.gotoState,r),o=r}}return o}}class Te{constructor(t,e=0){this.id=0,this.rule=t,this.position=e}advance(){return a(this.position<this.rule.rhs.length),new Te(this.rule,this.position+1)}copy(){return new Te(this.rule,this.position)}get key(){return a(!isNaN(this.rule.id),"Rule's ID is not yet set."),this.rule.id+":"+this.position}compareTo(t){let e=this.rule.id-t.rule.id;return 0==e&&(e=this.position-t.position),e}equals(t){return 0==this.compareTo(t)}get debugString(){const t=this.rule,e=this.position,s=t.rhs.syms.slice(0,e).join(" "),n=t.rhs.syms.slice(e).join(" ");return`${t.id} - ${t.nt} -> ${s} • ${n}`}}class Ie{constructor(t,...e){this.id=0,this._key=null,this._lookaheads={},this._hasLookAheads=!1,this.itemGraph=t,this.values=e}copy(){const t=new Ie(this.itemGraph,...this.values);return t._lookaheads={...this._lookaheads},t._hasLookAheads=this._hasLookAheads,t}addLookAhead(t,e){t.id in this._lookaheads||(this._lookaheads[t.id]=[]);for(const s of this._lookaheads[t.id])if(s==e)return!1;return this._hasLookAheads=!0,this._key=null,this._lookaheads[t.id].push(e),this._lookaheads[t.id].sort((t,e)=>t.id-e.id),!0}clearLookAheads(){this._lookaheads={}}getLookAheads(t){return this._lookaheads[t.id]||[]}get key(){return null==this._key&&(this._key=this.revalKey()),this._key}revalKey(){return this.hasLookAheads?(this.values.sort(),this.values.map(t=>t+"["+(this._lookaheads[t]||[]).map(t=>t.id).join(",")+"]").join("/")):(this.values.sort(),this.values.join("/"))}has(t){return this.values.indexOf(t)>=0}equals(t){return this.key==t.key}add(t){return this.has(t)||(this.values.push(t),this._key=null),this}get size(){return this.values.length}get debugString(){return this.debugValue.join("\n")}get hasLookAheads(){return this._hasLookAheads}get debugValue(){if(this.hasLookAheads){const t=this.values.map(t=>this.itemGraph.items.get(t));return t.sort((t,e)=>t.compareTo(e)),t.map(t=>{const e=this.getLookAheads(t).map(t=>t.label).sort((t,e)=>t.localeCompare(e)).join(", ");return e.length>0?`${t.debugString} / ( ${e} )`:t.debugString})}{const t=this.values.map(t=>this.itemGraph.items.get(t));return t.sort((t,e)=>t.compareTo(e)),t.map(t=>t.debugString)}}}class Oe{constructor(t){this.grammar=t,this.gotoSets={},this.items=new Y,this.itemSets=new Y}startItem(){return a(null!=this.grammar.startSymbol,"Start symbol must be set"),a(null!=(this.grammar.augStartRule||null),"Grammar is not augmented"),this.items.ensure(new Te(this.grammar.augStartRule))}reset(){this.grammar.refresh(),this.gotoSets={},this.items.clear(),this.itemSets.clear(),this.startSet()}refresh(){return this.reset(),this.grammar.refresh(),this.evalGotoSets(),this}evalGotoSets(){const t=this.itemSets;for(let e=0;e<t.size;e++){const s=t.get(e);for(const t of this.grammar.allSymbols)if(t!=this.grammar.Null){const e=this.goto(s,t);e.size>0&&this.setGoto(s,t,e)}}}goto(t,e){const s=this.newItemSet();for(const n of t.values){const r=this.items.get(n),i=r.rule;r.position<i.rhs.length&&i.rhs.syms[r.position]==e&&this.advanceItemAndAdd(r,t,s)}return this.closure(s)}advanceItemAndAdd(t,e,s){const n=this.items.ensure(t.advance());s.add(n.id);for(const r of e.getLookAheads(t))s.addLookAhead(n,r)}newItemSet(...t){return new Ie(this,...t.map(t=>t.id))}get size(){return this.itemSets.size}ensureGotoSet(t){return t.id in this.gotoSets||(this.gotoSets[t.id]={}),this.gotoSets[t.id]}setGoto(t,e,s){this.ensureGotoSet(t)[e.id]=s}getGoto(t,e){return(this.gotoSets[t.id]||{})[e.id]||null}forEachGoto(t,e){const s=this.gotoSets[t.id]||{};for(const t in s)if(0==e(this.grammar.getSymById(t),s[t]))break}gotoSetFor(t){return this.gotoSets[t.id]||{}}get debugValue(){const t={};return this.itemSets.entries.forEach(e=>{t[e.id]={items:[],goto:{}},t[e.id].items=e.debugValue;const s=this.gotoSets[e.id];for(const n in s){const r=this.grammar.getSymById(n);t[e.id].goto=t[e.id].goto||{},t[e.id].goto[r.label]=s[n].id}}),t}}class Re extends Oe{startSet(){const t=this.startItem(),e=this.newItemSet(t);return this.closure(e)}closure(t){const e=new Ie(this,...t.values);for(let t=0;t<e.values.length;t++){const s=e.values[t],n=this.items.get(s),r=n.rule;if(n.position<r.rhs.length){const t=r.rhs.syms[n.position];if(!t.isTerminal)for(const s of this.grammar.rulesForNT(t)){const t=this.items.ensure(new Te(s,0));e.add(t.id)}}}return 0==e.size?e:this.itemSets.ensure(e)}}class ke extends Oe{startSet(){const t=this.startItem(),e=this.newItemSet(t);return e.addLookAhead(t,this.grammar.Eof),this.closure(e)}closure(t){const e=t.copy();for(let t=0;t<e.values.length;t++){const s=e.values[t],n=this.items.get(s);if(n.position>=n.rule.rhs.length)continue;const r=n.rule.rhs,i=r.syms[n.position];if(!i.isTerminal)for(const t of e.getLookAheads(n)){const s=r.copy().append(t);this.grammar.firstSets.forEachTermIn(s,n.position+1,t=>{if(null!=t){const s=this.grammar.rulesForNT(i);for(const n of s){const s=this.items.ensure(new Te(n,0));e.add(s.id),e.addLookAhead(s,t)}}})}}return 0==e.size?e:this.itemSets.ensure(e)}}function Le(t){const e=function(t){const e=new Re(t).refresh();for(const s of e.itemSets.entries)Me(t,e,s);return e}(t);return[Pe(e,t),e]}function Me(t,e,s){for(const n of s.values){const r=e.items.get(n),i=r.rule;r.position>=i.rhs.length&&t.followSets.forEachTerm(i.nt,t=>{null!=t&&(a(t.isTerminal),s.addLookAhead(r,t))})}}function Pe(t,e){const s=new _e(e);for(const n of t.itemSets.entries){for(const r of n.values){const i=t.items.get(r),o=i.rule;if(i.position<o.rhs.length){const e=o.rhs.syms[i.position];if(e.isTerminal){const r=t.getGoto(n,e);r&&s.addAction(n.id,e,xe.Shift(r.id))}}else if(!o.nt.equals(e.augStartRule.nt)){const t=n.getLookAheads(i);for(const e of t)s.addAction(n.id,e,xe.Reduce(o))}}t.forEachGoto(n,(t,e)=>{null==t||t.isTerminal||s.addAction(n.id,t,xe.Goto(e.id))});const r=t.items.ensure(new Te(e.augStartRule,1));n.addLookAhead(r,e.Eof),n.has(r.id)&&s.addAction(n.id,e.Eof,xe.Accept())}return s}function Be(t,e,s,n,r){function i(t,e,n,o){if(e<0)a(null!=(s.gotoSets[n][t.nt.id]||null),"Transition on rule.nt missing from start state"),o.add(n);else{const s=t.rhs.syms[e],l=r[n][s.id]||null;a(null!=l,"Prev set should not be null"),l.forEach(s=>i(t,e-1,s,o))}}n.clearLookAheads();for(const r of n.values){const o=s.items.get(r),l=o.rule;if(o.position>=l.rhs.length){const s=new Set;i(l,l.rhs.length-1,n.id,s),s.forEach(s=>{const r=`[${s}:${l.nt.label}]`,i=e.getSym(r);a(null!=i,"Augmented grammar symbol [p:A] not found"),e.followSets.forEachTerm(i,s=>{if(null!=s&&s!=e.Eof){a(s.isTerminal);const e=s.label.substring(s.label.indexOf(":")+1,s.label.length-1).trim(),r=t.getSym(e);a(null!=r,`T (${e}) in [r:T] cannot be null`),n.addLookAhead(o,r)}})})}}}const $e=Symbol.for("yaml.alias"),De=Symbol.for("yaml.document"),Ve=Symbol.for("yaml.map"),Ue=Symbol.for("yaml.pair"),Fe=Symbol.for("yaml.scalar"),je=Symbol.for("yaml.seq"),Ge=Symbol.for("yaml.node.type"),ze=t=>!!t&&"object"==typeof t&&t[Ge]===$e,We=t=>!!t&&"object"==typeof t&&t[Ge]===De,Ke=t=>!!t&&"object"==typeof t&&t[Ge]===Ve,He=t=>!!t&&"object"==typeof t&&t[Ge]===Ue,qe=t=>!!t&&"object"==typeof t&&t[Ge]===Fe,Qe=t=>!!t&&"object"==typeof t&&t[Ge]===je;function Ye(t){if(t&&"object"==typeof t)switch(t[Ge]){case Ve:case je:return!0}return!1}function Je(t){if(t&&"object"==typeof t)switch(t[Ge]){case $e:case Ve:case Fe:case je:return!0}return!1}const Ze=t=>(qe(t)||Ye(t))&&!!t.anchor,Xe=Symbol("break visit"),ts=Symbol("skip children"),es=Symbol("remove node");function ss(t,e){const s=os(e);We(t)?ns(null,t.contents,s,Object.freeze([t]))===es&&(t.contents=null):ns(null,t,s,Object.freeze([]))}function ns(t,e,s,n){const r=as(t,e,s,n);if(Je(r)||He(r))return ls(t,n,r),ns(t,r,s,n);if("symbol"!=typeof r)if(Ye(e)){n=Object.freeze(n.concat(e));for(let t=0;t<e.items.length;++t){const r=ns(t,e.items[t],s,n);if("number"==typeof r)t=r-1;else{if(r===Xe)return Xe;r===es&&(e.items.splice(t,1),t-=1)}}}else if(He(e)){n=Object.freeze(n.concat(e));const t=ns("key",e.key,s,n);if(t===Xe)return Xe;t===es&&(e.key=null);const r=ns("value",e.value,s,n);if(r===Xe)return Xe;r===es&&(e.value=null)}return r}async function rs(t,e){const s=os(e);We(t)?await is(null,t.contents,s,Object.freeze([t]))===es&&(t.contents=null):await is(null,t,s,Object.freeze([]))}async function is(t,e,s,n){const r=await as(t,e,s,n);if(Je(r)||He(r))return ls(t,n,r),is(t,r,s,n);if("symbol"!=typeof r)if(Ye(e)){n=Object.freeze(n.concat(e));for(let t=0;t<e.items.length;++t){const r=await is(t,e.items[t],s,n);if("number"==typeof r)t=r-1;else{if(r===Xe)return Xe;r===es&&(e.items.splice(t,1),t-=1)}}}else if(He(e)){n=Object.freeze(n.concat(e));const t=await is("key",e.key,s,n);if(t===Xe)return Xe;t===es&&(e.key=null);const r=await is("value",e.value,s,n);if(r===Xe)return Xe;r===es&&(e.value=null)}return r}function os(t){return"object"==typeof t&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function as(t,e,s,n){return"function"==typeof s?s(t,e,n):Ke(e)?s.Map?.(t,e,n):Qe(e)?s.Seq?.(t,e,n):He(e)?s.Pair?.(t,e,n):qe(e)?s.Scalar?.(t,e,n):ze(e)?s.Alias?.(t,e,n):void 0}function ls(t,e,s){const n=e[e.length-1];if(Ye(n))n.items[t]=s;else if(He(n))"key"===t?n.key=s:n.value=s;else{if(!We(n)){const t=ze(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${t} parent`)}n.contents=s}}ss.BREAK=Xe,ss.SKIP=ts,ss.REMOVE=es,rs.BREAK=Xe,rs.SKIP=ts,rs.REMOVE=es;const hs={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},us=t=>t.replace(/[!,[\]{}]/g,t=>hs[t]);class cs{constructor(t,e){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},cs.defaultYaml,t),this.tags=Object.assign({},cs.defaultTags,e)}clone(){const t=new cs(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new cs(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:cs.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},cs.defaultTags)}return t}add(t,e){this.atNextDocument&&(this.yaml={explicit:cs.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},cs.defaultTags),this.atNextDocument=!1);const s=t.trim().split(/[ \t]+/),n=s.shift();switch(n){case"%TAG":{if(2!==s.length&&(e(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[t,n]=s;return this.tags[t]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==s.length)return e(0,"%YAML directive should contain exactly one part"),!1;const[t]=s;return"1.1"===t||"1.2"===t?(this.yaml.version=t,!0):(e(6,`Unsupported YAML version ${t}`,/^\d+\.\d+$/.test(t)),!1)}default:return e(0,`Unknown directive ${n}`,!0),!1}}tagName(t,e){if("!"===t)return"!";if("!"!==t[0])return e(`Not a valid tag: ${t}`),null;if("<"===t[1]){const s=t.slice(2,-1);return"!"===s||"!!"===s?(e(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(">"!==t[t.length-1]&&e("Verbatim tags must end with a >"),s)}const[,s,n]=t.match(/^(.*!)([^!]*)$/s);n||e(`The ${t} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(n)}catch(t){return e(String(t)),null}return"!"===s?t:(e(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[e,s]of Object.entries(this.tags))if(t.startsWith(s))return e+us(t.substring(s.length));return"!"===t[0]?t:`!<${t}>`}toString(t){const e=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let n;if(t&&s.length>0&&Je(t.contents)){const e={};ss(t.contents,(t,s)=>{Je(s)&&s.tag&&(e[s.tag]=!0)}),n=Object.keys(e)}else n=[];for(const[r,i]of s)"!!"===r&&"tag:yaml.org,2002:"===i||t&&!n.some(t=>t.startsWith(i))||e.push(`%TAG ${r} ${i}`);return e.join("\n")}}function ds(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){const e=JSON.stringify(t);throw new Error(`Anchor must not contain whitespace or control characters: ${e}`)}return!0}function fs(t,e,s,n){if(n&&"object"==typeof n)if(Array.isArray(n))for(let e=0,s=n.length;e<s;++e){const s=n[e],r=fs(t,n,String(e),s);void 0===r?delete n[e]:r!==s&&(n[e]=r)}else if(n instanceof Map)for(const e of Array.from(n.keys())){const s=n.get(e),r=fs(t,n,e,s);void 0===r?n.delete(e):r!==s&&n.set(e,r)}else if(n instanceof Set)for(const e of Array.from(n)){const s=fs(t,n,e,e);void 0===s?n.delete(e):s!==e&&(n.delete(e),n.add(s))}else for(const[e,s]of Object.entries(n)){const r=fs(t,n,e,s);void 0===r?delete n[e]:r!==s&&(n[e]=r)}return t.call(e,s,n)}function gs(t,e,s){if(Array.isArray(t))return t.map((t,e)=>gs(t,String(e),s));if(t&&"function"==typeof t.toJSON){if(!s||!Ze(t))return t.toJSON(e,s);const n={aliasCount:0,count:1,res:void 0};s.anchors.set(t,n),s.onCreate=t=>{n.res=t,delete s.onCreate};const r=t.toJSON(e,s);return s.onCreate&&s.onCreate(r),r}return"bigint"!=typeof t||s?.keep?t:Number(t)}cs.defaultYaml={explicit:!1,version:"1.2"},cs.defaultTags={"!!":"tag:yaml.org,2002:"};class ms{constructor(t){Object.defineProperty(this,Ge,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:e,maxAliasCount:s,onAnchor:n,reviver:r}={}){if(!We(t))throw new TypeError("A document argument is required");const i={anchors:new Map,doc:t,keep:!0,mapAsMap:!0===e,mapKeyWarned:!1,maxAliasCount:"number"==typeof s?s:100},o=gs(this,"",i);if("function"==typeof n)for(const{count:t,res:e}of i.anchors.values())n(e,t);return"function"==typeof r?fs(r,{"":o},"",o):o}}class ps extends ms{constructor(t){super($e),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,e){let s,n;e?.aliasResolveCache?s=e.aliasResolveCache:(s=[],ss(t,{Node:(t,e)=>{(ze(e)||Ze(e))&&s.push(e)}}),e&&(e.aliasResolveCache=s));for(const t of s){if(t===this)break;t.anchor===this.source&&(n=t)}return n}toJSON(t,e){if(!e)return{source:this.source};const{anchors:s,doc:n,maxAliasCount:r}=e,i=this.resolve(n,e);if(!i){const t=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(t)}let o=s.get(i);if(o||(gs(i,null,e),o=s.get(i)),void 0===o?.res)throw new ReferenceError("This should not happen: Alias anchor was not resolved?");if(r>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=bs(n,i,s)),o.count*o.aliasCount>r))throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack");return o.res}toString(t,e,s){const n=`*${this.source}`;if(t){if(ds(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const t=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(t)}if(t.implicitKey)return`${n} `}return n}}function bs(t,e,s){if(ze(e)){const n=e.resolve(t),r=s&&n&&s.get(n);return r?r.count*r.aliasCount:0}if(Ye(e)){let n=0;for(const r of e.items){const e=bs(t,r,s);e>n&&(n=e)}return n}if(He(e)){const n=bs(t,e.key,s),r=bs(t,e.value,s);return Math.max(n,r)}return 1}const Ss=t=>!t||"function"!=typeof t&&"object"!=typeof t;class ys extends ms{constructor(t){super(Fe),this.value=t}toJSON(t,e){return e?.keep?this.value:gs(this.value,t,e)}toString(){return String(this.value)}}function Es(t,e,s){if(We(t)&&(t=t.contents),Je(t))return t;if(He(t)){const e=s.schema[Ve].createNode?.(s.schema,null,s);return e.items.push(t),e}(t instanceof String||t instanceof Number||t instanceof Boolean||"undefined"!=typeof BigInt&&t instanceof BigInt)&&(t=t.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=s;let l;if(n&&t&&"object"==typeof t){if(l=a.get(t),l)return l.anchor??(l.anchor=r(t)),new ps(l.anchor);l={anchor:null,node:null},a.set(t,l)}e?.startsWith("!!")&&(e="tag:yaml.org,2002:"+e.slice(2));let h=function(t,e,s){if(e){const t=s.filter(t=>t.tag===e),n=t.find(t=>!t.format)??t[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return s.find(e=>e.identify?.(t)&&!e.format)}(t,e,o.tags);if(!h){if(t&&"function"==typeof t.toJSON&&(t=t.toJSON()),!t||"object"!=typeof t){const e=new ys(t);return l&&(l.node=e),e}h=t instanceof Map?o[Ve]:Symbol.iterator in Object(t)?o[je]:o[Ve]}i&&(i(h),delete s.onTagObj);const u=h?.createNode?h.createNode(s.schema,t,s):"function"==typeof h?.nodeClass?.from?h.nodeClass.from(s.schema,t,s):new ys(t);return e?u.tag=e:h.default||(u.tag=h.tag),l&&(l.node=u),u}function ws(t,e,s){let n=s;for(let t=e.length-1;t>=0;--t){const s=e[t];if("number"==typeof s&&Number.isInteger(s)&&s>=0){const t=[];t[s]=n,n=t}else n=new Map([[s,n]])}return Es(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}ys.BLOCK_FOLDED="BLOCK_FOLDED",ys.BLOCK_LITERAL="BLOCK_LITERAL",ys.PLAIN="PLAIN",ys.QUOTE_DOUBLE="QUOTE_DOUBLE",ys.QUOTE_SINGLE="QUOTE_SINGLE";class Cs extends ms{constructor(t,e){super(t),Object.defineProperty(this,"schema",{value:e,configurable:!0,enumerable:!1,writable:!0})}clone(t){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(e.schema=t),e.items=e.items.map(e=>Je(e)||He(e)?e.clone(t):e),this.range&&(e.range=this.range.slice()),e}addIn(t,e){if((t=>null==t||"object"==typeof t&&!!t[Symbol.iterator]().next().done)(t))this.add(e);else{const[s,...n]=t,r=this.get(s,!0);if(Ye(r))r.addIn(n,e);else{if(void 0!==r||!this.schema)throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`);this.set(s,ws(this.schema,n,e))}}}deleteIn(t){const[e,...s]=t;if(0===s.length)return this.delete(e);const n=this.get(e,!0);if(Ye(n))return n.deleteIn(s);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${s}`)}getIn(t,e){const[s,...n]=t,r=this.get(s,!0);return 0===n.length?!e&&qe(r)?r.value:r:Ye(r)?r.getIn(n,e):void 0}hasAllNullValues(t){return this.items.every(e=>{if(!He(e))return!1;const s=e.value;return null==s||t&&qe(s)&&null==s.value&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(t){const[e,...s]=t;if(0===s.length)return this.has(e);const n=this.get(e,!0);return!!Ye(n)&&n.hasIn(s)}setIn(t,e){const[s,...n]=t;if(0===n.length)this.set(s,e);else{const t=this.get(s,!0);if(Ye(t))t.setIn(n,e);else{if(void 0!==t||!this.schema)throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`);this.set(s,ws(this.schema,n,e))}}}}const vs=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function xs(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}const _s=(t,e,s)=>t.endsWith("\n")?xs(s,e):s.includes("\n")?"\n"+xs(s,e):(t.endsWith(" ")?"":" ")+s,As="flow",Ns="block",Ts="quoted";function Is(t,e,s="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return t;r<i&&(i=0);const l=Math.max(1+i,1+r-e.length);if(t.length<=l)return t;const h=[],u={};let c,d,f=r-e.length;"number"==typeof n&&(n>r-Math.max(2,i)?h.push(0):f=r-n);let g=!1,m=-1,p=-1,b=-1;s===Ns&&(m=Os(t,m,e.length),-1!==m&&(f=m+l));for(let n;n=t[m+=1];){if(s===Ts&&"\\"===n){switch(p=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if("\n"===n)s===Ns&&(m=Os(t,m,e.length)),f=m+e.length+l,c=void 0;else{if(" "===n&&d&&" "!==d&&"\n"!==d&&"\t"!==d){const e=t[m+1];e&&" "!==e&&"\n"!==e&&"\t"!==e&&(c=m)}if(m>=f)if(c)h.push(c),f=c+l,c=void 0;else if(s===Ts){for(;" "===d||"\t"===d;)d=n,n=t[m+=1],g=!0;const e=m>b+1?m-2:p-1;if(u[e])return t;h.push(e),u[e]=!0,f=e+l,c=void 0}else g=!0}d=n}if(g&&a&&a(),0===h.length)return t;o&&o();let S=t.slice(0,h[0]);for(let n=0;n<h.length;++n){const r=h[n],i=h[n+1]||t.length;0===r?S=`\n${e}${t.slice(0,i)}`:(s===Ts&&u[r]&&(S+=`${t[r]}\\`),S+=`\n${e}${t.slice(r+1,i)}`)}return S}function Os(t,e,s){let n=e,r=e+1,i=t[r];for(;" "===i||"\t"===i;)if(e<r+s)i=t[++e];else{do{i=t[++e]}while(i&&"\n"!==i);n=e,r=e+1,i=t[r]}return n}const Rs=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ks=t=>/^(%|---|\.\.\.)/m.test(t);function Ls(t,e){const s=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return s;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ks(t)?" ":"");let o="",a=0;for(let t=0,e=s[t];e;e=s[++t])if(" "===e&&"\\"===s[t+1]&&"n"===s[t+2]&&(o+=s.slice(a,t)+"\\ ",t+=1,a=t,e="\\"),"\\"===e)switch(s[t+1]){case"u":{o+=s.slice(a,t);const e=s.substr(t+2,4);switch(e){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===e.substr(0,2)?o+="\\x"+e.substr(2):o+=s.substr(t,6)}t+=5,a=t+1}break;case"n":if(n||'"'===s[t+2]||s.length<r)t+=1;else{for(o+=s.slice(a,t)+"\n\n";"\\"===s[t+2]&&"n"===s[t+3]&&'"'!==s[t+4];)o+="\n",t+=2;o+=i," "===s[t+2]&&(o+="\\"),t+=1,a=t+1}break;default:t+=1}return o=a?o+s.slice(a):s,n?o:Is(o,i,Ts,Rs(e,!1))}function Ms(t,e){if(!1===e.options.singleQuote||e.implicitKey&&t.includes("\n")||/[ \t]\n|\n[ \t]/.test(t))return Ls(t,e);const s=e.indent||(ks(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&\n${s}`)+"'";return e.implicitKey?n:Is(n,s,As,Rs(e,!1))}function Ps(t,e){const{singleQuote:s}=e.options;let n;if(!1===s)n=Ls;else{const e=t.includes('"'),r=t.includes("'");n=e&&!r?Ms:r&&!e?Ls:s?Ms:Ls}return n(t,e)}let Bs;try{Bs=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{Bs=/\n+(?!\n|$)/g}function $s({comment:t,type:e,value:s},n,r,i){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(s))return Ps(s,n);const h=n.indent||(n.forceBlockIndent||ks(s)?" ":""),u="literal"===o||"folded"!==o&&e!==ys.BLOCK_FOLDED&&(e===ys.BLOCK_LITERAL||!function(t,e,s){if(!e||e<0)return!1;const n=e-s,r=t.length;if(r<=n)return!1;for(let e=0,s=0;e<r;++e)if("\n"===t[e]){if(e-s>n)return!0;if(s=e+1,r-s<=n)return!1}return!0}(s,l,h.length));if(!s)return u?"|\n":">\n";let c,d;for(d=s.length;d>0;--d){const t=s[d-1];if("\n"!==t&&"\t"!==t&&" "!==t)break}let f=s.substring(d);const g=f.indexOf("\n");-1===g?c="-":s===f||g!==f.length-1?(c="+",i&&i()):c="",f&&(s=s.slice(0,-f.length),"\n"===f[f.length-1]&&(f=f.slice(0,-1)),f=f.replace(Bs,`$&${h}`));let m,p=!1,b=-1;for(m=0;m<s.length;++m){const t=s[m];if(" "===t)p=!0;else{if("\n"!==t)break;b=m}}let S=s.substring(0,b<m?b+1:m);S&&(s=s.substring(S.length),S=S.replace(/\n+/g,`$&${h}`));let y=(p?h?"2":"1":"")+c;if(t&&(y+=" "+a(t.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){const t=s.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${h}`);let r=!1;const i=Rs(n,!0);"folded"!==o&&e!==ys.BLOCK_FOLDED&&(i.onOverflow=()=>{r=!0});const a=Is(`${S}${t}${f}`,h,Ns,i);if(!r)return`>${y}\n${h}${a}`}return`|${y}\n${h}${S}${s=s.replace(/\n+/g,`$&${h}`)}${f}`}function Ds(t,e,s,n){const{implicitKey:r,inFlow:i}=e,o="string"==typeof t.value?t:Object.assign({},t,{value:String(t.value)});let{type:a}=t;a!==ys.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ys.QUOTE_DOUBLE);const l=t=>{switch(t){case ys.BLOCK_FOLDED:case ys.BLOCK_LITERAL:return r||i?Ps(o.value,e):$s(o,e,s,n);case ys.QUOTE_DOUBLE:return Ls(o.value,e);case ys.QUOTE_SINGLE:return Ms(o.value,e);case ys.PLAIN:return function(t,e,s,n){const{type:r,value:i}=t,{actualString:o,implicitKey:a,indent:l,indentStep:h,inFlow:u}=e;if(a&&i.includes("\n")||u&&/[[\]{},]/.test(i))return Ps(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes("\n")?Ps(i,e):$s(t,e,s,n);if(!a&&!u&&r!==ys.PLAIN&&i.includes("\n"))return $s(t,e,s,n);if(ks(i)){if(""===l)return e.forceBlockIndent=!0,$s(t,e,s,n);if(a&&l===h)return Ps(i,e)}const c=i.replace(/\n+/g,`$&\n${l}`);if(o){const t=t=>t.default&&"tag:yaml.org,2002:str"!==t.tag&&t.test?.test(c),{compat:s,tags:n}=e.doc.schema;if(n.some(t)||s?.some(t))return Ps(i,e)}return a?c:Is(c,l,As,Rs(e,!1))}(o,e,s,n);default:return null}};let h=l(a);if(null===h){const{defaultKeyType:t,defaultStringType:s}=e.options,n=r&&t||s;if(h=l(n),null===h)throw new Error(`Unsupported default string type ${n}`)}return h}function Vs(t,e,s,n){if(He(t))return t.toString(e,s,n);if(ze(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let r;const i=Je(t)?t:e.doc.createNode(t,{onTagObj:t=>r=t});r??(r=function(t,e){if(e.tag){const s=t.filter(t=>t.tag===e.tag);if(s.length>0)return s.find(t=>t.format===e.format)??s[0]}let s,n;if(qe(e)){n=e.value;let r=t.filter(t=>t.identify?.(n));if(r.length>1){const t=r.filter(t=>t.test);t.length>0&&(r=t)}s=r.find(t=>t.format===e.format)??r.find(t=>!t.format)}else n=e,s=t.find(t=>t.nodeClass&&n instanceof t.nodeClass);if(!s)throw new Error(`Tag not resolved for ${n?.constructor?.name??(null===n?"null":typeof n)} value`);return s}(e.doc.schema.tags,i));const o=function(t,e,{anchors:s,doc:n}){if(!n.directives)return"";const r=[],i=(qe(t)||Ye(t))&&t.anchor;i&&ds(i)&&(s.add(i),r.push(`&${i}`));const o=t.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a="function"==typeof r.stringify?r.stringify(i,e,s,n):qe(i)?Ds(i,e,s,n):i.toString(e,s,n);return o?qe(i)||"{"===a[0]||"["===a[0]?`${o} ${a}`:`${o}\n${e.indent}${a}`:a}const Us="<<",Fs={identify:t=>t===Us||"symbol"==typeof t&&t.description===Us,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ys(Symbol(Us)),{addToJSMap:js}),stringify:()=>Us};function js(t,e,s){if(s=t&&ze(s)?s.resolve(t.doc):s,Qe(s))for(const n of s.items)Gs(t,e,n);else if(Array.isArray(s))for(const n of s)Gs(t,e,n);else Gs(t,e,s)}function Gs(t,e,s){const n=t&&ze(s)?s.resolve(t.doc):s;if(!Ke(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,t,Map);for(const[t,s]of r)e instanceof Map?e.has(t)||e.set(t,s):e instanceof Set?e.add(t):Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function zs(t,e,{key:s,value:n}){if(Je(s)&&s.addToJSMap)s.addToJSMap(t,e,n);else if(((t,e)=>(Fs.identify(e)||qe(e)&&(!e.type||e.type===ys.PLAIN)&&Fs.identify(e.value))&&t?.doc.schema.tags.some(t=>t.tag===Fs.tag&&t.default))(t,s))js(t,e,n);else{const r=gs(s,"",t);if(e instanceof Map)e.set(r,gs(n,r,t));else if(e instanceof Set)e.add(r);else{const i=function(t,e,s){if(null===e)return"";if("object"!=typeof e)return String(e);if(Je(t)&&s?.doc){const e=function(t){const e=Object.assign({blockQuote:!0,commentString:vs,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,{});let s;switch(e.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:t,flowCollectionPadding:e.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof e.indent?" ".repeat(e.indent):" ",inFlow:s,options:e}}(s.doc);e.anchors=new Set;for(const t of s.anchors.keys())e.anchors.add(t.anchor);e.inFlow=!0,e.inStringifyKey=!0;const i=t.toString(e);if(!s.mapKeyWarned){let t=JSON.stringify(i);t.length>40&&(t=t.substring(0,36)+'..."'),r=`Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`,"debug"!==(n=s.doc.options.logLevel)&&"warn"!==n||console.warn(r),s.mapKeyWarned=!0}return i}var n,r;return JSON.stringify(e)}(s,r,t),o=gs(n,i,t);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Ws(t,e,s){const n=Es(t,void 0,s),r=Es(e,void 0,s);return new Ks(n,r)}class Ks{constructor(t,e=null){Object.defineProperty(this,Ge,{value:Ue}),this.key=t,this.value=e}clone(t){let{key:e,value:s}=this;return Je(e)&&(e=e.clone(t)),Je(s)&&(s=s.clone(t)),new Ks(e,s)}toJSON(t,e){return zs(e,e?.mapAsMap?new Map:{},this)}toString(t,e,s){return t?.doc?function({key:t,value:e},s,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:h,indentSeq:u,simpleKeys:c}}=s;let d=Je(t)&&t.comment||null;if(c){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Ye(t)||!Je(t)&&"object"==typeof t)throw new Error("With simple keys, collection cannot be used as a key value")}let f=!c&&(!t||d&&null==e&&!s.inFlow||Ye(t)||(qe(t)?t.type===ys.BLOCK_FOLDED||t.type===ys.BLOCK_LITERAL:"object"==typeof t));s=Object.assign({},s,{allNullValues:!1,implicitKey:!f&&(c||!i),indent:a+l});let g,m,p,b=!1,S=!1,y=Vs(t,s,()=>b=!0,()=>S=!0);if(!f&&!s.inFlow&&y.length>1024){if(c)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(s.inFlow){if(i||null==e)return b&&n&&n(),""===y?"?":f?`? ${y}`:y}else if(i&&!c||null==e&&f)return y=`? ${y}`,d&&!b?y+=_s(y,s.indent,h(d)):S&&r&&r(),y;b&&(d=null),f?(d&&(y+=_s(y,s.indent,h(d))),y=`? ${y}\n${a}:`):(y=`${y}:`,d&&(y+=_s(y,s.indent,h(d)))),Je(e)?(g=!!e.spaceBefore,m=e.commentBefore,p=e.comment):(g=!1,m=null,p=null,e&&"object"==typeof e&&(e=o.createNode(e))),s.implicitKey=!1,f||d||!qe(e)||(s.indentAtStart=y.length+1),S=!1,u||!(l.length>=2)||s.inFlow||f||!Qe(e)||e.flow||e.tag||e.anchor||(s.indent=s.indent.substring(2));let E=!1;const w=Vs(e,s,()=>E=!0,()=>S=!0);let C=" ";if(d||g||m)C=g?"\n":"",m&&(C+=`\n${xs(h(m),s.indent)}`),""!==w||s.inFlow?C+=`\n${s.indent}`:"\n"===C&&p&&(C="\n\n");else if(!f&&Ye(e)){const t=w[0],n=w.indexOf("\n"),r=-1!==n,i=s.inFlow??e.flow??0===e.items.length;if(r||!i){let e=!1;if(r&&("&"===t||"!"===t)){let s=w.indexOf(" ");"&"===t&&-1!==s&&s<n&&"!"===w[s+1]&&(s=w.indexOf(" ",s+1)),(-1===s||n<s)&&(e=!0)}e||(C=`\n${s.indent}`)}}else""!==w&&"\n"!==w[0]||(C="");return y+=C+w,s.inFlow?E&&n&&n():p&&!E?y+=_s(y,s.indent,h(p)):S&&r&&r(),y}(this,t,e,s):JSON.stringify(this)}}function Hs(t,e,s){return(e.inFlow??t.flow?Qs:qs)(t,e,s)}function qs({comment:t,items:e},s,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:h}}=s,u=Object.assign({},s,{indent:i,type:null});let c=!1;const d=[];for(let t=0;t<e.length;++t){const r=e[t];let o=null;if(Je(r))!c&&r.spaceBefore&&d.push(""),Ys(s,d,r.commentBefore,c),r.comment&&(o=r.comment);else if(He(r)){const t=Je(r.key)?r.key:null;t&&(!c&&t.spaceBefore&&d.push(""),Ys(s,d,t.commentBefore,c))}c=!1;let a=Vs(r,u,()=>o=null,()=>c=!0);o&&(a+=_s(a,i,h(o))),c&&o&&(c=!1),d.push(n+a)}let f;if(0===d.length)f=r.start+r.end;else{f=d[0];for(let t=1;t<d.length;++t){const e=d[t];f+=e?`\n${l}${e}`:"\n"}}return t?(f+="\n"+xs(h(t),l),a&&a()):c&&o&&o(),f}function Qs({items:t},e,{flowChars:s,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let h=!1,u=0;const c=[];for(let s=0;s<t.length;++s){const r=t[s];let i=null;if(Je(r))r.spaceBefore&&c.push(""),Ys(e,c,r.commentBefore,!1),r.comment&&(i=r.comment);else if(He(r)){const t=Je(r.key)?r.key:null;t&&(t.spaceBefore&&c.push(""),Ys(e,c,t.commentBefore,!1),t.comment&&(h=!0));const s=Je(r.value)?r.value:null;s?(s.comment&&(i=s.comment),s.commentBefore&&(h=!0)):null==r.value&&t?.comment&&(i=t.comment)}i&&(h=!0);let o=Vs(r,l,()=>i=null);s<t.length-1&&(o+=","),i&&(o+=_s(o,n,a(i))),!h&&(c.length>u||o.includes("\n"))&&(h=!0),c.push(o),u=c.length}const{start:d,end:f}=s;if(0===c.length)return d+f;if(!h){const t=c.reduce((t,e)=>t+e.length+2,2);h=e.options.lineWidth>0&&t>e.options.lineWidth}if(h){let t=d;for(const e of c)t+=e?`\n${i}${r}${e}`:"\n";return`${t}\n${r}${f}`}return`${d}${o}${c.join(" ")}${o}${f}`}function Ys({indent:t,options:{commentString:e}},s,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const r=xs(e(n),t);s.push(r.trimStart())}}function Js(t,e){const s=qe(e)?e.value:e;for(const n of t)if(He(n)){if(n.key===e||n.key===s)return n;if(qe(n.key)&&n.key.value===s)return n}}class Zs extends Cs{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ve,t),this.items=[]}static from(t,e,s){const{keepUndefined:n,replacer:r}=s,i=new this(t),o=(t,o)=>{if("function"==typeof r)o=r.call(e,t,o);else if(Array.isArray(r)&&!r.includes(t))return;(void 0!==o||n)&&i.items.push(Ws(t,o,s))};if(e instanceof Map)for(const[t,s]of e)o(t,s);else if(e&&"object"==typeof e)for(const t of Object.keys(e))o(t,e[t]);return"function"==typeof t.sortMapEntries&&i.items.sort(t.sortMapEntries),i}add(t,e){let s;s=He(t)?t:t&&"object"==typeof t&&"key"in t?new Ks(t.key,t.value):new Ks(t,t?.value);const n=Js(this.items,s.key),r=this.schema?.sortMapEntries;if(n){if(!e)throw new Error(`Key ${s.key} already set`);qe(n.value)&&Ss(s.value)?n.value.value=s.value:n.value=s.value}else if(r){const t=this.items.findIndex(t=>r(s,t)<0);-1===t?this.items.push(s):this.items.splice(t,0,s)}else this.items.push(s)}delete(t){const e=Js(this.items,t);return!!e&&this.items.splice(this.items.indexOf(e),1).length>0}get(t,e){const s=Js(this.items,t),n=s?.value;return(!e&&qe(n)?n.value:n)??void 0}has(t){return!!Js(this.items,t)}set(t,e){this.add(new Ks(t,e),!0)}toJSON(t,e,s){const n=s?new s:e?.mapAsMap?new Map:{};e?.onCreate&&e.onCreate(n);for(const t of this.items)zs(e,n,t);return n}toString(t,e,s){if(!t)return JSON.stringify(this);for(const t of this.items)if(!He(t))throw new Error(`Map items must all be pairs; found ${JSON.stringify(t)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Hs(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:s,onComment:e})}}const Xs={collection:"map",default:!0,nodeClass:Zs,tag:"tag:yaml.org,2002:map",resolve:(t,e)=>(Ke(t)||e("Expected a mapping for this tag"),t),createNode:(t,e,s)=>Zs.from(t,e,s)};class tn extends Cs{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(je,t),this.items=[]}add(t){this.items.push(t)}delete(t){const e=en(t);return"number"==typeof e&&this.items.splice(e,1).length>0}get(t,e){const s=en(t);if("number"!=typeof s)return;const n=this.items[s];return!e&&qe(n)?n.value:n}has(t){const e=en(t);return"number"==typeof e&&e<this.items.length}set(t,e){const s=en(t);if("number"!=typeof s)throw new Error(`Expected a valid index, not ${t}.`);const n=this.items[s];qe(n)&&Ss(e)?n.value=e:this.items[s]=e}toJSON(t,e){const s=[];e?.onCreate&&e.onCreate(s);let n=0;for(const t of this.items)s.push(gs(t,String(n++),e));return s}toString(t,e,s){return t?Hs(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:s,onComment:e}):JSON.stringify(this)}static from(t,e,s){const{replacer:n}=s,r=new this(t);if(e&&Symbol.iterator in Object(e)){let t=0;for(let i of e){if("function"==typeof n){const s=e instanceof Set?i:String(t++);i=n.call(e,s,i)}r.items.push(Es(i,void 0,s))}}return r}}function en(t){let e=qe(t)?t.value:t;return e&&"string"==typeof e&&(e=Number(e)),"number"==typeof e&&Number.isInteger(e)&&e>=0?e:null}const sn={collection:"seq",default:!0,nodeClass:tn,tag:"tag:yaml.org,2002:seq",resolve:(t,e)=>(Qe(t)||e("Expected a sequence for this tag"),t),createNode:(t,e,s)=>tn.from(t,e,s)},nn={identify:t=>"string"==typeof t,default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:(t,e,s,n)=>Ds(t,e=Object.assign({actualString:!0},e),s,n)},rn={identify:t=>null==t,createNode:()=>new ys(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ys(null),stringify:({source:t},e)=>"string"==typeof t&&rn.test.test(t)?t:e.options.nullStr},on={identify:t=>"boolean"==typeof t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new ys("t"===t[0]||"T"===t[0]),stringify:({source:t,value:e},s)=>t&&on.test.test(t)&&e===("t"===t[0]||"T"===t[0])?t:e?s.options.trueStr:s.options.falseStr};function an({format:t,minFractionDigits:e,tag:s,value:n}){if("bigint"==typeof n)return String(n);const r="number"==typeof n?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!t&&e&&(!s||"tag:yaml.org,2002:float"===s)&&/^\d/.test(i)){let t=i.indexOf(".");t<0&&(t=i.length,i+=".");let s=e-(i.length-t-1);for(;s-- >0;)i+="0"}return i}const ln={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>"nan"===t.slice(-3).toLowerCase()?NaN:"-"===t[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:an},hn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){const e=Number(t.value);return isFinite(e)?e.toExponential():an(t)}},un=t=>"bigint"==typeof t||Number.isInteger(t),cn=(t,e,s,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),s);function dn(t,e,s){const{value:n}=t;return un(n)&&n>=0?s+n.toString(e):an(t)}const fn=[Xs,sn,nn,rn,on,{identify:t=>un(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,s)=>cn(t,2,8,s),stringify:t=>dn(t,8,"0o")},{identify:un,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,s)=>cn(t,0,10,s),stringify:an},{identify:t=>un(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,s)=>cn(t,2,16,s),stringify:t=>dn(t,16,"0x")},ln,hn,{identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){const e=new ys(parseFloat(t)),s=t.indexOf(".");return-1!==s&&"0"===t[t.length-1]&&(e.minFractionDigits=t.length-s-1),e},stringify:an}];function gn(t){return"bigint"==typeof t||Number.isInteger(t)}const mn=({value:t})=>JSON.stringify(t),pn=[Xs,sn].concat([{identify:t=>"string"==typeof t,default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:mn},{identify:t=>null==t,createNode:()=>new ys(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:mn},{identify:t=>"boolean"==typeof t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>"true"===t,stringify:mn},{identify:gn,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:s})=>s?BigInt(t):parseInt(t,10),stringify:({value:t})=>gn(t)?t.toString():JSON.stringify(t)},{identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:mn}],{default:!0,tag:"",test:/^/,resolve:(t,e)=>(e(`Unresolved plain scalar ${JSON.stringify(t)}`),t)}),bn={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if("function"==typeof atob){const e=atob(t.replace(/[\n\r]/g,"")),s=new Uint8Array(e.length);for(let t=0;t<e.length;++t)s[t]=e.charCodeAt(t);return s}return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:s},n,r,i){if(!s)return"";const o=s;let a;if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let t="";for(let e=0;e<o.length;++e)t+=String.fromCharCode(o[e]);a=btoa(t)}if(e??(e=ys.BLOCK_LITERAL),e!==ys.QUOTE_DOUBLE){const t=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),s=Math.ceil(a.length/t),r=new Array(s);for(let e=0,n=0;e<s;++e,n+=t)r[e]=a.substr(n,t);a=r.join(e===ys.BLOCK_LITERAL?"\n":" ")}return Ds({comment:t,type:e,value:a},n,r,i)}};function Sn(t,e){if(Qe(t))for(let s=0;s<t.items.length;++s){let n=t.items[s];if(!He(n)){if(Ke(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const t=n.items[0]||new Ks(new ys(null));if(n.commentBefore&&(t.key.commentBefore=t.key.commentBefore?`${n.commentBefore}\n${t.key.commentBefore}`:n.commentBefore),n.comment){const e=t.value??t.key;e.comment=e.comment?`${n.comment}\n${e.comment}`:n.comment}n=t}t.items[s]=He(n)?n:new Ks(n)}}else e("Expected a sequence for this tag");return t}function yn(t,e,s){const{replacer:n}=s,r=new tn(t);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let t of e){let o,a;if("function"==typeof n&&(t=n.call(e,String(i++),t)),Array.isArray(t)){if(2!==t.length)throw new TypeError(`Expected [key, value] tuple: ${t}`);o=t[0],a=t[1]}else if(t&&t instanceof Object){const e=Object.keys(t);if(1!==e.length)throw new TypeError(`Expected tuple with one key, not ${e.length} keys`);o=e[0],a=t[o]}else o=t;r.items.push(Ws(o,a,s))}return r}const En={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Sn,createNode:yn};class wn extends tn{constructor(){super(),this.add=Zs.prototype.add.bind(this),this.delete=Zs.prototype.delete.bind(this),this.get=Zs.prototype.get.bind(this),this.has=Zs.prototype.has.bind(this),this.set=Zs.prototype.set.bind(this),this.tag=wn.tag}toJSON(t,e){if(!e)return super.toJSON(t);const s=new Map;e?.onCreate&&e.onCreate(s);for(const t of this.items){let n,r;if(He(t)?(n=gs(t.key,"",e),r=gs(t.value,n,e)):n=gs(t,"",e),s.has(n))throw new Error("Ordered maps must not include duplicate keys");s.set(n,r)}return s}static from(t,e,s){const n=yn(t,e,s),r=new this;return r.items=n.items,r}}wn.tag="tag:yaml.org,2002:omap";const Cn={collection:"seq",identify:t=>t instanceof Map,nodeClass:wn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){const s=Sn(t,e),n=[];for(const{key:t}of s.items)qe(t)&&(n.includes(t.value)?e(`Ordered maps must not include duplicate keys: ${t.value}`):n.push(t.value));return Object.assign(new wn,s)},createNode:(t,e,s)=>wn.from(t,e,s)};function vn({value:t,source:e},s){return e&&(t?xn:_n).test.test(e)?e:t?s.options.trueStr:s.options.falseStr}const xn={identify:t=>!0===t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ys(!0),stringify:vn},_n={identify:t=>!1===t,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ys(!1),stringify:vn},An={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>"nan"===t.slice(-3).toLowerCase()?NaN:"-"===t[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:an},Nn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){const e=Number(t.value);return isFinite(e)?e.toExponential():an(t)}},Tn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){const e=new ys(parseFloat(t.replace(/_/g,""))),s=t.indexOf(".");if(-1!==s){const n=t.substring(s+1).replace(/_/g,"");"0"===n[n.length-1]&&(e.minFractionDigits=n.length)}return e},stringify:an},In=t=>"bigint"==typeof t||Number.isInteger(t);function On(t,e,s,{intAsBigInt:n}){const r=t[0];if("-"!==r&&"+"!==r||(e+=1),t=t.substring(e).replace(/_/g,""),n){switch(s){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`}const e=BigInt(t);return"-"===r?BigInt(-1)*e:e}const i=parseInt(t,s);return"-"===r?-1*i:i}function Rn(t,e,s){const{value:n}=t;if(In(n)){const t=n.toString(e);return n<0?"-"+s+t.substr(1):s+t}return an(t)}const kn={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,s)=>On(t,2,2,s),stringify:t=>Rn(t,2,"0b")},Ln={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,s)=>On(t,1,8,s),stringify:t=>Rn(t,8,"0")},Mn={identify:In,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,s)=>On(t,0,10,s),stringify:an},Pn={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,s)=>On(t,2,16,s),stringify:t=>Rn(t,16,"0x")};class Bn extends Zs{constructor(t){super(t),this.tag=Bn.tag}add(t){let e;e=He(t)?t:t&&"object"==typeof t&&"key"in t&&"value"in t&&null===t.value?new Ks(t.key,null):new Ks(t,null),Js(this.items,e.key)||this.items.push(e)}get(t,e){const s=Js(this.items,t);return!e&&He(s)?qe(s.key)?s.key.value:s.key:s}set(t,e){if("boolean"!=typeof e)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof e);const s=Js(this.items,t);s&&!e?this.items.splice(this.items.indexOf(s),1):!s&&e&&this.items.push(new Ks(t))}toJSON(t,e){return super.toJSON(t,e,Set)}toString(t,e,s){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),e,s);throw new Error("Set items must all have null values")}static from(t,e,s){const{replacer:n}=s,r=new this(t);if(e&&Symbol.iterator in Object(e))for(let t of e)"function"==typeof n&&(t=n.call(e,t,t)),r.items.push(Ws(t,null,s));return r}}Bn.tag="tag:yaml.org,2002:set";const $n={collection:"map",identify:t=>t instanceof Set,nodeClass:Bn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,s)=>Bn.from(t,e,s),resolve(t,e){if(Ke(t)){if(t.hasAllNullValues(!0))return Object.assign(new Bn,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};function Dn(t,e){const s=t[0],n="-"===s||"+"===s?t.substring(1):t,r=t=>e?BigInt(t):Number(t),i=n.replace(/_/g,"").split(":").reduce((t,e)=>t*r(60)+r(e),r(0));return"-"===s?r(-1)*i:i}function Vn(t){let{value:e}=t,s=t=>t;if("bigint"==typeof e)s=t=>BigInt(t);else if(isNaN(e)||!isFinite(e))return an(t);let n="";e<0&&(n="-",e*=s(-1));const r=s(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(t=>String(t).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}const Un={identify:t=>"bigint"==typeof t||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:s})=>Dn(t,s),stringify:Vn},Fn={identify:t=>"number"==typeof t,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Dn(t,!1),stringify:Vn},jn={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){const e=t.match(jn.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,s,n,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let h=Date.UTC(s,n-1,r,i||0,o||0,a||0,l);const u=e[8];if(u&&"Z"!==u){let t=Dn(u,!1);Math.abs(t)<30&&(t*=60),h-=6e4*t}return new Date(h)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""},Gn=[Xs,sn,nn,rn,xn,_n,kn,Ln,Mn,Pn,An,Nn,Tn,bn,Fs,Cn,En,$n,Un,Fn,jn];new Map([["core",fn],["failsafe",[Xs,sn,nn]],["json",pn],["yaml11",Gn],["yaml-1.1",Gn]]),Error;const zn=Symbol("break visit"),Wn=Symbol("skip children"),Kn=Symbol("remove item");function Hn(t,e){"type"in t&&"document"===t.type&&(t={start:t.start,value:t.value}),qn(Object.freeze([]),t,e)}function qn(t,e,s){let n=s(e,t);if("symbol"==typeof n)return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let e=0;e<i.items.length;++e){const n=qn(Object.freeze(t.concat([[r,e]])),i.items[e],s);if("number"==typeof n)e=n-1;else{if(n===zn)return zn;n===Kn&&(i.items.splice(e,1),e-=1)}}"function"==typeof n&&"key"===r&&(n=n(e,t))}}return"function"==typeof n?n(e,t):n}var Qn;Hn.BREAK=zn,Hn.SKIP=Wn,Hn.REMOVE=Kn,Hn.itemAtPath=(t,e)=>{let s=t;for(const[t,n]of e){const e=s?.[t];if(!e||!("items"in e))return;s=e.items[n]}return s},Hn.parentCollection=(t,e)=>{const s=Hn.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],r=s?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")},new Set("0123456789ABCDEFabcdef"),new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),new Set(",[]{}"),new Set(" ,[]{}\n\r\t"),E.ONE,function(t){t.Kampitham="Kampitham",t.Nokku="Nokku",t.Spuritham="Spuritham",t.Prathyagatham="Prathyagatham",t.Aahaatam_Raavi="Raavi",t.Aahaatam_Kandippu="Kandippu",t.Vaali="Vaali",t.Odukkal="Odukkal",t.Jaaru_Eetra="EetraJaaru",t.Jaaru_Irakka="IrakkaJaaru",t.Orikkai="Orikkai"}(Qn||(Qn={}));class Yn{constructor(){this.shapeId=Yn.idCounter++,this._x=null,this._y=null,this._width=null,this._height=null,this.parentShape=null,this.children=[]}get bbox(){return this._bbox||(this._bbox=this.refreshBBox()),this._bbox}get minSize(){return this._minSize||(this._minSize=this.refreshMinSize()),this._minSize}invalidateBounds(){this._minSize=null,this._bbox=null}setBounds(t,e,s,n,r=!1){null!=t&&(isNaN(t)?this._x=null:this._x=t),null!=e&&(isNaN(e)?this._y=null:this._y=e),null!=s&&(isNaN(s)?this._width=null:this._width=s),null!=n&&(isNaN(n)?this._height=null:this._height=n);const[i,o,a,l]=this.updateBounds(t,e,s,n);return null!=i&&(isNaN(i)?this._x=null:this._x=i),null!=o&&(isNaN(o)?this._y=null:this._y=o),null!=a&&(isNaN(a)?this._width=null:this._width=a),null!=l&&(isNaN(l)?this._height=null:this._height=l),r&&this.refreshLayout(),[i,o,a,l]}get hasX(){return null!=this._x&&!isNaN(this._x)}get hasY(){return null!=this._y&&!isNaN(this._y)}get hasWidth(){return null!=this._width&&!isNaN(this._width)}get hasHeight(){return null!=this._height&&!isNaN(this._height)}get x(){return this._x||0}set x(t){this.setBounds(null==t?NaN:t,null,null,null)}get y(){return null!=this._y?this._y:0}set y(t){this.setBounds(null,null==t?NaN:t,null,null)}get width(){return null!=this._width?this._width:0}set width(t){this.setBounds(null,null,null==t?NaN:t,null)}get height(){return null!=this._height?this._height:0}set height(t){this.setBounds(null,null,null,null==t?NaN:t)}refreshLayout(){}}Yn.idCounter=0;class Jn extends Yn{}class Zn extends Yn{constructor(t){super(),this.element=t}refreshBBox(){return b(this.element)}refreshMinSize(){return b(this.element)}updateBounds(t,e,s,n){return[t,e,s,n]}refreshLayout(){this.hasX&&this.element.setAttribute("x",""+this._x),this.hasY&&this.element.setAttribute("y",""+this._y)}}class Xn extends Yn{constructor(){super(...arguments),this.depth=0,this.roleIndex=0}get glyphOffset(){return 0}}class tr extends Xn{constructor(t){super(),this.leafAtom=t}isLeaf(){return!0}get viewId(){return this.leafAtom.uuid}get totalDuration(){return this.leafAtom.duration}}class er extends Xn{constructor(t,e){super(),this.group=t,this.atomViews=[],this.defaultToNotes=!0,this.needsLayout=!0,this.scaleFactor=1,this.showContinuationMarkers=!1,this.continuationMarkerElements=[],this.contentWidth=0,this.atomSpacing=2,this.setStyles(e||{})}get totalDuration(){return this.group.duration}createElements(t){this.groupElement=S("g",{parent:t,attrs:{class:"groupViewRoot",id:"groupViewRoot"+this.group.uuid}});for(const t of this.group.atoms.values()){const e=this.createAtomView(t);this.atomViews.push(e)}this.invalidateBounds()}isLeaf(){return!1}refreshBBox(){return b(this.groupElement)}refreshMinSize(){let t=0,e=0;this.atomViews.forEach(s=>{const n=s.minSize,r=s.totalDuration;if(!r.isZero){const t=r.num/r.den,s=(n.width+this.atomSpacing)/t;e=Math.max(e,s)}t=Math.max(t,n.height)});const s=this.group.totalChildDuration,n=s.num/s.den,r=Math.max(0,e*n-this.atomSpacing);return new g(r*this.scaleFactor,t*this.scaleFactor)}updateBounds(t,e,s,n){return[t,e,s,n]}refreshLayout(){let t="translate("+this.x+","+this.y+")";this.scaleFactor<1&&(t+=" scale("+this.scaleFactor+")"),this.groupElement.setAttribute("transform",t);const e=this.minSize.height/this.scaleFactor,s=(this.hasHeight?this.height/this.scaleFactor:e)-e,n=this.group.totalChildDuration,r=this.minSize.width/this.scaleFactor,i=this.hasWidth?this.width/this.scaleFactor:r;this.clearContinuationMarkers();let o=A,a=0;this.atomViews.forEach((t,e)=>{let r=(n.isZero?0:o.timesNum(i).divby(n).floor)-t.glyphOffset;r<a&&(r=a),t.setBounds(r,s,null,null,!0);const l=t.contentWidth||t.bbox.width;if(a=r+l,this.showContinuationMarkers&&!n.isZero){const e=t.totalDuration,r=e.num/e.den;if(r>1){const t=Math.floor(r)-1;for(let a=1;a<=t;a++){const t=o.plus(e.timesNum(a).divbyNum(Math.floor(r))).timesNum(i).divby(n).floor;this.renderContinuationMarker(t,s)}}}o=o.plus(t.totalDuration)}),this.contentWidth=a,this.invalidateBounds();for(const t of this.embelishments)t.refreshLayout();this.invalidateBounds()}clearContinuationMarkers(){for(const t of this.continuationMarkerElements)t.remove();this.continuationMarkerElements=[]}renderContinuationMarker(t,e){const s=S("text",{parent:this.groupElement,attrs:{class:"continuationMarker",x:t.toString(),y:e.toString()},text:","});this.continuationMarkerElements.push(s)}get embelishments(){return this._embelishments||(this._embelishments=this.createEmbelishments()),this._embelishments}createEmbelishments(){return[]}setStyles(t){"atomSpacing"in t&&(this.atomSpacing=t.atomSpacing),"showContinuationMarkers"in t&&(this.showContinuationMarkers=t.showContinuationMarkers),this.needsLayout=!0}}class sr extends Jn{constructor(t){super(),this.atomView=t}}class nr extends sr{constructor(t,e){super(t),this.noteView=t,this.note=e,this.dotRadius=1,this.dotSpacing=2.5;const s=this.noteView.embRoot(),n=Math.abs(e.octave);this.dotsElem=S("g",{doc:document,parent:s,attrs:{width:2*this.dotRadius*n+(n-1)*this.dotSpacing,height:2*this.dotRadius,source:"atom"+this.noteView.leafAtom.uuid}});let r=0;for(let t=0;t<n;t++)S("circle",{doc:document,parent:this.dotsElem,attrs:{cx:r,cy:0,r:this.dotRadius,class:"notation-octave-dot"}}),r+=this.dotRadius+this.dotRadius+this.dotSpacing}refreshBBox(){return b(this.dotsElem)}refreshMinSize(){const t=Math.abs(this.note.octave);return{width:2*this.dotRadius*t+(t-1)*this.dotSpacing,height:2*this.dotRadius}}updateBounds(t,e,s,n){return null==t&&(t=this.x),null==e&&(e=this.y),[t,e,null,null]}refreshLayout(){this.dotsElem.setAttribute("transform","translate("+this.x+","+this.y+")")}}class rr extends sr{constructor(t,e){super(e),this.label=t,this.atomView=e;const s=this.atomView.embRoot();this.labelElem=S("text",{doc:document,parent:s,text:t,attrs:{source:"atom"+this.atomView.leafAtom.uuid,class:"notation-embelishment-label","dominant-baseline":"hanging"}})}refreshBBox(){return b(this.labelElem)}refreshMinSize(){return b(this.labelElem)}updateBounds(t,e,s,n){return[t,e,s,n]}refreshLayout(){this.labelElem.setAttribute("x",""+this.x),this.labelElem.setAttribute("y",""+this.y)}}class ir extends rr{constructor(t){super("~",t),this.atomView=t}}class or extends rr{constructor(t){super("w",t),this.atomView=t}}class ar extends rr{constructor(t){super("∵",t),this.atomView=t}}class lr extends rr{constructor(t){super("∴",t),this.atomView=t}}class hr extends rr{constructor(t){super("^",t),this.atomView=t}}class ur extends rr{constructor(t){super("✓",t),this.atomView=t}}class cr extends rr{constructor(t){super("⌒",t),this.atomView=t}}class dr extends rr{constructor(t){super("x",t),this.atomView=t}}class fr extends rr{constructor(t){super("γ",t),this.atomView=t}}class gr extends sr{constructor(t,e){super(e),this.jaaru=t,this.atomView=e;const s=this.atomView.embRoot();this.pathElem=S("path",{doc:document,parent:s,attrs:{source:"atom"+this.atomView.leafAtom.uuid,class:"notation-jaaru-path",d:this.pathAttribute()}})}pathAttribute(t=0){const e=this.atomView.glyph.minSize;let s=0;const n=e.height/2,r=t+n;let i=this.atomView.y;return this.jaaru.ascending?(i+=e.height,s=i-n):(i-=n,s=i+n),[`M ${t} ${i}`,`Q ${r} ${i} ${r} ${s}`].join(" ")}refreshMinSize(){return b(this.pathElem)}refreshBBox(){return b(this.pathElem)}updateBounds(t,e,s,n){return[t,null,null,null]}refreshLayout(){this.pathElem.setAttribute("d",this.pathAttribute(this.x))}}class mr extends Jn{constructor(t){super(),this.groupView=t,this.line=null,this.leftCircle=null,this.rightCircle=null,this.bracketGroup=null,this.lineOffset=2,this.circleRadius=1.5,this.lineExtension=2,this.positionMode="below-embellishments",this.bracketGroup=S("g",{doc:document,parent:this.groupView.groupElement,attrs:{class:"group-bracket",source:"group"+this.groupView.group.uuid}}),this.line=S("line",{doc:document,parent:this.bracketGroup,attrs:{class:"group-bracket-line"}}),this.leftCircle=S("circle",{doc:document,parent:this.bracketGroup,attrs:{class:"group-bracket-circle",r:String(this.circleRadius)}}),this.rightCircle=S("circle",{doc:document,parent:this.bracketGroup,attrs:{class:"group-bracket-circle",r:String(this.circleRadius)}})}refreshBBox(){return this.bracketGroup?b(this.bracketGroup):new m(0,0,0,0)}refreshMinSize(){return new g(0,this.lineOffset+this.circleRadius)}updateBounds(t,e,s,n){return[t,e,s,n]}refreshLayout(){if(!this.line||!this.leftCircle||!this.rightCircle)return;const t=this.groupView.bbox,e=this.groupView.contentWidth||t.width;let s;s="below-embellishments"===this.positionMode?t.y+this.lineOffset-2:t.y-this.lineOffset;const n=-this.lineExtension,r=e+this.lineExtension;this.line.setAttribute("x1",String(n)),this.line.setAttribute("y1",String(s)),this.line.setAttribute("x2",String(r)),this.line.setAttribute("y2",String(s)),this.leftCircle.setAttribute("cx",String(n)),this.leftCircle.setAttribute("cy",String(s)),this.rightCircle.setAttribute("cx",String(r)),this.rightCircle.setAttribute("cy",String(s))}}class pr extends er{createAtomView(t){return function(t,e,s=!1,n=1,r=0){let i;switch(e.TYPE){case T.SPACE:i=new Sr(e);break;case T.SYLLABLE:i=new Er(e);break;case T.NOTE:i=new yr(e);break;case T.LITERAL:if(s){const t=B.fromLit(e);i=new yr(t)}else{const t=P.fromLit(e);i=new Er(t)}break;case T.GROUP:i=new pr(e),i.defaultToNotes=s,i.scaleFactor=n;break;default:throw new Error("Invalid atom type: "+e.TYPE)}return i.depth=r,i.createElements(t),i}(this.groupElement,t,this.defaultToNotes,.7,this.depth+1)}createEmbelishments(){const t=super.createEmbelishments();return this.depth>=1&&t.push(new mr(this)),t}refreshMinSize(){const t=super.refreshMinSize();return this.depth>=1?new g(t.width,t.height+pr.BRACKET_HEIGHT*this.scaleFactor):t}}pr.BRACKET_HEIGHT=8;class br extends tr{constructor(){super(...arguments),this.leftSlot=[],this.topSlot=[],this.rightSlot=[],this.bottomSlot=[]}refreshBBox(){return b(this.rootGroup.element)}refreshMinSize(){const t=Object.assign({},this.rootText.minSize),e=this.leftSlot.reduce((t,e)=>t+e.minSize.width,0)+this.rightSlot.reduce((t,e)=>t+e.minSize.width,0)+this.leftSlot.length+this.rightSlot.length,s=this.topSlot.reduce((t,e)=>t+e.minSize.height,0)+this.bottomSlot.reduce((t,e)=>t+e.minSize.height,0);return t.width+=e,t.height+=s,t}get glyphOffset(){return this.leftSlot.reduce((t,e)=>t+e.minSize.width,0)+this.leftSlot.length}updateBounds(t,e,s,n){return[t,e,NaN,NaN]}layoutElements(){this.rootText.minSize;let t=0,e=this.hasY?this.y:0;for(const e of this.leftSlot)e.x=t,e.refreshLayout(),t+=e.minSize.width+1;const s=t;this.rootText.x=t,this.rootText.refreshLayout(),t+=this.rootText.minSize.width;for(const e of this.rightSlot)e.x=t,e.refreshLayout(),t+=e.minSize.width+1;const n=this.glyph.minSize,r=s+this.glyph.x,i=this.glyph.y;e=i-this.glyph.minSize.height+5;for(const t of this.topSlot){const s=t.minSize;t.setBounds(r+(n.width-s.width)/2,e-s.height,null,null,!0),e=t.y}e=i+7;for(const t of this.bottomSlot){const s=t.minSize;t.setBounds(r+(n.width-s.width)/2,e,null,null,!0),e=t.y+s.height}this.invalidateBounds()}refreshLayout(){this.layoutElements(),this.rootGroup.element.setAttribute("transform","translate("+this.x+","+this.y+")")}addEmbelishment(t,e){t.push(e)}orderEmbelishments(){const t=this.leafAtom;if(t.TYPE!=T.SYLLABLE&&t.TYPE!=T.NOTE)return;const e=t;if(0!=e.embelishments.length)for(const t of e.embelishments)switch(t.type){case Qn.Kampitham:this.addEmbelishment(this.topSlot,new ir(this));break;case Qn.Nokku:this.addEmbelishment(this.topSlot,new or(this));break;case Qn.Spuritham:this.addEmbelishment(this.topSlot,new lr(this));break;case Qn.Prathyagatham:this.addEmbelishment(this.topSlot,new ar(this));break;case Qn.Orikkai:this.addEmbelishment(this.topSlot,new fr(this));break;case Qn.Odukkal:this.addEmbelishment(this.topSlot,new dr(this));break;case Qn.Aahaatam_Raavi:this.addEmbelishment(this.topSlot,new hr(this));break;case Qn.Aahaatam_Kandippu:this.addEmbelishment(this.topSlot,new ur(this));break;case Qn.Vaali:this.addEmbelishment(this.topSlot,new cr(this));break;case Qn.Jaaru_Eetra:case Qn.Jaaru_Irakka:this.addEmbelishment(this.leftSlot,new gr(t,this))}}embRoot(){return this.rootGroup.element}needsRootElement(){return!0}createElements(t){this.createGlyphRoot(t),this.createGlyphElement(),this.orderEmbelishments(),this.createPostSpacingElement(),this.invalidateBounds()}createGlyphRoot(t){this.rootGroup=new Zn(S("g",{doc:document,parent:t,attrs:{atomid:this.leafAtom.uuid,class:"atomViewRootGroup",id:"atomViewRootGroup"+this.leafAtom.uuid}})),this.rootText=new Zn(S("text",{doc:document,parent:this.rootGroup.element,attrs:{atomid:this.leafAtom.uuid,class:"atomViewTextRoot",id:"atomViewTextRoot"+this.leafAtom.uuid}}))}createGlyphElement(){const t=this.leafAtom;this.glyph=new Zn(S("tspan",{doc:document,parent:this.rootText.element,attrs:{atomid:t.uuid,id:"atomGlyph"+t.uuid},text:this.glyphLabel}))}createPostSpacingElement(){this.leafAtom.beforeRest&&(this.postSpacingSpan=S("tspan",{doc:document,parent:this.rootText.element,attrs:{atomid:this.leafAtom.uuid,id:"postSpacing"+this.leafAtom.uuid},text:this.leafAtom.beforeRest?" - ":" "}))}}class Sr extends br{get glyphLabel(){return this.space.isSilent?" ":this.space.duration.isOne?",":0==this.space.duration.cmpNum(2)?";":"_"}get space(){return this.leafAtom}}class yr extends br{get glyphLabel(){return this.note.value}needsRootElement(){return!0}createGlyphElement(){super.createGlyphElement(),1!=this.note.shift&&0==this.note.shift||(this.shiftElement=S("tspan",{doc:document,parent:this.rootText.element,attrs:{atomid:this.note.uuid,class:"noteShiftTSpan",id:"noteShift"+this.note.uuid,"baseline-shift":"sub"},text:(1==this.note.shift?"*":this.note.shift)+" "}))}moveGlyphToRoot(){this.shiftElement&&this.rootGroup.element.appendChild(this.shiftElement)}orderEmbelishments(){const t=this.note;t.octave>0?this.topSlot.push(new nr(this,t)):this.note.octave<0&&this.bottomSlot.push(new nr(this,t)),super.orderEmbelishments()}get note(){return this.leafAtom}}class Er extends br{get glyphLabel(){return this.syllable.value}get syllable(){return this.leafAtom}}const wr=E.ONE,[Cr]=(wr.timesNum(2),function(t,e=null){const s=e||{},[n,r,i]=function(t,e=null){const s=e||{},[n,r]=function(t,e){const s=new ot((e=e||{}).grammar||{}),n=new Se(t,{...e,grammar:s}),r=n.generatedTokenizer.next.bind(n.generatedTokenizer);return(e.debug||"").split("|").findIndex(t=>"all"==t||"lexer"==t)>=0&&console.log("Prog: \n",`${n.generatedTokenizer.vm.prog.debugValue().join("\n")}`),[s,r]}(t,s);n.augmentStartSymbol();const[i,o]=function(t,e="lr1"){switch(e){case"lr1":return function(t){const e=new ke(t).refresh();return[Pe(e,t),e]}(t);case"lalr":return function(t){const[e,s]=Le(t);if(!e.hasConflicts)return[e,s];const n=function(t,e){const s=new ot;function n(t,n){const r=`[${t}:${n.label}]`,i=s.ensureSym(new st(s,r,n.isTerminal),!1);return 0!=t||e.startSymbol!=n||e.startSymbol==i||n.isTerminal||(s.startSymbol=i),i}for(const s in t.gotoSets){const r=t.gotoSets[s];for(const t in r)n(s,e.getSymById(t))}function r(e,s,r){let i=e;const o=r.rhs.syms.map((e,s)=>{const r=n(i,e),o=t.gotoSets[i][e.id]||null;return a(null!=o,"Next set transition *must* be valid"),i=o.id,r});return new nt(...o)}for(const i in t.gotoSets){const o=t.gotoSets[i];for(const t in o){const o=e.getSymById(t),a=i;if(!o.isTerminal){const t=n(a,o);e.forEachRule(o,(e,n)=>{const i=r(a,0,e),o=new it(t,i);s.addRule(o)})}}}return s}(s,t),r={};for(const t in s.gotoSets)for(const e in s.gotoSets[t]){const n=s.gotoSets[t][e];n.id in r||(r[n.id]={}),e in r[n.id]||(r[n.id][e]=new Set),r[n.id][e].add(t)}for(const i in e.conflictActions){const e=s.itemSets.get(i);Be(t,n,s,e,r)}return[Pe(s,t),s]}(t)}return Le(t)}(n,s.type);return[i,r,o]}(t,s),o=new Ne(n);return(s.tokenizer||r)&&o.setTokenizer(s.tokenizer||r),(s.debug||"").split("|").findIndex(t=>"all"==t||"parser"==t)>=0&&function(t,e){const s=t.grammar,n=t.parseTable;console.log("===============================\nGrammar (as default): \n",s.debugValue.map((t,e)=>`${e+1} - ${t}`),"===============================\nGrammar (as Bison): \n",s.debugValue.map((t,e)=>`${t.replace("->",":")} ; \n`).join(""),"===============================\nParseTable: \n",JSON.stringify(function(t,e){const s={},n=t.debugValue,r=e?.debugValue;for(const t in n){const i=n[t];if(e){const e=r[t];s[t]={items:e.items,actions:i,goto:e.goto}}else s[t]=i}return s}(n,e),null,4),"===============================\nConflicts: \n",n.conflictActions)}(o,i),[o,r,i]}(String.raw`
2
2
  %define IdentChar /[^%!@$#&\^|\[\]={}()<>+\-,;~: \t\f\r\n\v\\\.\'\"]/
3
3
 
4
4
  %token BSLASH "\\"
@@ -112,5 +112,5 @@
112
112
 
113
113
  Duration -> Fraction | NUMBER;
114
114
  Fraction -> NUMBER SLASH NUMBER { newFraction } ;
115
- `,{debug:"",type:"lalr",leftRecursive:!0,tokenHandlers:{toEmbelishment:(t,e,s)=>{const[n,r]=s.parseEmbelishment(t.value);return null==n?(console.log("Skipping Embelishment: ",t.value),s.errors.push(new jt(`Invalid embelishment: ${t.value}`,t.start,1+t.end-t.start,"InvalidEmbelishment",t.value)),null):(t.value=n,t.tag=r?"PRE_EMB":"POST_EMB",t)},toCommandName:(t,e,s)=>(t.value=t.value.substring(1),t),toBoolean:(t,e,s)=>(t.value="true"==t.value,t),toNumber:(t,e,s)=>(t.value=parseInt(t.value),t),toString:(t,e,s)=>(t.value=t.value.substring(1,t.value.length-1),t),toMarker:(t,e,s)=>{if("PRE_MARKER"!=t.tag&&"POST_MARKER"!=t.tag)throw new Error("Invalid token for converting to note: "+t.tag);const n="PRE_MARKER"==t.tag,r=n?t.value.substring(1,t.value.length-3):t.value.substring(3,t.value.length-1);return t.value=new T(r,n),t},toOctavedNote:(t,e,s)=>{if("DOTS_IDENT"==t.tag){const e=t.positions[1][1]-t.positions[1][0],s=t.value.substring(e);t.value=new R(s,Kn,-e)}else{if("IDENT_DOTS"!=t.tag)throw new Error("Invalid token for converting to note: "+t.tag);{const e=t.positions[2][1]-t.positions[2][0],s=t.value.substring(0,t.value.length-e);t.value=new R(s,Kn,e)}}return t},toRoleSelector:(t,e,s)=>(t.value=t.value.substring(0,t.value.length-1),t),toLineAnnotation:(t,e,s)=>(t.value=t.value.substring(1),t),toSingleLineRawString:(t,e,s)=>(t.value=t.value.substring(1),t),toMultiLineRawString:(t,e,s)=>{const n='"'+e.substring(t.positions[1][0],t.positions[1][1]),r=e.index,i=Wt.advanceAfter(e,n)-n.length;if(i<0)throw new Error("EOF expected while finding end of Raw String Literal: '"+n+"'");return t.value=e.substring(r,i),t},toFrontMatter:(t,e,s)=>{const n=e.index,r=Wt.advanceAfter(e,"\n---")-4;if(r<0)throw new Error("EOF expected while finding end of front matter");return t.value=e.substring(n,r),t}}}));return r.default})());
115
+ `,{debug:"",type:"lalr",leftRecursive:!0,tokenHandlers:{toEmbelishment:(t,e,s)=>{const[n,r]=s.parseEmbelishment(t.value);return null==n?(console.log("Skipping Embelishment: ",t.value),s.errors.push(new Kt(`Invalid embelishment: ${t.value}`,t.start,1+t.end-t.start,"InvalidEmbelishment",t.value)),null):(t.value=n,t.tag=r?"PRE_EMB":"POST_EMB",t)},toCommandName:(t,e,s)=>(t.value=t.value.substring(1),t),toBoolean:(t,e,s)=>(t.value="true"==t.value,t),toNumber:(t,e,s)=>(t.value=parseInt(t.value),t),toString:(t,e,s)=>(t.value=t.value.substring(1,t.value.length-1),t),toMarker:(t,e,s)=>{if("PRE_MARKER"!=t.tag&&"POST_MARKER"!=t.tag)throw new Error("Invalid token for converting to note: "+t.tag);const n="PRE_MARKER"==t.tag,r=n?t.value.substring(1,t.value.length-3):t.value.substring(3,t.value.length-1);return t.value=new k(r,n),t},toOctavedNote:(t,e,s)=>{if("DOTS_IDENT"==t.tag){const e=t.positions[1][1]-t.positions[1][0],s=t.value.substring(e);t.value=new B(s,wr,-e)}else{if("IDENT_DOTS"!=t.tag)throw new Error("Invalid token for converting to note: "+t.tag);{const e=t.positions[2][1]-t.positions[2][0],s=t.value.substring(0,t.value.length-e);t.value=new B(s,wr,e)}}return t},toRoleSelector:(t,e,s)=>(t.value=t.value.substring(0,t.value.length-1),t),toLineAnnotation:(t,e,s)=>(t.value=t.value.substring(1),t),toSingleLineRawString:(t,e,s)=>(t.value=t.value.substring(1),t),toMultiLineRawString:(t,e,s)=>{const n='"'+e.substring(t.positions[1][0],t.positions[1][1]),r=e.index,i=Yt.advanceAfter(e,n)-n.length;if(i<0)throw new Error("EOF expected while finding end of Raw String Literal: '"+n+"'");return t.value=e.substring(r,i),t},toFrontMatter:(t,e,s)=>{const n=e.index,r=Yt.advanceAfter(e,"\n---")-4;if(r<0)throw new Error("EOF expected while finding end of front matter");return t.value=e.substring(n,r),t}}}));return r.default})());
116
116
  //# sourceMappingURL=notations.umd.min.js.map