@rr0/ufoathome 0.185.2 → 0.185.3
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.
- package/dist-embed-scene/rr0-scene.mjs +4 -4
- package/dist-embed-sighting/{CaseReportExport-Drb2dd78.js → CaseReportExport-lbuI40c8.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +9 -9
- package/dist-embed-sighting-editor/{CaseReportExport-COqBs7VN.js → CaseReportExport-QyaWB9n9.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +7 -7
- package/package.json +1 -1
|
@@ -412,8 +412,8 @@ ${e} :is(select:not([multiple]):not([size]), .rr0-select) {
|
|
|
412
412
|
<button id="copy" class="share-copy" type="button"></button>
|
|
413
413
|
</div>
|
|
414
414
|
</dialog>
|
|
415
|
-
`;class Gd extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Gd.TAG)||customElements.define(Gd.TAG,Gd)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=k5;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await y5.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?ao.pinnedLink(e.link(),"0.185.
|
|
416
|
-
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.185.2")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Y(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}class Nr extends Error{}class Vg{constructor(e){this.name=e}validate(e){return!0}}class sT extends Vg{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Nr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Nr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ni{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new sT(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=s,this.duration=s?(s.max-s.min+1)*s.duration:1,this.validator=n}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class mw{millisecond;second;minute;hour;day;month;year}class R5 extends mw{}class nT extends R5{millisecond=new Ni("millisecond",0,999,void 0);second=new Ni("second",0,59,this.millisecond);minute=new Ni("minute",0,59,this.second);hour=new Ni("hour",0,23,this.minute);day=new Ni("day",1,31,this.hour);month=new Ni("month",1,12,this.day);year=new Ni("year",0,9999,this.month)}const mt=new nT;class rT extends sT{constructor(e=1,t=12){super("month",e,t)}}class Md extends Ni{static Month28=new Md(28);static Month29=new Md(29);static ThirtyDays=new Md(30);static ThirtyOneDays=new Md(31);constructor(e,t=new rT(1,e)){super("month",1,e,mt.day,t)}static create(e,t){switch(e){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return t%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Nr("Unsupported month",e,t)}}}class go{static instance=new go;render(e){return e.value.toString()}}class Yn{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new Vg(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=go.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class We{static#e=new Map;static register(e,t){We.#e.set(e,t)}static get(e){const t=We.#e.get(e);if(!t)throw new Nr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class lu extends Yn{constructor(e=new Date().getFullYear(),t=mt.year){super(e,t)}static fromString(e,t=We.get(lu)){return new lu(t.parse(e))}}class Do extends go{static default=new Do("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class cu extends Yn{constructor(e=new Date().getMonth()+1,t=mt.month){super(e,t)}static fromString(e,t=We.get(cu)){return new cu(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class hu extends Yn{constructor(e=new Date().getDate(),t=mt.day){super(e,t)}static fromString(e,t=We.get(hu)){const i=t.parse(e);return new hu(i)}toString(e=Do.default){return super.toString(e)}}class du extends Yn{constructor(e=new Date().getHours(),t=mt.hour){super(e,t)}static fromString(e,t=We.get(du)){return new du(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class uu extends Yn{constructor(e=new Date().getMinutes(),t=mt.minute){super(e,t)}static fromString(e,t=We.get(uu)){return new uu(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class pu extends Yn{constructor(e=new Date().getSeconds(),t=mt.second){super(e,t)}static fromString(e,t=We.get(pu)){return new pu(t.parse(e),mt.second)}toString(e=Do.default){return super.toString(e)}}class Ec extends Yn{static renderer=new Do("0",3);constructor(e,t=mt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Ec.renderer){return super.toString(e)}}class C5{render(e){return e.toString()}}class O5 extends C5{render(e){const t=e.value,i=Math.abs(t),s=Math.floor(i/60),n=i%60;if(s===0&&n===0)return"Z";{const r=t<0?"-":"+",a=s.toString().padStart(2,"0"),o=n>0?":"+n.toString().padEnd(2,"0"):"";return r+a+o}}}class mc{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=We.get(mc),i=void 0){const s=t.parse(e,i);return new mc(s)}toString(e=new O5){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Hn{static timeshift(e,t){return e+(Hn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:s}=e,n=e.hour??12;if(![t,i,s].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=Hn.rule(t);if(!r)return!1;const a=Hn.rank(i,s,n);return a>=Hn.rank(r.start.month,r.start.day,2)&&a<Hn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:Hn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:Hn.sunday(e,3,2)},end:{month:11,day:Hn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:Hn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:Hn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const s=new Date(Date.UTC(2e3,t-1,1));s.setUTCFullYear(e);const n=1+(7-s.getUTCDay())%7;if(i>0)return n+7*(i-1);const r=[31,Hn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=n;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const L5={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},P5={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},N5={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},F5={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},U5={name:"PT",timeshift:c=>Hn.timeshift(-480,c),title:"Pacific Time (US)"},B5={name:"MT",timeshift:c=>Hn.timeshift(-420,c),title:"Mountain Time (US)"},z5={name:"CT",timeshift:c=>Hn.timeshift(-360,c),title:"Central Time (US)"},H5={name:"ET",timeshift:c=>Hn.timeshift(-300,c),title:"Eastern Time (US)"},G5={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},V5={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},W5={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},$5={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},K5={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},X5={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},Y5={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},q5={name:"Z",timeshift:"Z",title:"UTC"},j5={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},Z5={name:"BST",timeshift:"+01",title:"British Summer Time"},J5={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},Q5={name:"CET",timeshift:"+01",title:"Central European Time"},e_={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},t_={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},i_={name:"BJT",timeshift:"+08",title:"Beijing Time"},s_={name:"CST",timeshift:"-06",title:"Central Standard Time"},n_={name:"JST",timeshift:"+09",title:"Japan Standard Time"},r_={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},a_={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},o_={name:"LST",timeshift:"?",title:"Local Sideral Time"},XM=[X5,r_,K5,i_,Z5,s_,V5,Q5,J5,z5,G5,$5,W5,H5,j5,t_,n_,o_,N5,e_,F5,B5,a_,P5,L5,U5,Y5,q5];class Wg{static instance=new Wg;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const s=t.join("-"),n=e.timeshift?e.timeshift.toString():"",r=i.join(":")+n;return s+(r.length>0?"T"+r:"")}}class Hc extends Nr{constructor(e="method is abstract"){super(e)}}class gw{units;constructor(e){this.units=e}newYear(e){throw new Hc}newMonth(e){throw new Hc}newDay(e){throw new Hc}newHour(e){throw new Hc}newMinute(e){throw new Hc}newSecond(e){throw new Hc}}class l_ extends mw{millisecond=new Ni("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ni("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ni("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ni("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ni("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ni("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ni("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Ff=new l_;class $g{static instance=new $g;render(e){const t=La.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(go.instance)+"MM");const r=t.days;r&&(i+=r.toString(go.instance)+"D");const a=t.hours;a&&(i+=a.toString(go.instance)+"H");const o=t.minutes;o&&(i+=o.toString(go.instance)+"M");const l=t.seconds;return l&&(i+=l.toString(go.instance)+"S"),i}}class La extends Yn{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*mt.year.duration:0)+(e.months?e.months*mt.month.duration:0)+(e.days?e.days*mt.day.duration:0)+(e.hours?e.hours*mt.hour.duration:0)+(e.minutes?e.minutes*mt.minute.duration:0)+(e.seconds?e.seconds*mt.second.duration:0)},new Ni("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=h_){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/mt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*mt.year.duration);const o=i/mt.month.duration,l=Math.floor(o);l>0&&(n.months=t.newMonth(s*l),i-=l*mt.month.duration);const h=i/mt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*mt.day.duration);const u=i/mt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*mt.hour.duration);const f=i/mt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*mt.minute.duration);const g=i/mt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=We.get(La)){return new La(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new La(i-s)}toSpec(){return La.toSpec(this)}toString(e=$g.instance){return e.render(this)}}class aT extends gw{constructor(e){super(e)}newYear(e){return new lu(e,this.units.year)}newMonth(e){return new cu(e,this.units.month)}newDay(e){return new hu(e,this.units.day)}newHour(e){return new du(e,this.units.hour)}newMinute(e){return new uu(e,this.units.minute)}newSecond(e){return new pu(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new mc(typeof e=="number"?e:e.value)}}const c_=new aT(mt),h_=new aT(Ff);class yn{#e;#t;#i;#s;#n;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:yn.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof Yn?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof Yn?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof Yn?e:this.factory.newDay(e)}get hour(){return this.#s}set hour(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newHour(e):!e||e.start||e instanceof Yn?e:this.factory.newHour(e)}get minute(){return this.#n}set minute(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newMinute(e):!e||e.start||e instanceof Yn?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof Yn?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof Yn)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof mc)?this.factory.newTimeshift(e):e}get factory(){return c_}static fromString(e,t=We.get(yn)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h}=t.parse(e);return new yn({year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new yn({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return yn.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Vg(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new La(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new yn(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Wg.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const s=this.day?.toSpec();s&&(e.day=s);const n=this.hour?.toSpec();n&&(e.hour=n);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const l=this.timeshift?.toSpec();return l&&(e.timeshift=l),e}toJSON(){return this.toSpec()}}class vw{static instance=new vw;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class Gp{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=yn.fromString(e)),e&&!(e instanceof yn)&&!(e instanceof La))throw new Nr("Interval start is not a level 0 date or duration: "+e);this._start=e}_end;get end(){return this._end}set end(e){if(typeof e=="string"&&(e=yn.fromString(e)),e&&!(e instanceof yn)&&!(e instanceof La))throw new Nr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Gp)){const{start:i,end:s}=t.parse(e);return new Gp(i,s)}toString(e=vw.instance){return e.render(this)}[Symbol.iterator](){let e=this.start;return{next:()=>{const t={done:e>this.end,value:e};return e++,t}}}}class Uf extends go{static instance=new Uf(Do.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class To extends Yn{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=Uf.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class oT extends nT{year=new Ni("year",-9999,9999,this.month);yearExtended=new Ni("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const S0=new oT;class jl extends To{constructor(e,t=S0.year){super(e,t)}static fromString(e,t=S0.year,i=We.get(jl)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=S0.yearExtended),n!==void 0){const r=new jl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new jl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new jl(s,t)}}class lT extends Vg{monthValidator=new rT;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class Zl extends To{constructor(e,t=new Ni(mt.month.name,1,24,mt.day,new lT)){super(e,t)}static fromString(e,t=We.get(Zl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.month;const r=new Zl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Zl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Zl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Jl extends To{constructor(e,t=mt.day){super(e,t)}static fromString(e,t=We.get(Jl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.day;const r=new Jl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Jl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Jl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ql extends To{constructor(e,t=mt.hour){super(e,t)}static fromString(e,t=We.get(Ql)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.hour;const r=new Ql(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Ql(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Ql(i)}}class ec extends To{constructor(e,t=mt.minute){super(e,t)}static fromString(e,t=We.get(ec)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.minute,r=new ec(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ec(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ec(i)}toString(e=Uf.instance){return super.toString(e)}}class tc extends To{constructor(e,t=mt.second){super(e,t)}static fromString(e,t=We.get(tc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.second,r=new tc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new tc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new tc(i)}}class yh extends mc{static fromString(e,t=We.get(yh),i=void 0){return new yh(t.parse(e,i))}}class cT extends gw{constructor(e){super(e)}newYear(e){return new jl(e,this.units.year)}newMonth(e){return new Zl(e,this.units.month)}newDay(e){return new Jl(e,this.units.day)}newHour(e){return new Ql(e,this.units.hour)}newMinute(e){return new ec(e,this.units.minute)}newSecond(e){return new tc(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new yh(typeof e=="number"?e:e.value)}}const d_=new cT(S0),u_=new cT(Ff);class Or extends yn{constructor(e){super(e)}get factory(){return d_}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new Or({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static fromString(e,t=We.get(Or)){const i=t.parse(e);return new Or(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Or.fromString(i)}clone(){return new Or(this.toSpec())}}const Zs=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class Kg extends $g{static instance=new Kg;render(e){return super.render(e)}}class Xs extends To{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Xs.getValue(e,Zs.year)+Xs.getValue(e,Zs.month)+Xs.getValue(e,Zs.day)+Xs.getValue(e,Zs.hour)+Xs.getValue(e,Zs.minute)+Xs.getValue(e,Zs.second),uncertain:Xs.getBoolean(e,Zs.uncertain),approximate:Xs.getBoolean(e,"approximate")},Ff.millisecond)}static getBoolean(e,t){return e[t]||e[Zs.year+"s"]?.[t]||e[Zs.month+"s"]?.[t]||e[Zs.day+"s"]?.[t]||e[Zs.hour+"s"]?.[t]||e[Zs.minute+"s"]?.[t]||e[Zs.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof To?s=s.value:typeof e=="number"&&(s=e),s){const n=mt[t];i=s*n.duration}return i}static toSpec(e,t=u_){return{...La.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=We.get(Xs)){const i=t.parse(e);return new Xs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Xs(i-s)}toString(e=Kg.instance){return super.toString(e)}toSpec(){return Xs.toSpec(this)}}class Vp extends Gp{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=Or.fromString(e)),e&&!(e instanceof Or)&&!(e instanceof Xs))throw new Nr("Interval start is not a level 1 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Or.fromString(e)),e&&!(e instanceof Or)&&!(e instanceof Xs))throw new Nr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Vp)){const{start:i,end:s}=t.parse(e);return new Vp(i,s)}}class Au extends To{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class p_ extends oT{year=new Ni("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const M1=new p_;class Jo extends Au{constructor(e,t=M1.year){super(e,t)}static fromString(e,t=M1.year,i=We.get(Jo)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Jo(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Jo(Object.assign({...s},{value:Math.min(s.value.end,t.max)})),o={start:r,end:a},l=s.value.estimate;return l&&(o.estimate=l),o}else return new Jo(s)}}class f_ extends lT{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class Qo extends Au{constructor(e,t=new Ni(mt.month.name,1,41,mt.day,new f_)){super(e,t)}static fromString(e,t=We.get(Qo)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.month,r=new Qo(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Qo(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Qo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class el extends Au{constructor(e,t=mt.day){super(e,t)}static fromString(e,t=We.get(el)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.day,r=new el(Object.assign({...i},{value:Math.max(s,n.min)})),a=new el(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new el(i)}toString(e){return super.toString(e).padStart(2,"0")}}class tl extends Au{constructor(e,t=mt.hour){super(e,t)}static fromString(e,t=We.get(tl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.hour,r=new tl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new tl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new tl(i)}}class il extends Au{constructor(e,t=mt.minute){super(e,t)}static fromString(e,t=We.get(il)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.minute,r=new il(Object.assign({...i},{value:Math.max(s,n.min)})),a=new il(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new il(i)}}class sl extends Au{constructor(e,t=mt.second){super(e,t)}static fromString(e,t=mt.second,i=We.get(sl)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new sl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new sl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new sl(s,t)}}class hT extends yh{}class m_ extends Uf{qualifier(){return""}}class Ll extends Wg{static instance=new Ll;static valueRenderer=new m_(Do.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],s=Ll.names.slice(Ll.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=Ll.qualifier(i.uncertainComponent,i.approximateComponent),r=Ll.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(Ll.valueRenderer)+r}}class dT extends gw{constructor(e){super(e)}newYear(e){return new Jo(e,this.units.year)}newMonth(e){return new Qo(e,this.units.month)}newDay(e){return new el(e,this.units.day)}newHour(e){return new tl(e,this.units.hour)}newMinute(e){return new il(e,this.units.minute)}newSecond(e){return new sl(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new hT(typeof e=="number"?e:e.value)}}const g_=new dT(M1),v_=new dT(Ff);class pr extends Or{constructor(e){super(e)}toString(e=Ll.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return g_}static fromDate(e){return new pr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static fromString(e,t=We.get(pr)){const i=t.parse(e);return new pr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return pr.fromString(i)}clone(){return new pr(this.toSpec())}}class vl{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Nr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Hc(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class xd extends Kg{static instance=new xd;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(e,t){return e?t?"%":"?":t?"~":""}render(e){const t=xd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of xd.designators){const r=e.components[s];r&&(i+=xd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class Ws extends Xs{#e;constructor(e){if(super(typeof e=="number"?e:{value:Ws.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},Ff.millisecond),typeof e!="number"){const t={};for(const i of Ws.componentNames)e[i]instanceof To&&(t[i]=e[i]);Object.keys(t).length>0&&(this.#e=t)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#e}#t(e){return this.#e?Object.values(this.#e).some(t=>t[e]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#t("uncertain")}set uncertain(e){super.uncertain=e}get approximate(){return super.approximate||this.#t("approximate")}set approximate(e){super.approximate=e}get hasQualifiedComponent(){return this.#e?Object.values(this.#e).some(e=>e.uncertainComponent||e.approximateComponent):!1}static valueFromSpec(e){return Ws.getValue(e,Zs.year)+Ws.getValue(e,Zs.month)+Ws.getValue(e,Zs.day)+Ws.getValue(e,Zs.hour)+Ws.getValue(e,Zs.minute)+Ws.getValue(e,Zs.second)}static toSpec(e,t=v_){const i=Xs.toSpec(e,t);if(e instanceof Ws&&e.hasQualifiedComponent)for(const s of Ws.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=We.get(Ws)){const i=t.parse(e);return new Ws(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Ws(i-s)}toSpec(){return Ws.toSpec(this)}toString(e=xd.instance){return super.toString(e)}}class Wp extends Vp{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=pr.fromString(e)),e&&!(e instanceof pr)&&!(e instanceof Ws))throw new Nr("Interval start is not a level 2 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=pr.fromString(e)),e&&!(e instanceof pr)&&!(e instanceof Ws))throw new Nr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Wp)){const{start:i,end:s}=t.parse(e);return new Wp(i,s)}}class G0 extends Set{constructor(e,t){super(e),this.exclusive=t}has(e){const t=e.toString().replace("..","/");for(const i of this)if(i.toString()===t)return!0;return!1}static fromString(e,t=We.get(G0)){const{exclusive:i,values:s}=t.parse(e);return new G0(s,i)}}class bl extends vl{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return bl.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Nr(`${this.name} cannot be negative`);return super.parse(e)}}class B{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return B.optional(B.group(e,...t))}static optionalNonCapturingGroup(...e){return B.optional(B.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return B.group(e,`${i||""}[${s}]${t}`)}}const YM="yearValue";class $p extends bl{static format(e=""){return B.numberGroup(B.groupName(e,YM),"{4}",void 0)}constructor(){super(YM,$p.format())}}const qM="monthValue";class Kp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,qM),"{1,2}",void 0)}constructor(){super(qM,Kp.format())}}const jM="dayValue";class Vd extends bl{static format(e=""){return B.numberGroup(B.groupName(e,jM),"{1,2}",void 0)}constructor(){super(jM,Vd.format())}}const ZM="hourValue";class Wd extends bl{static format(e=""){return B.numberGroup(B.groupName(e,ZM),"{1,2}",void 0)}constructor(){super(ZM,Wd.format())}}const JM="minuteValue";class Xp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,JM),"{1,2}",void 0)}constructor(){super(JM,Xp.format())}}const QM="secondValue";class Yp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,QM),"{1,2}",void 0)}constructor(){super(QM,Yp.format())}}const ex="timeshiftValue",tx="shiftHour",ix="shiftMinute";class fu extends vl{static format(e=""){return XM.map(t=>t.name).join("|")+"|"+B.nonCapturingGroup(B.group(e+tx,B.numberGroup(B.groupName(e,ex),"{2}","[+-]")),B.optionalNonCapturingGroup(":?",B.numberGroup(B.groupName(e,ix),"{2}",void 0)))}constructor(){super(ex,fu.format())}parse(e,t){let i=0;const s=XM.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new Nr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[tx];r&&(i+=parseInt(r,10)*60);const a=n[ix];a&&(i+=parseInt(a,10))}return i}}const sx="year",nx="month",rx="day",ax="hour",ox="minute",lx="second",cx="millisecond",hx="timeshift";class Zc extends vl{static format(e=""){return B.group(B.groupName(e,sx),$p.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,nx),Kp.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,rx),Vd.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,ax),Wd.format(e)),":?",B.group(B.groupName(e,ox),Xp.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,lx),Yp.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,cx),"\\d+"))),"\\s*",B.optionalGroup(B.groupName(e,hx),fu.format(e)))))}constructor(){super("date",Zc.format())}parse(e){const t=this.regexGroups(e),i=t[sx],s=t[nx],n=t[rx],r=t[ax],a=t[ox],o=t[lx],l=t[cx],h=t[hx],d=i?new lu($p.read(i)):void 0,u=s?Kp.read(s):void 0;return{year:d,month:u?new cu(u,Md.create(u.value,d?.value)):void 0,day:n?new hu(Vd.read(n)):void 0,hour:r?new du(Wd.read(r)):void 0,minute:a?new uu(Xp.read(a)):void 0,second:o?new pu(Yp.read(o)):void 0,millisecond:l?Ec.parseFraction(l):void 0,timeshift:h?mc.fromString(h,new fu,{year:d?.value,month:u?.value,day:n?Vd.read(n).value:void 0,hour:r?Wd.read(r).value:void 0}):void 0}}}const dx="years",yv="months",b_="days",ux="hours",px="minutes",fx="seconds";class bw extends vl{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,dx),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,yv),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,b_),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ux),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,px),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,fx),"+",void 0,"\\d"),"S")}constructor(){super("duration",bw.format())}parseGroups(e){return{years:e[dx],months:e[yv],days:e[yv],hours:e[ux],minutes:e[px],seconds:e[fx]}}}const wv="start",Mv="end";class yw extends vl{static format=B.group(wv,Zc.format(wv))+"/"+B.group(Mv,Zc.format(Mv));constructor(){super("interval",yw.format)}parse(e){const t=this.regexGroups(e),i=t[wv],s=t[Mv];return{start:i?yn.fromString(i,new Zc):void 0,end:s?yn.fromString(s,new Zc):void 0}}}We.register(yn,()=>new Zc);We.register(hu,()=>new Vd);We.register(La,()=>new bw);We.register(du,()=>new Wd);We.register(Gp,()=>new yw);We.register(uu,()=>new Xp);We.register(cu,()=>new Kp);We.register(pu,()=>new Yp);We.register(mc,()=>new fu);We.register(lu,()=>new $p);class Qi extends bl{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Qi.uncertainGroup+Qi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return B.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(B.groupName(Qi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(Qi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(Qi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return B.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let s=0,n;for(n=0;n<t.length;n++){const l=t[n];if(l==="X")break;s=s*10+parseInt(l,10)}if(n<t.length){let l=1;for(let u=0;u<t.length-n;u++)l*=10;const h=i*s*l,d=h+l-1;s={start:h,end:d}}else s*=i;const r=e[B.groupName(Qi.uncertainAndApproximateGroup,this.name)],a=e[B.groupName(Qi.approximateGroup,this.name)]||r,o=e[B.groupName(Qi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const mx="yearValue";class qp extends Qi{constructor(){super(mx,qp.format())}static format(e=""){return"Y?"+Qi.numberFormat(B.groupName(e,mx),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const gx="monthValue";class jp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,gx),"{1,2}",void 0)}constructor(){super(gx,jp.format())}}const vx="dayValue";class Zp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,vx),"{1,2}",void 0)}constructor(){super(vx,Zp.format())}}const bx="hourValue";class Jp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,bx),"{1,2}",void 0)}constructor(){super(bx,Jp.format())}}const yx="minuteValue";class Qp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,yx),"{1,2}",void 0)}constructor(){super(yx,Qp.format())}}const wx="secondValue";class ef extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,wx),"{1,2}",void 0)}constructor(){super(wx,ef.format())}}class tf extends fu{}class hs extends vl{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=hs.format()){super("date",e)}static format(e=""){return B.group(B.groupName(e,hs.yearGroup),qp.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.monthGroup),jp.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.dayGroup),Zp.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,hs.hourGroup),Jp.format(e)),":",B.group(B.groupName(e,hs.minuteGroup),Qp.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,hs.secondGroup),ef.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,hs.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,hs.timeshiftGroup),tf.format(e)))))}parseGroups(e){const t=e[hs.millisecondGroup],i=t?Ec.parseFraction(t):void 0,s=e[hs.secondGroup],n=s?tc.fromString(s,new ef):void 0,r=e[hs.minuteGroup];let a;r&&(a=ec.fromString(r,new Qp),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[hs.hourGroup];let l;o&&(l=Ql.fromString(o,new Jp),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[hs.dayGroup];let d;h&&(d=Jl.fromString(h,new Zp),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[hs.monthGroup];let p;u&&(p=Zl.fromString(u,new jp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[hs.yearGroup];let m;f&&(m=jl.fromString(f,void 0,new qp),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[hs.timeshiftGroup],v=g?yh.fromString(g,new tf,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:v}}}const Mx="years",xx="months",Ex="days",Sx="hours",Ax="minutes",Tx="seconds";class Jc extends Qi{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Mx),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,xx),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Ex),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Sx),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Ax),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Tx),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",Jc.format())}parseGroups(e){return{years:e[Mx],months:e[xx],days:e[Ex],hours:e[Sx],minutes:e[Ax],seconds:e[Tx],uncertain:!!e[Qi.uncertainGroup],approximate:!!e[Qi.approximateGroup]}}}const y_="dates",xv="start",Ev="end",Ix="durations",Sv="durationMin",Av="durationMax";class ww extends vl{static format=B.group(y_,B.optionalGroup(xv,B.group("openStart","\\.\\.")+"|"+hs.format(xv))+"/"+B.optionalGroup(Ev,B.group("openEnd","\\.\\.")+"|"+hs.format(Ev)))+"|"+B.group(Ix,B.group(Sv,Jc.format(Sv))+"/"+B.group(Av,Jc.format(Av)));constructor(e="interval",t=ww.format){super(e,t)}parseGroups(e){let t,i;if(e[Ix]){const n=e[Sv];t=Xs.fromString(n,new Jc);const r=e[Av];i=Xs.fromString(r,new Jc)}else{const n=e[xv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=Or.fromString(n,new hs)}const r=e[Ev];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Or.fromString(r,new hs)}}return{start:t,end:i}}}We.register(Or,()=>new hs);We.register(Jl,()=>new Zp);We.register(Xs,()=>new Jc);We.register(Ql,()=>new Jp);We.register(Vp,()=>new ww);We.register(ec,()=>new Qp);We.register(Zl,()=>new jp);We.register(tc,()=>new ef);We.register(yh,()=>new tf);We.register(jl,()=>new qp);class li extends Qi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=li.uncertainGroup+li.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(B.groupName(li.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(li.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(li.uncertainAndApproximateGroup,e),"%")+Qi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[B.groupName(li.uncertainAndApproximateGroup,this.name)];return(e[B.groupName(li.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[B.groupName(li.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const ku="yearValue",_x="exp",Dx="signif";class sf extends li{constructor(){super(ku,sf.format())}static format(e=""){return"Y?"+B.nonCapturingGroup(B.group(B.groupName(e,_x),"[-]?\\d+E\\d+")+"|"+li.numberFormat(B.groupName(e,ku),"+","[-]?")+B.optionalGroup(B.groupName(e,Dx),"S\\d+"))}parseGroups(e){const t=e[_x];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),l=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[ku]=l.toString()}const i=e[Dx],s=e[ku];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";e[ku]=(o<0?"-":"")+l}const n=super.parseGroups(e);return i&&(n.value.estimate=parseInt(s,10)),n}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const kx="monthValue";class nf extends li{static format(e=""){return li.numberFormat(B.groupName(e,kx),"{1,2}",void 0)}constructor(){super(kx,nf.format())}}const Rx="dayValue";class rf extends li{static format(e=""){return li.numberFormat(B.groupName(e,Rx),"{1,2}",void 0)}constructor(){super(Rx,rf.format())}}const Cx="hourValue";class af extends li{static format(e=""){return li.numberFormat(B.groupName(e,Cx),"{1,2}",void 0)}constructor(){super(Cx,af.format())}}const Ox="secondValue";class of extends li{static format(e=""){return li.numberFormat(B.groupName(e,Ox),"{1,2}",void 0)}constructor(){super(Ox,of.format())}}const Lx="minuteValue";class lf extends li{static format(e=""){return li.numberFormat(B.groupName(e,Lx),"{1,2}",void 0)}constructor(){super(Lx,lf.format())}}class w_ extends tf{}class vi extends vl{static yearGroup=hs.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",vi.format())}static format(e=""){return B.group(B.groupName(e,vi.yearGroup),sf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,vi.monthGroup),nf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,vi.dayGroup),rf.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,vi.hourGroup),af.format(e)),":",B.group(B.groupName(e,vi.minuteGroup),lf.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,vi.secondGroup),of.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,vi.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,vi.timeshiftGroup),w_.format(e)))))}parseGroups(e){const t=e[vi.millisecondGroup],i=t?Ec.parseFraction(t):void 0,s=e[vi.secondGroup];let n;s&&(n=sl.fromString(s,void 0,new of),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[vi.minuteGroup];let a;r&&(a=il.fromString(r,new lf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[vi.hourGroup];let l;o&&(l=tl.fromString(o,new af),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[vi.dayGroup];let d;h&&(d=el.fromString(h,new rf),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[vi.monthGroup];let p;u&&(p=Qo.fromString(u,new nf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[vi.yearGroup];let m;f&&(m=Jo.fromString(f,void 0,new sf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[vi.timeshiftGroup],v=g?hT.fromString(g,new tf,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:v}}}const Px="durationValue";class Mw extends li{static format(e=""){return"^"+li.numberFormat(B.groupName(e,Px),"+",void 0)}constructor(){super(Px,Mw.format())}}class M_ extends mw{millisecond=new Ni("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new Ni("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ni("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new Ni("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new Ni("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new Ni("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new Ni("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Rh=new M_;class ut extends li{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new Mw;static componentFormat(e,t,i,s,n=""){const r=B.group(B.groupName(e,ut.quantityGroup(t)),li.numberFormat(B.groupName(e,i),"+",void 0,"\\d"));return B.group(B.groupName(e,t),r,s,n)}static quantityGroup(e){return e+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",ut.format())}static format(e=""){const t=B.groupName(e,ut.durationGroup);return this.qualifierFormat(B.groupName(li.uncertainGroup,t),"?")+this.qualifierFormat(B.groupName(li.approximateGroup,t),"~")+this.qualifierFormat(B.groupName(li.uncertainAndApproximateGroup,t),"%")+"P"+B.optional(ut.componentFormat(e,ut.yearsGroup,vi.yearGroup,"Y"))+B.optionalNonCapturingGroup(ut.componentFormat(e,ut.monthsGroup,vi.monthGroup,"MM")+"|"+ut.componentFormat(e,ut.isoMonthsGroup,"isoMonth","M",ut.isoMonthsLookahead))+B.optional(ut.componentFormat(e,ut.daysGroup,vi.dayGroup,"D"))+"T?"+B.optional(ut.componentFormat(e,ut.hoursGroup,vi.hourGroup,"H"))+B.optional(ut.componentFormat(e,ut.minutesGroup,vi.minuteGroup,"M"))+B.optional(ut.componentFormat(e,ut.secondsGroup,vi.secondGroup,"S"))+B.optionalGroup(B.groupName(e,ut.suffixGroup),"[?~%]")}static parseComponent(e,t,i){const s=ut.componentParser.parse(e);return new t(s,i)}parseGroups(e){const t=e[ut.quantityGroup(ut.secondsGroup)];let i;t&&(i=ut.parseComponent(t,sl,Rh.second),i.uncertain=!!e[B.groupName(li.uncertainGroup,ut.secondsGroup)]||!1,i.approximate=!!e[B.groupName(li.approximateGroup,ut.secondsGroup)]||!1);const s=e[ut.quantityGroup(ut.minutesGroup)];let n;s&&(n=ut.parseComponent(s,il,Rh.minute),n.uncertain=n.uncertain||i?.uncertain||!1,n.approximate=n.approximate||i?.approximate||!1);const r=e[ut.quantityGroup(ut.hoursGroup)];let a;r&&(a=ut.parseComponent(r,tl,Rh.hour),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[ut.quantityGroup(ut.daysGroup)];let l;o&&(l=ut.parseComponent(o,el,Rh.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[ut.quantityGroup(ut.monthsGroup)]||e[ut.quantityGroup(ut.isoMonthsGroup)];let d;h&&(d=ut.parseComponent(h,Qo,Rh.month),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[ut.quantityGroup(ut.yearsGroup)];let p;u&&(p=ut.parseComponent(u,Jo,Rh.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ut.suffixGroup],m=!!e[B.groupName(li.uncertainAndApproximateGroup,ut.durationGroup)]||f==="%",g=m||!!e[B.groupName(li.uncertainGroup,ut.durationGroup)]||f==="?",v=m||!!e[B.groupName(li.approximateGroup,ut.durationGroup)]||f==="~";return{years:p,months:d,days:l,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const x_="dates",Tv="start",Iv="end",Nx="durations",_v="durationMin",Dv="durationMax";class Xg extends vl{static format=B.group(x_,B.optionalGroup(Tv,B.group("openStart","\\.\\.")+"|"+vi.format(Tv))+"/"+B.optionalGroup(Iv,B.group("openEnd","\\.\\.")+"|"+vi.format(Iv)))+"|"+B.group(Nx,B.group(_v,ut.format(_v))+"/"+B.group(Dv,ut.format(Dv)));constructor(e="interval",t=Xg.format){super(e,t)}parseGroups(e){let t,i;if(e[Nx]){const n=e[_v];t=Ws.fromString(n,new ut);const r=e[Dv];i=Ws.fromString(r,new ut)}else{const n=e[Tv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=pr.fromString(n,new vi)}const r=e[Iv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=pr.fromString(r,new vi)}}return{start:t,end:i}}}class E_{parse(e){e=e.trim();const t=e.startsWith("["),s=e.substring(1,e.length-1).split(","),n=[];for(const r of s){let a;r.includes("..")?a=Wp.fromString(r.replace("..","/"),new Xg):a=pr.fromString(r,new vi),n.push(a)}return{values:n,exclusive:t}}}We.register(pr,()=>new vi);We.register(el,()=>new rf);We.register(Ws,()=>new ut);We.register(tl,()=>new af);We.register(Wp,()=>new Xg);We.register(il,()=>new lf);We.register(Qo,()=>new nf);We.register(sl,()=>new of);We.register(G0,()=>new E_);We.register(Jo,()=>new sf);class Ls{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[Ls.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>Ls.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(Ls.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(l=>l===i))!==null&&s!==void 0?s:Object.keys(a).find(l=>Ls.base(l)===Ls.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}Ls.any=new Ls([]);var Fx;(function(c){c.abductee="abductee",c.actor="actor",c.artist="artist",c.anthropologist="anthropologist",c.archeologist="archeologist",c.astronaut="astronaut",c.astronomer="astronomer",c.astrologist="astrologist",c.astrophysicist="astrophysicist",c.banker="banker",c.barman="barman",c.biologist="biologist",c.biochemist="biochemist",c.biophysicist="biophysicist",c.bishop="bishop",c.businessman="businessman",c.botanist="botanist",c.cameraman="cameraman",c.chemist="chemist",c.contactee="contactee",c.cryptozoologist="cryptozoologist",c.dentist="dentist",c.director="director",c.diplomat="diplomat",c.diver="diver",c.electronics="electronics",c.engineer="engineer",c.ethnologist="ethnologist",c.exobiologist="exobiologist",c.farmer="farmer",c.firefighter="firefighter",c.flightAttendant="flightAttendant",c.geologist="geologist",c.geophysicist="geophysicist",c.geographer="geographer",c.historian="historian",c.houseWife="houseWife",c.hypnotherapist="hypnotherapist",c.illusionist="illusionist",c.journalist="journalist",c.judge="judge",c.lawyer="lawyer",c.leader="leader",c.librarian="librarian",c.logger="logger",c.mathematician="mathematician",c.mechanic="mechanic",c.meteorologist="meteorologist",c.military="military",c.musician="musician",c.neurologist="neurologist",c.neuroscientist="neuroscientist",c.neuropsychiatrist="neuropsychiatrist",c.nurse="nurse",c.oceanographer="oceanographer",c.painter="painter",c.parapsychologist="parapsychologist",c.philosopher="philosopher",c.photographer="photographer",c.physician="physician",c.physicist="physicist",c.pilot="pilot",c.politician="politician",c.policeman="policeman",c.priest="priest",c.producer="producer",c.prospector="prospector",c.psychologist="psychologist",c.psychiatrist="psychiatrist",c.radioastronomer="radioastronomer",c.radioamateur="radioamateur",c.salesman="salesman",c.sailor="sailor",c.sociologist="sociologist",c.softwareEngineer="softwareEngineer",c.stuntman="stuntman",c.taxiDriver="taxiDriver",c.teacher="teacher",c.telegrapher="telegrapher",c.truckDriver="truckDriver",c.ufologist="ufologist",c.ufoWitness="ufoWitness",c.ufoWitness2="ufoWitness2",c.worker="worker",c.writer="writer"})(Fx||(Fx={}));var Ux;(function(c){c.neutral="neutral",c.male="male",c.female="female"})(Ux||(Ux={}));class S_ extends Error{constructor(e,t){super(e),this.cause=t}}class xw extends S_{constructor(e=xw.defaultMessage,t){super(e,t)}}xw.defaultMessage="Assertion failed";var Bx;(function(c){c.country="country",c.region="region",c.department="department",c.city="city",c.company="company"})(Bx||(Bx={}));var zx;(function(c){c.at="at",c.au="au",c.ar="ar",c.be="be",c.br="br",c.ca="ca",c.ch="ch",c.cn="cn",c.cl="cl",c.co="co",c.cy="cy",c.de="de",c.dk="dk",c.do="do",c.dz="dz",c.gr="gr",c.ec="ec",c.eg="eg",c.es="es",c.fi="fi",c.fr="fr",c.ga="ga",c.ge="ge",c.hu="hu",c.in="in",c.ie="ie",c.ir="ir",c.il="il",c.it="it",c.jp="jp",c.kr="kr",c.ma="ma",c.mx="mx",c.my="my",c.mz="mz",c.nl="nl",c.no="no",c.nz="nz",c.pa="pa",c.pe="pe",c.ph="ph",c.pl="pl",c.pt="pt",c.ro="ro",c.ru="ru",c.sc="sc",c.tr="tr",c.ua="ua",c.uk="uk",c.us="us",c.sa="sa",c.se="se",c.su="su",c.tn="tn",c.tw="tw",c.ve="ve",c.za="za"})(zx||(zx={}));class A_{static of(e){if(!(!e||e.length===0))return e.some(t=>t.outcome==="fails"&&t.against!=="supposed")?"incompatible":e.some(t=>t.outcome!=="holds")?"unsettled":"compatible"}}/**
|
|
415
|
+
`;class Gd extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Gd.TAG)||customElements.define(Gd.TAG,Gd)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=k5;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await y5.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?ao.pinnedLink(e.link(),"0.185.3"):e.link(),this.fitLink();const s=`<script type="module" src="${t?ao.pinned(e.module,"0.185.3"):ao.current(e.module,import.meta.url,ou.home())}"><\/script>
|
|
416
|
+
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.185.3")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Y(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}class Nr extends Error{}class Vg{constructor(e){this.name=e}validate(e){return!0}}class sT extends Vg{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Nr(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Nr(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Ni{name;min;max;duration;subUnit;validator;constructor(e,t,i,s,n=new sT(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=s,this.duration=s?(s.max-s.min+1)*s.duration:1,this.validator=n}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class mw{millisecond;second;minute;hour;day;month;year}class R5 extends mw{}class nT extends R5{millisecond=new Ni("millisecond",0,999,void 0);second=new Ni("second",0,59,this.millisecond);minute=new Ni("minute",0,59,this.second);hour=new Ni("hour",0,23,this.minute);day=new Ni("day",1,31,this.hour);month=new Ni("month",1,12,this.day);year=new Ni("year",0,9999,this.month)}const mt=new nT;class rT extends sT{constructor(e=1,t=12){super("month",e,t)}}class Md extends Ni{static Month28=new Md(28);static Month29=new Md(29);static ThirtyDays=new Md(30);static ThirtyOneDays=new Md(31);constructor(e,t=new rT(1,e)){super("month",1,e,mt.day,t)}static create(e,t){switch(e){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return t%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Nr("Unsupported month",e,t)}}}class go{static instance=new go;render(e){return e.value.toString()}}class Yn{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new Vg(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=go.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class We{static#e=new Map;static register(e,t){We.#e.set(e,t)}static get(e){const t=We.#e.get(e);if(!t)throw new Nr(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class lu extends Yn{constructor(e=new Date().getFullYear(),t=mt.year){super(e,t)}static fromString(e,t=We.get(lu)){return new lu(t.parse(e))}}class Do extends go{static default=new Do("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class cu extends Yn{constructor(e=new Date().getMonth()+1,t=mt.month){super(e,t)}static fromString(e,t=We.get(cu)){return new cu(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class hu extends Yn{constructor(e=new Date().getDate(),t=mt.day){super(e,t)}static fromString(e,t=We.get(hu)){const i=t.parse(e);return new hu(i)}toString(e=Do.default){return super.toString(e)}}class du extends Yn{constructor(e=new Date().getHours(),t=mt.hour){super(e,t)}static fromString(e,t=We.get(du)){return new du(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class uu extends Yn{constructor(e=new Date().getMinutes(),t=mt.minute){super(e,t)}static fromString(e,t=We.get(uu)){return new uu(t.parse(e))}toString(e=Do.default){return super.toString(e)}}class pu extends Yn{constructor(e=new Date().getSeconds(),t=mt.second){super(e,t)}static fromString(e,t=We.get(pu)){return new pu(t.parse(e),mt.second)}toString(e=Do.default){return super.toString(e)}}class Ec extends Yn{static renderer=new Do("0",3);constructor(e,t=mt.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=Ec.renderer){return super.toString(e)}}class C5{render(e){return e.toString()}}class O5 extends C5{render(e){const t=e.value,i=Math.abs(t),s=Math.floor(i/60),n=i%60;if(s===0&&n===0)return"Z";{const r=t<0?"-":"+",a=s.toString().padStart(2,"0"),o=n>0?":"+n.toString().padEnd(2,"0"):"";return r+a+o}}}class mc{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=We.get(mc),i=void 0){const s=t.parse(e,i);return new mc(s)}toString(e=new O5){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Hn{static timeshift(e,t){return e+(Hn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:s}=e,n=e.hour??12;if(![t,i,s].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=Hn.rule(t);if(!r)return!1;const a=Hn.rank(i,s,n);return a>=Hn.rank(r.start.month,r.start.day,2)&&a<Hn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:Hn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:Hn.sunday(e,3,2)},end:{month:11,day:Hn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:Hn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:Hn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const s=new Date(Date.UTC(2e3,t-1,1));s.setUTCFullYear(e);const n=1+(7-s.getUTCDay())%7;if(i>0)return n+7*(i-1);const r=[31,Hn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=n;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const L5={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},P5={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},N5={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},F5={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},U5={name:"PT",timeshift:c=>Hn.timeshift(-480,c),title:"Pacific Time (US)"},B5={name:"MT",timeshift:c=>Hn.timeshift(-420,c),title:"Mountain Time (US)"},z5={name:"CT",timeshift:c=>Hn.timeshift(-360,c),title:"Central Time (US)"},H5={name:"ET",timeshift:c=>Hn.timeshift(-300,c),title:"Eastern Time (US)"},G5={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},V5={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},W5={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},$5={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},K5={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},X5={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},Y5={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},q5={name:"Z",timeshift:"Z",title:"UTC"},j5={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},Z5={name:"BST",timeshift:"+01",title:"British Summer Time"},J5={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},Q5={name:"CET",timeshift:"+01",title:"Central European Time"},e_={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},t_={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},i_={name:"BJT",timeshift:"+08",title:"Beijing Time"},s_={name:"CST",timeshift:"-06",title:"Central Standard Time"},n_={name:"JST",timeshift:"+09",title:"Japan Standard Time"},r_={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},a_={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},o_={name:"LST",timeshift:"?",title:"Local Sideral Time"},XM=[X5,r_,K5,i_,Z5,s_,V5,Q5,J5,z5,G5,$5,W5,H5,j5,t_,n_,o_,N5,e_,F5,B5,a_,P5,L5,U5,Y5,q5];class Wg{static instance=new Wg;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const s=t.join("-"),n=e.timeshift?e.timeshift.toString():"",r=i.join(":")+n;return s+(r.length>0?"T"+r:"")}}class Hc extends Nr{constructor(e="method is abstract"){super(e)}}class gw{units;constructor(e){this.units=e}newYear(e){throw new Hc}newMonth(e){throw new Hc}newDay(e){throw new Hc}newHour(e){throw new Hc}newMinute(e){throw new Hc}newSecond(e){throw new Hc}}class l_ extends mw{millisecond=new Ni("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Ni("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ni("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Ni("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Ni("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Ni("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Ni("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Ff=new l_;class $g{static instance=new $g;render(e){const t=La.toSpec(e);let i="P";const s=t.years;s&&(i+=s.toString()+"Y");const n=t.months;n&&(i+=n.toString(go.instance)+"MM");const r=t.days;r&&(i+=r.toString(go.instance)+"D");const a=t.hours;a&&(i+=a.toString(go.instance)+"H");const o=t.minutes;o&&(i+=o.toString(go.instance)+"M");const l=t.seconds;return l&&(i+=l.toString(go.instance)+"S"),i}}class La extends Yn{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*mt.year.duration:0)+(e.months?e.months*mt.month.duration:0)+(e.days?e.days*mt.day.duration:0)+(e.hours?e.hours*mt.hour.duration:0)+(e.minutes?e.minutes*mt.minute.duration:0)+(e.seconds?e.seconds*mt.second.duration:0)},new Ni("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=h_){let i=typeof e=="number"?e:e.value;const s=i>0?1:-1;i=Math.abs(i);const n={},r=i/mt.year.duration,a=Math.floor(r);a>0&&(n.years=t.newYear(s*a),i-=a*mt.year.duration);const o=i/mt.month.duration,l=Math.floor(o);l>0&&(n.months=t.newMonth(s*l),i-=l*mt.month.duration);const h=i/mt.day.duration,d=Math.floor(h);d>0&&(n.days=t.newDay(s*d),i-=d*mt.day.duration);const u=i/mt.hour.duration,p=Math.floor(u);p>0&&(n.hours=t.newHour(s*p),i-=p*mt.hour.duration);const f=i/mt.minute.duration,m=Math.floor(f);m>0&&(n.minutes=t.newMinute(s*m),i-=m*mt.minute.duration);const g=i/mt.second.duration,v=Math.floor(s*g);return v>0&&(n.seconds=t.newSecond(v)),n}static fromString(e,t=We.get(La)){return new La(t.parse(e))}static between(e,t){const i=t.getTime(),s=e.getTime();return new La(i-s)}toSpec(){return La.toSpec(this)}toString(e=$g.instance){return e.render(this)}}class aT extends gw{constructor(e){super(e)}newYear(e){return new lu(e,this.units.year)}newMonth(e){return new cu(e,this.units.month)}newDay(e){return new hu(e,this.units.day)}newHour(e){return new du(e,this.units.hour)}newMinute(e){return new uu(e,this.units.minute)}newSecond(e){return new pu(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new mc(typeof e=="number"?e:e.value)}}const c_=new aT(mt),h_=new aT(Ff);class yn{#e;#t;#i;#s;#n;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:yn.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof Yn?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof Yn?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof Yn?e:this.factory.newDay(e)}get hour(){return this.#s}set hour(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newHour(e):!e||e.start||e instanceof Yn?e:this.factory.newHour(e)}get minute(){return this.#n}set minute(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newMinute(e):!e||e.start||e instanceof Yn?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof Yn?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof Yn)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof mc)?this.factory.newTimeshift(e):e}get factory(){return c_}static fromString(e,t=We.get(yn)){const{year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h}=t.parse(e);return new yn({year:i,month:s,day:n,hour:r,minute:a,second:o,millisecond:l,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new yn({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return yn.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Vg(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new La(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new yn(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Wg.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const s=this.day?.toSpec();s&&(e.day=s);const n=this.hour?.toSpec();n&&(e.hour=n);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const o=this.millisecond?.toSpec();o&&(e.millisecond=o);const l=this.timeshift?.toSpec();return l&&(e.timeshift=l),e}toJSON(){return this.toSpec()}}class vw{static instance=new vw;render(e){return(e.start?e.start.toString():"")+"/"+(e.end?e.end.toString():"")}}class Gp{constructor(e,t){this.start=e,this.end=t}_start;get start(){return this._start}set start(e){if(typeof e=="string"&&(e=yn.fromString(e)),e&&!(e instanceof yn)&&!(e instanceof La))throw new Nr("Interval start is not a level 0 date or duration: "+e);this._start=e}_end;get end(){return this._end}set end(e){if(typeof e=="string"&&(e=yn.fromString(e)),e&&!(e instanceof yn)&&!(e instanceof La))throw new Nr("Interval end is not a level 0 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Gp)){const{start:i,end:s}=t.parse(e);return new Gp(i,s)}toString(e=vw.instance){return e.render(this)}[Symbol.iterator](){let e=this.start;return{next:()=>{const t={done:e>this.end,value:e};return e++,t}}}}class Uf extends go{static instance=new Uf(Do.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class To extends Yn{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=Uf.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class oT extends nT{year=new Ni("year",-9999,9999,this.month);yearExtended=new Ni("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const S0=new oT;class jl extends To{constructor(e,t=S0.year){super(e,t)}static fromString(e,t=S0.year,i=We.get(jl)){const s=i.parse(e),n=s.value.start;if(e.startsWith("Y")&&(t=S0.yearExtended),n!==void 0){const r=new jl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new jl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new jl(s,t)}}class lT extends Vg{monthValidator=new rT;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class Zl extends To{constructor(e,t=new Ni(mt.month.name,1,24,mt.day,new lT)){super(e,t)}static fromString(e,t=We.get(Zl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.month;const r=new Zl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Zl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Zl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Jl extends To{constructor(e,t=mt.day){super(e,t)}static fromString(e,t=We.get(Jl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.day;const r=new Jl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Jl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Jl(i)}toString(e){return super.toString(e).padStart(2,"0")}}class Ql extends To{constructor(e,t=mt.hour){super(e,t)}static fromString(e,t=We.get(Ql)){const i=t.parse(e),s=i.value.start;if(s!==void 0){let n=mt.hour;const r=new Ql(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Ql(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Ql(i)}}class ec extends To{constructor(e,t=mt.minute){super(e,t)}static fromString(e,t=We.get(ec)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.minute,r=new ec(Object.assign({...i},{value:Math.max(s,n.min)})),a=new ec(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new ec(i)}toString(e=Uf.instance){return super.toString(e)}}class tc extends To{constructor(e,t=mt.second){super(e,t)}static fromString(e,t=We.get(tc)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.second,r=new tc(Object.assign({...i},{value:Math.max(s,n.min)})),a=new tc(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new tc(i)}}class yh extends mc{static fromString(e,t=We.get(yh),i=void 0){return new yh(t.parse(e,i))}}class cT extends gw{constructor(e){super(e)}newYear(e){return new jl(e,this.units.year)}newMonth(e){return new Zl(e,this.units.month)}newDay(e){return new Jl(e,this.units.day)}newHour(e){return new Ql(e,this.units.hour)}newMinute(e){return new ec(e,this.units.minute)}newSecond(e){return new tc(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new yh(typeof e=="number"?e:e.value)}}const d_=new cT(S0),u_=new cT(Ff);class Or extends yn{constructor(e){super(e)}get factory(){return d_}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new Or({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static fromString(e,t=We.get(Or)){const i=t.parse(e);return new Or(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Or.fromString(i)}clone(){return new Or(this.toSpec())}}const Zs=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class Kg extends $g{static instance=new Kg;render(e){return super.render(e)}}class Xs extends To{constructor(e){super(typeof e=="number"||e.hasOwnProperty("value")?e:{value:Xs.getValue(e,Zs.year)+Xs.getValue(e,Zs.month)+Xs.getValue(e,Zs.day)+Xs.getValue(e,Zs.hour)+Xs.getValue(e,Zs.minute)+Xs.getValue(e,Zs.second),uncertain:Xs.getBoolean(e,Zs.uncertain),approximate:Xs.getBoolean(e,"approximate")},Ff.millisecond)}static getBoolean(e,t){return e[t]||e[Zs.year+"s"]?.[t]||e[Zs.month+"s"]?.[t]||e[Zs.day+"s"]?.[t]||e[Zs.hour+"s"]?.[t]||e[Zs.minute+"s"]?.[t]||e[Zs.second+"s"]?.[t]||!1}static getValue(e,t){let i=0,s=e[t+"s"];if(s instanceof To?s=s.value:typeof e=="number"&&(s=e),s){const n=mt[t];i=s*n.duration}return i}static toSpec(e,t=u_){return{...La.toSpec(e,t),uncertain:e.uncertain||!1,approximate:e.approximate||!1}}static fromString(e,t=We.get(Xs)){const i=t.parse(e);return new Xs(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Xs(i-s)}toString(e=Kg.instance){return super.toString(e)}toSpec(){return Xs.toSpec(this)}}class Vp extends Gp{constructor(e,t){super(e,t)}get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=Or.fromString(e)),e&&!(e instanceof Or)&&!(e instanceof Xs))throw new Nr("Interval start is not a level 1 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=Or.fromString(e)),e&&!(e instanceof Or)&&!(e instanceof Xs))throw new Nr("Interval end is not a level 1 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Vp)){const{start:i,end:s}=t.parse(e);return new Vp(i,s)}}class Au extends To{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class p_ extends oT{year=new Ni("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const M1=new p_;class Jo extends Au{constructor(e,t=M1.year){super(e,t)}static fromString(e,t=M1.year,i=We.get(Jo)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new Jo(Object.assign({...s},{value:Math.max(n,t.min)})),a=new Jo(Object.assign({...s},{value:Math.min(s.value.end,t.max)})),o={start:r,end:a},l=s.value.estimate;return l&&(o.estimate=l),o}else return new Jo(s)}}class f_ extends lT{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class Qo extends Au{constructor(e,t=new Ni(mt.month.name,1,41,mt.day,new f_)){super(e,t)}static fromString(e,t=We.get(Qo)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.month,r=new Qo(Object.assign({...i},{value:Math.max(s,n.min)})),a=new Qo(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new Qo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class el extends Au{constructor(e,t=mt.day){super(e,t)}static fromString(e,t=We.get(el)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.day,r=new el(Object.assign({...i},{value:Math.max(s,n.min)})),a=new el(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new el(i)}toString(e){return super.toString(e).padStart(2,"0")}}class tl extends Au{constructor(e,t=mt.hour){super(e,t)}static fromString(e,t=We.get(tl)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.hour,r=new tl(Object.assign({...i},{value:Math.max(s,n.min)})),a=new tl(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new tl(i)}}class il extends Au{constructor(e,t=mt.minute){super(e,t)}static fromString(e,t=We.get(il)){const i=t.parse(e),s=i.value.start;if(s!==void 0){const n=mt.minute,r=new il(Object.assign({...i},{value:Math.max(s,n.min)})),a=new il(Object.assign({...i},{value:Math.min(i.value.end,n.max)}));return{start:r,end:a}}else return new il(i)}}class sl extends Au{constructor(e,t=mt.second){super(e,t)}static fromString(e,t=mt.second,i=We.get(sl)){const s=i.parse(e),n=s.value.start;if(n!==void 0){const r=new sl(Object.assign({...s},{value:Math.max(n,t.min)})),a=new sl(Object.assign({...s},{value:Math.min(s.value.end,t.max)}));return{start:r,end:a}}else return new sl(s,t)}}class hT extends yh{}class m_ extends Uf{qualifier(){return""}}class Ll extends Wg{static instance=new Ll;static valueRenderer=new m_(Do.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],s=Ll.names.slice(Ll.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),n=Ll.qualifier(i.uncertainComponent,i.approximateComponent),r=Ll.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!s.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!s.some(a=>a.approximate));return n+i.toString(Ll.valueRenderer)+r}}class dT extends gw{constructor(e){super(e)}newYear(e){return new Jo(e,this.units.year)}newMonth(e){return new Qo(e,this.units.month)}newDay(e){return new el(e,this.units.day)}newHour(e){return new tl(e,this.units.hour)}newMinute(e){return new il(e,this.units.minute)}newSecond(e){return new sl(e,this.units.second)}newMillisecond(e){return new Ec(e,this.units.millisecond)}newTimeshift(e){return new hT(typeof e=="number"?e:e.value)}}const g_=new dT(M1),v_=new dT(Ff);class pr extends Or{constructor(e){super(e)}toString(e=Ll.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return g_}static fromDate(e){return new pr({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:yn.timeshiftOf(e)})}static fromString(e,t=We.get(pr)){const i=t.parse(e);return new pr(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return pr.fromString(i)}clone(){return new pr(this.toSpec())}}class vl{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Nr(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Hc(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class xd extends Kg{static instance=new xd;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(e,t){return e?t?"%":"?":t?"~":""}render(e){const t=xd.qualifier(e.uncertainDuration,e.approximateDuration);if(!e.hasQualifiedComponent)return t+super.render(e);let i=t+"P";for(const[s,n]of xd.designators){const r=e.components[s];r&&(i+=xd.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+n)}return i}}class Ws extends Xs{#e;constructor(e){if(super(typeof e=="number"?e:{value:Ws.valueFromSpec(e),uncertain:e.uncertain===!0,approximate:e.approximate===!0},Ff.millisecond),typeof e!="number"){const t={};for(const i of Ws.componentNames)e[i]instanceof To&&(t[i]=e[i]);Object.keys(t).length>0&&(this.#e=t)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#e}#t(e){return this.#e?Object.values(this.#e).some(t=>t[e]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#t("uncertain")}set uncertain(e){super.uncertain=e}get approximate(){return super.approximate||this.#t("approximate")}set approximate(e){super.approximate=e}get hasQualifiedComponent(){return this.#e?Object.values(this.#e).some(e=>e.uncertainComponent||e.approximateComponent):!1}static valueFromSpec(e){return Ws.getValue(e,Zs.year)+Ws.getValue(e,Zs.month)+Ws.getValue(e,Zs.day)+Ws.getValue(e,Zs.hour)+Ws.getValue(e,Zs.minute)+Ws.getValue(e,Zs.second)}static toSpec(e,t=v_){const i=Xs.toSpec(e,t);if(e instanceof Ws&&e.hasQualifiedComponent)for(const s of Ws.componentNames)delete i[s],e.components[s]&&(i[s]=e.components[s]);return i}static fromString(e,t=We.get(Ws)){const i=t.parse(e);return new Ws(i)}static between(e,t){const i=t.getTime(),s=e.getTime();return new Ws(i-s)}toSpec(){return Ws.toSpec(this)}toString(e=xd.instance){return super.toString(e)}}class Wp extends Vp{get start(){return this._start}set start(e){if(typeof e=="string"&&(super.start=pr.fromString(e)),e&&!(e instanceof pr)&&!(e instanceof Ws))throw new Nr("Interval start is not a level 2 date or duration: "+e);this._start=e}get end(){return this._end}set end(e){if(typeof e=="string"&&(e=pr.fromString(e)),e&&!(e instanceof pr)&&!(e instanceof Ws))throw new Nr("Interval end is not a level 2 date or duration: "+e);this._end=e}static fromString(e,t=We.get(Wp)){const{start:i,end:s}=t.parse(e);return new Wp(i,s)}}class G0 extends Set{constructor(e,t){super(e),this.exclusive=t}has(e){const t=e.toString().replace("..","/");for(const i of this)if(i.toString()===t)return!0;return!1}static fromString(e,t=We.get(G0)){const{exclusive:i,values:s}=t.parse(e);return new G0(s,i)}}class bl extends vl{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return bl.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Nr(`${this.name} cannot be negative`);return super.parse(e)}}class B{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return B.optional(B.group(e,...t))}static optionalNonCapturingGroup(...e){return B.optional(B.nonCapturingGroup(...e))}static numberGroup(e,t,i,s="\\d"){return B.group(e,`${i||""}[${s}]${t}`)}}const YM="yearValue";class $p extends bl{static format(e=""){return B.numberGroup(B.groupName(e,YM),"{4}",void 0)}constructor(){super(YM,$p.format())}}const qM="monthValue";class Kp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,qM),"{1,2}",void 0)}constructor(){super(qM,Kp.format())}}const jM="dayValue";class Vd extends bl{static format(e=""){return B.numberGroup(B.groupName(e,jM),"{1,2}",void 0)}constructor(){super(jM,Vd.format())}}const ZM="hourValue";class Wd extends bl{static format(e=""){return B.numberGroup(B.groupName(e,ZM),"{1,2}",void 0)}constructor(){super(ZM,Wd.format())}}const JM="minuteValue";class Xp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,JM),"{1,2}",void 0)}constructor(){super(JM,Xp.format())}}const QM="secondValue";class Yp extends bl{static format(e=""){return B.numberGroup(B.groupName(e,QM),"{1,2}",void 0)}constructor(){super(QM,Yp.format())}}const ex="timeshiftValue",tx="shiftHour",ix="shiftMinute";class fu extends vl{static format(e=""){return XM.map(t=>t.name).join("|")+"|"+B.nonCapturingGroup(B.group(e+tx,B.numberGroup(B.groupName(e,ex),"{2}","[+-]")),B.optionalNonCapturingGroup(":?",B.numberGroup(B.groupName(e,ix),"{2}",void 0)))}constructor(){super(ex,fu.format())}parse(e,t){let i=0;const s=XM.find(n=>n.name===e);if(s){if(typeof s.timeshift=="function")try{return s.timeshift(t??{})}catch(n){throw new Nr(`The time zone ${e} depends on the date: ${n.message}`)}e=s.timeshift}if(e!=="Z"){const n=this.regexGroups(e),r=n[tx];r&&(i+=parseInt(r,10)*60);const a=n[ix];a&&(i+=parseInt(a,10))}return i}}const sx="year",nx="month",rx="day",ax="hour",ox="minute",lx="second",cx="millisecond",hx="timeshift";class Zc extends vl{static format(e=""){return B.group(B.groupName(e,sx),$p.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,nx),Kp.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,rx),Vd.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,ax),Wd.format(e)),":?",B.group(B.groupName(e,ox),Xp.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,lx),Yp.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,cx),"\\d+"))),"\\s*",B.optionalGroup(B.groupName(e,hx),fu.format(e)))))}constructor(){super("date",Zc.format())}parse(e){const t=this.regexGroups(e),i=t[sx],s=t[nx],n=t[rx],r=t[ax],a=t[ox],o=t[lx],l=t[cx],h=t[hx],d=i?new lu($p.read(i)):void 0,u=s?Kp.read(s):void 0;return{year:d,month:u?new cu(u,Md.create(u.value,d?.value)):void 0,day:n?new hu(Vd.read(n)):void 0,hour:r?new du(Wd.read(r)):void 0,minute:a?new uu(Xp.read(a)):void 0,second:o?new pu(Yp.read(o)):void 0,millisecond:l?Ec.parseFraction(l):void 0,timeshift:h?mc.fromString(h,new fu,{year:d?.value,month:u?.value,day:n?Vd.read(n).value:void 0,hour:r?Wd.read(r).value:void 0}):void 0}}}const dx="years",yv="months",b_="days",ux="hours",px="minutes",fx="seconds";class bw extends vl{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,dx),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,yv),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,b_),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,ux),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,px),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,fx),"+",void 0,"\\d"),"S")}constructor(){super("duration",bw.format())}parseGroups(e){return{years:e[dx],months:e[yv],days:e[yv],hours:e[ux],minutes:e[px],seconds:e[fx]}}}const wv="start",Mv="end";class yw extends vl{static format=B.group(wv,Zc.format(wv))+"/"+B.group(Mv,Zc.format(Mv));constructor(){super("interval",yw.format)}parse(e){const t=this.regexGroups(e),i=t[wv],s=t[Mv];return{start:i?yn.fromString(i,new Zc):void 0,end:s?yn.fromString(s,new Zc):void 0}}}We.register(yn,()=>new Zc);We.register(hu,()=>new Vd);We.register(La,()=>new bw);We.register(du,()=>new Wd);We.register(Gp,()=>new yw);We.register(uu,()=>new Xp);We.register(cu,()=>new Kp);We.register(pu,()=>new Yp);We.register(mc,()=>new fu);We.register(lu,()=>new $p);class Qi extends bl{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=Qi.uncertainGroup+Qi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return B.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(B.groupName(Qi.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(Qi.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(Qi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return B.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let s=0,n;for(n=0;n<t.length;n++){const l=t[n];if(l==="X")break;s=s*10+parseInt(l,10)}if(n<t.length){let l=1;for(let u=0;u<t.length-n;u++)l*=10;const h=i*s*l,d=h+l-1;s={start:h,end:d}}else s*=i;const r=e[B.groupName(Qi.uncertainAndApproximateGroup,this.name)],a=e[B.groupName(Qi.approximateGroup,this.name)]||r,o=e[B.groupName(Qi.uncertainGroup,this.name)]||r;return{value:s,approximate:a?!!a:!1,uncertain:o?!!o:!1}}}const mx="yearValue";class qp extends Qi{constructor(){super(mx,qp.format())}static format(e=""){return"Y?"+Qi.numberFormat(B.groupName(e,mx),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const gx="monthValue";class jp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,gx),"{1,2}",void 0)}constructor(){super(gx,jp.format())}}const vx="dayValue";class Zp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,vx),"{1,2}",void 0)}constructor(){super(vx,Zp.format())}}const bx="hourValue";class Jp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,bx),"{1,2}",void 0)}constructor(){super(bx,Jp.format())}}const yx="minuteValue";class Qp extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,yx),"{1,2}",void 0)}constructor(){super(yx,Qp.format())}}const wx="secondValue";class ef extends Qi{static format(e=""){return Qi.numberFormat(B.groupName(e,wx),"{1,2}",void 0)}constructor(){super(wx,ef.format())}}class tf extends fu{}class hs extends vl{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=hs.format()){super("date",e)}static format(e=""){return B.group(B.groupName(e,hs.yearGroup),qp.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.monthGroup),jp.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,hs.dayGroup),Zp.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,hs.hourGroup),Jp.format(e)),":",B.group(B.groupName(e,hs.minuteGroup),Qp.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,hs.secondGroup),ef.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,hs.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,hs.timeshiftGroup),tf.format(e)))))}parseGroups(e){const t=e[hs.millisecondGroup],i=t?Ec.parseFraction(t):void 0,s=e[hs.secondGroup],n=s?tc.fromString(s,new ef):void 0,r=e[hs.minuteGroup];let a;r&&(a=ec.fromString(r,new Qp),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[hs.hourGroup];let l;o&&(l=Ql.fromString(o,new Jp),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[hs.dayGroup];let d;h&&(d=Jl.fromString(h,new Zp),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[hs.monthGroup];let p;u&&(p=Zl.fromString(u,new jp),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[hs.yearGroup];let m;f&&(m=jl.fromString(f,void 0,new qp),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[hs.timeshiftGroup],v=g?yh.fromString(g,new tf,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:v}}}const Mx="years",xx="months",Ex="days",Sx="hours",Ax="minutes",Tx="seconds";class Jc extends Qi{static format(e=""){return"P"+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Mx),"+",void 0,"\\d"),"Y")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,xx),"+",void 0,"\\d"),"MM")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Ex),"+",void 0,"\\d"),"D")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Sx),"+",void 0,"\\d"),"H")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Ax),"+",void 0,"\\d"),"M")+B.optionalNonCapturingGroup(B.numberGroup(B.groupName(e,Tx),"+",void 0,"\\d"),"S")+this.formatSuffix(e)}constructor(){super("duration",Jc.format())}parseGroups(e){return{years:e[Mx],months:e[xx],days:e[Ex],hours:e[Sx],minutes:e[Ax],seconds:e[Tx],uncertain:!!e[Qi.uncertainGroup],approximate:!!e[Qi.approximateGroup]}}}const y_="dates",xv="start",Ev="end",Ix="durations",Sv="durationMin",Av="durationMax";class ww extends vl{static format=B.group(y_,B.optionalGroup(xv,B.group("openStart","\\.\\.")+"|"+hs.format(xv))+"/"+B.optionalGroup(Ev,B.group("openEnd","\\.\\.")+"|"+hs.format(Ev)))+"|"+B.group(Ix,B.group(Sv,Jc.format(Sv))+"/"+B.group(Av,Jc.format(Av)));constructor(e="interval",t=ww.format){super(e,t)}parseGroups(e){let t,i;if(e[Ix]){const n=e[Sv];t=Xs.fromString(n,new Jc);const r=e[Av];i=Xs.fromString(r,new Jc)}else{const n=e[xv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=Or.fromString(n,new hs)}const r=e[Ev];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Or.fromString(r,new hs)}}return{start:t,end:i}}}We.register(Or,()=>new hs);We.register(Jl,()=>new Zp);We.register(Xs,()=>new Jc);We.register(Ql,()=>new Jp);We.register(Vp,()=>new ww);We.register(ec,()=>new Qp);We.register(Zl,()=>new jp);We.register(tc,()=>new ef);We.register(yh,()=>new tf);We.register(jl,()=>new qp);class li extends Qi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=li.uncertainGroup+li.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(B.groupName(li.uncertainGroup,e),"?")+this.qualifierFormat(B.groupName(li.approximateGroup,e),"~")+this.qualifierFormat(B.groupName(li.uncertainAndApproximateGroup,e),"%")+Qi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[B.groupName(li.uncertainAndApproximateGroup,this.name)];return(e[B.groupName(li.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[B.groupName(li.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const ku="yearValue",_x="exp",Dx="signif";class sf extends li{constructor(){super(ku,sf.format())}static format(e=""){return"Y?"+B.nonCapturingGroup(B.group(B.groupName(e,_x),"[-]?\\d+E\\d+")+"|"+li.numberFormat(B.groupName(e,ku),"+","[-]?")+B.optionalGroup(B.groupName(e,Dx),"S\\d+"))}parseGroups(e){const t=e[_x];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),l=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[ku]=l.toString()}const i=e[Dx],s=e[ku];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:o}=this.getValueAndSign(e);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";e[ku]=(o<0?"-":"")+l}const n=super.parseGroups(e);return i&&(n.value.estimate=parseInt(s,10)),n}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const kx="monthValue";class nf extends li{static format(e=""){return li.numberFormat(B.groupName(e,kx),"{1,2}",void 0)}constructor(){super(kx,nf.format())}}const Rx="dayValue";class rf extends li{static format(e=""){return li.numberFormat(B.groupName(e,Rx),"{1,2}",void 0)}constructor(){super(Rx,rf.format())}}const Cx="hourValue";class af extends li{static format(e=""){return li.numberFormat(B.groupName(e,Cx),"{1,2}",void 0)}constructor(){super(Cx,af.format())}}const Ox="secondValue";class of extends li{static format(e=""){return li.numberFormat(B.groupName(e,Ox),"{1,2}",void 0)}constructor(){super(Ox,of.format())}}const Lx="minuteValue";class lf extends li{static format(e=""){return li.numberFormat(B.groupName(e,Lx),"{1,2}",void 0)}constructor(){super(Lx,lf.format())}}class w_ extends tf{}class vi extends vl{static yearGroup=hs.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",vi.format())}static format(e=""){return B.group(B.groupName(e,vi.yearGroup),sf.format(e))+B.optionalNonCapturingGroup("-",B.group(B.groupName(e,vi.monthGroup),nf.format(e)),B.optionalNonCapturingGroup("-",B.group(B.groupName(e,vi.dayGroup),rf.format(e)),B.optionalNonCapturingGroup("[T ]",B.group(B.groupName(e,vi.hourGroup),af.format(e)),":",B.group(B.groupName(e,vi.minuteGroup),lf.format(e)),B.optionalNonCapturingGroup(":",B.group(B.groupName(e,vi.secondGroup),of.format(e)),B.optionalNonCapturingGroup("[.,]",B.group(B.groupName(e,vi.millisecondGroup),"\\d+"))),B.optionalGroup(B.groupName(e,vi.timeshiftGroup),w_.format(e)))))}parseGroups(e){const t=e[vi.millisecondGroup],i=t?Ec.parseFraction(t):void 0,s=e[vi.secondGroup];let n;s&&(n=sl.fromString(s,void 0,new of),n.uncertain=n?.uncertain||!1,n.approximate=n?.approximate||!1);const r=e[vi.minuteGroup];let a;r&&(a=il.fromString(r,new lf),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[vi.hourGroup];let l;o&&(l=tl.fromString(o,new af),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[vi.dayGroup];let d;h&&(d=el.fromString(h,new rf),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[vi.monthGroup];let p;u&&(p=Qo.fromString(u,new nf),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[vi.yearGroup];let m;f&&(m=Jo.fromString(f,void 0,new sf),m.uncertain=m.uncertain||p?.uncertain||!1,m.approximate=m.approximate||p?.approximate||!1);const g=e[vi.timeshiftGroup],v=g?hT.fromString(g,new tf,{year:m?.value,month:p?.value,day:d?.value,hour:l?.value}):void 0;return{year:m,month:p,day:d,hour:l,minute:a,second:n,millisecond:i,timeshift:v}}}const Px="durationValue";class Mw extends li{static format(e=""){return"^"+li.numberFormat(B.groupName(e,Px),"+",void 0)}constructor(){super(Px,Mw.format())}}class M_ extends mw{millisecond=new Ni("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new Ni("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Ni("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new Ni("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new Ni("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new Ni("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new Ni("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Rh=new M_;class ut extends li{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new Mw;static componentFormat(e,t,i,s,n=""){const r=B.group(B.groupName(e,ut.quantityGroup(t)),li.numberFormat(B.groupName(e,i),"+",void 0,"\\d"));return B.group(B.groupName(e,t),r,s,n)}static quantityGroup(e){return e+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",ut.format())}static format(e=""){const t=B.groupName(e,ut.durationGroup);return this.qualifierFormat(B.groupName(li.uncertainGroup,t),"?")+this.qualifierFormat(B.groupName(li.approximateGroup,t),"~")+this.qualifierFormat(B.groupName(li.uncertainAndApproximateGroup,t),"%")+"P"+B.optional(ut.componentFormat(e,ut.yearsGroup,vi.yearGroup,"Y"))+B.optionalNonCapturingGroup(ut.componentFormat(e,ut.monthsGroup,vi.monthGroup,"MM")+"|"+ut.componentFormat(e,ut.isoMonthsGroup,"isoMonth","M",ut.isoMonthsLookahead))+B.optional(ut.componentFormat(e,ut.daysGroup,vi.dayGroup,"D"))+"T?"+B.optional(ut.componentFormat(e,ut.hoursGroup,vi.hourGroup,"H"))+B.optional(ut.componentFormat(e,ut.minutesGroup,vi.minuteGroup,"M"))+B.optional(ut.componentFormat(e,ut.secondsGroup,vi.secondGroup,"S"))+B.optionalGroup(B.groupName(e,ut.suffixGroup),"[?~%]")}static parseComponent(e,t,i){const s=ut.componentParser.parse(e);return new t(s,i)}parseGroups(e){const t=e[ut.quantityGroup(ut.secondsGroup)];let i;t&&(i=ut.parseComponent(t,sl,Rh.second),i.uncertain=!!e[B.groupName(li.uncertainGroup,ut.secondsGroup)]||!1,i.approximate=!!e[B.groupName(li.approximateGroup,ut.secondsGroup)]||!1);const s=e[ut.quantityGroup(ut.minutesGroup)];let n;s&&(n=ut.parseComponent(s,il,Rh.minute),n.uncertain=n.uncertain||i?.uncertain||!1,n.approximate=n.approximate||i?.approximate||!1);const r=e[ut.quantityGroup(ut.hoursGroup)];let a;r&&(a=ut.parseComponent(r,tl,Rh.hour),a.uncertain=a.uncertain||n?.uncertain||!1,a.approximate=a.approximate||n?.approximate||!1);const o=e[ut.quantityGroup(ut.daysGroup)];let l;o&&(l=ut.parseComponent(o,el,Rh.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=e[ut.quantityGroup(ut.monthsGroup)]||e[ut.quantityGroup(ut.isoMonthsGroup)];let d;h&&(d=ut.parseComponent(h,Qo,Rh.month),d.uncertain=d.uncertain||l?.uncertain||!1,d.approximate=d.approximate||l?.approximate||!1);const u=e[ut.quantityGroup(ut.yearsGroup)];let p;u&&(p=ut.parseComponent(u,Jo,Rh.year),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[ut.suffixGroup],m=!!e[B.groupName(li.uncertainAndApproximateGroup,ut.durationGroup)]||f==="%",g=m||!!e[B.groupName(li.uncertainGroup,ut.durationGroup)]||f==="?",v=m||!!e[B.groupName(li.approximateGroup,ut.durationGroup)]||f==="~";return{years:p,months:d,days:l,hours:a,minutes:n,seconds:i,uncertain:g,approximate:v}}}const x_="dates",Tv="start",Iv="end",Nx="durations",_v="durationMin",Dv="durationMax";class Xg extends vl{static format=B.group(x_,B.optionalGroup(Tv,B.group("openStart","\\.\\.")+"|"+vi.format(Tv))+"/"+B.optionalGroup(Iv,B.group("openEnd","\\.\\.")+"|"+vi.format(Iv)))+"|"+B.group(Nx,B.group(_v,ut.format(_v))+"/"+B.group(Dv,ut.format(Dv)));constructor(e="interval",t=Xg.format){super(e,t)}parseGroups(e){let t,i;if(e[Nx]){const n=e[_v];t=Ws.fromString(n,new ut);const r=e[Dv];i=Ws.fromString(r,new ut)}else{const n=e[Tv];switch(n){case void 0:t=null;break;case"..":t=void 0;break;default:t=pr.fromString(n,new vi)}const r=e[Iv];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=pr.fromString(r,new vi)}}return{start:t,end:i}}}class E_{parse(e){e=e.trim();const t=e.startsWith("["),s=e.substring(1,e.length-1).split(","),n=[];for(const r of s){let a;r.includes("..")?a=Wp.fromString(r.replace("..","/"),new Xg):a=pr.fromString(r,new vi),n.push(a)}return{values:n,exclusive:t}}}We.register(pr,()=>new vi);We.register(el,()=>new rf);We.register(Ws,()=>new ut);We.register(tl,()=>new af);We.register(Wp,()=>new Xg);We.register(il,()=>new lf);We.register(Qo,()=>new nf);We.register(sl,()=>new of);We.register(G0,()=>new E_);We.register(Jo,()=>new sf);class Ls{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[Ls.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>Ls.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(Ls.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(l=>l===i))!==null&&s!==void 0?s:Object.keys(a).find(l=>Ls.base(l)===Ls.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}Ls.any=new Ls([]);var Fx;(function(c){c.abductee="abductee",c.actor="actor",c.artist="artist",c.anthropologist="anthropologist",c.archeologist="archeologist",c.astronaut="astronaut",c.astronomer="astronomer",c.astrologist="astrologist",c.astrophysicist="astrophysicist",c.banker="banker",c.barman="barman",c.biologist="biologist",c.biochemist="biochemist",c.biophysicist="biophysicist",c.bishop="bishop",c.businessman="businessman",c.botanist="botanist",c.cameraman="cameraman",c.chemist="chemist",c.contactee="contactee",c.cryptozoologist="cryptozoologist",c.dentist="dentist",c.director="director",c.diplomat="diplomat",c.diver="diver",c.electronics="electronics",c.engineer="engineer",c.ethnologist="ethnologist",c.exobiologist="exobiologist",c.farmer="farmer",c.firefighter="firefighter",c.flightAttendant="flightAttendant",c.geologist="geologist",c.geophysicist="geophysicist",c.geographer="geographer",c.historian="historian",c.houseWife="houseWife",c.hypnotherapist="hypnotherapist",c.illusionist="illusionist",c.journalist="journalist",c.judge="judge",c.lawyer="lawyer",c.leader="leader",c.librarian="librarian",c.logger="logger",c.mathematician="mathematician",c.mechanic="mechanic",c.meteorologist="meteorologist",c.military="military",c.musician="musician",c.neurologist="neurologist",c.neuroscientist="neuroscientist",c.neuropsychiatrist="neuropsychiatrist",c.nurse="nurse",c.oceanographer="oceanographer",c.painter="painter",c.parapsychologist="parapsychologist",c.philosopher="philosopher",c.photographer="photographer",c.physician="physician",c.physicist="physicist",c.pilot="pilot",c.politician="politician",c.policeman="policeman",c.priest="priest",c.producer="producer",c.prospector="prospector",c.psychologist="psychologist",c.psychiatrist="psychiatrist",c.radioastronomer="radioastronomer",c.radioamateur="radioamateur",c.salesman="salesman",c.sailor="sailor",c.sociologist="sociologist",c.softwareEngineer="softwareEngineer",c.stuntman="stuntman",c.taxiDriver="taxiDriver",c.teacher="teacher",c.telegrapher="telegrapher",c.truckDriver="truckDriver",c.ufologist="ufologist",c.ufoWitness="ufoWitness",c.ufoWitness2="ufoWitness2",c.worker="worker",c.writer="writer"})(Fx||(Fx={}));var Ux;(function(c){c.neutral="neutral",c.male="male",c.female="female"})(Ux||(Ux={}));class S_ extends Error{constructor(e,t){super(e),this.cause=t}}class xw extends S_{constructor(e=xw.defaultMessage,t){super(e,t)}}xw.defaultMessage="Assertion failed";var Bx;(function(c){c.country="country",c.region="region",c.department="department",c.city="city",c.company="company"})(Bx||(Bx={}));var zx;(function(c){c.at="at",c.au="au",c.ar="ar",c.be="be",c.br="br",c.ca="ca",c.ch="ch",c.cn="cn",c.cl="cl",c.co="co",c.cy="cy",c.de="de",c.dk="dk",c.do="do",c.dz="dz",c.gr="gr",c.ec="ec",c.eg="eg",c.es="es",c.fi="fi",c.fr="fr",c.ga="ga",c.ge="ge",c.hu="hu",c.in="in",c.ie="ie",c.ir="ir",c.il="il",c.it="it",c.jp="jp",c.kr="kr",c.ma="ma",c.mx="mx",c.my="my",c.mz="mz",c.nl="nl",c.no="no",c.nz="nz",c.pa="pa",c.pe="pe",c.ph="ph",c.pl="pl",c.pt="pt",c.ro="ro",c.ru="ru",c.sc="sc",c.tr="tr",c.ua="ua",c.uk="uk",c.us="us",c.sa="sa",c.se="se",c.su="su",c.tn="tn",c.tw="tw",c.ve="ve",c.za="za"})(zx||(zx={}));class A_{static of(e){if(!(!e||e.length===0))return e.some(t=>t.outcome==="fails"&&t.against!=="supposed")?"incompatible":e.some(t=>t.outcome!=="holds")?"unsettled":"compatible"}}/**
|
|
417
417
|
@preserve
|
|
418
418
|
|
|
419
419
|
Astronomy library for JavaScript (browser and Node.js).
|
|
@@ -4607,7 +4607,7 @@ button.open { display: inline-flex; align-items: center; gap: 6px; cursor: point
|
|
|
4607
4607
|
.option input { margin: 2px 0 0; }
|
|
4608
4608
|
${Ys.css(".menu")}
|
|
4609
4609
|
.menu:popover-open { position-area: bottom span-left; margin: .35em 0 0; }
|
|
4610
|
-
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(Wc.TAG)||customElements.define(Wc.TAG,Wc)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=Ps.preferencesFor(this),this.language=Fa([...this.preferences],Pa),this.messages=await A5.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=Wc.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=e.hint,i.setAttribute("aria-label",e.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=Wc.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:e.button}));const s=document.createElement("div");s.className="menu",s.setAttribute("role","menu"),Ys.attach(i,s);const n=[["html",e.html,e.htmlHint],["print",e.print,e.printHint],["json",e.json,e.jsonHint],["csv",e.csv,e.csvHint]];s.append(...n.map(([o,l,h])=>{const d=document.createElement("button");return d.type="button",d.setAttribute("role","menuitem"),d.append(Object.assign(document.createElement("strong"),{textContent:l}),Object.assign(document.createElement("small"),{textContent:h})),d.addEventListener("click",()=>void this.export(o,s)),d}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:e.pictures}),Object.assign(document.createElement("small"),{textContent:e.picturesHint})),r.append(this.withPictures,a),s.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),s.append(this.status),i.addEventListener("click",()=>Ys.show(s,s.hidden)),this.shadowRoot.replaceChildren(t,i,s)}async export(e,t){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:s},n]=await Promise.all([Y(()=>import("./CaseReportExport-COqBs7VN.js"),[],import.meta.url),this.source()]);await s.make(e,n,this.language,this.preferences,this.withPictures?.checked??!1,(r,a)=>{this.status.textContent=i.drawing.replace("{done}",String(r)).replace("{total}",String(a))}),this.status.hidden=!0,Ys.show(t,!1)}catch{this.status.textContent=i.failed}}}}const vN=Fi.catalog({en:()=>Y(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(c=>c.readingCheckTexts_en),fr:()=>Y(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(c=>c.readingCheckTexts_fr),es:()=>Y(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(c=>c.readingCheckTexts_es),it:()=>Y(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(c=>c.readingCheckTexts_it)});class lr{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Ji.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Ji.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new lr(a,new URL("case.json",n).href),l=o.tracks[0];return l.recording=e,l.base={url:s},l.event.id=o.proposedId(l),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Ji.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const l={type:"event",eventType:Ji.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],l],this.caseChanged=!0,l}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}static sealed(e){return e.sealed===!0}seal(e,t){t?e.event.sealed=!0:delete e.event.sealed,this.caseChanged=!0}clone(e,t){if(!e.recording)return;const i=e.kind==="reading"?this.accountOf(e):void 0;if(e.kind==="reading"&&!i)return;const s=t??e.event.title;return this.addObservation(structuredClone(e.recording),e.event.time,s,i?{account:i,by:e.event.by}:void 0)}keep(e,t,i=!1){!i&&lr.sealed(e.event)||(t=Mn.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Ji.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(l=>l.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Ji.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Ji.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!lr.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(l=>s(l)?t:l);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(l=>l!==void 0&&s(l)?t:l);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Ji.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let l=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${l}.json`)||o.has(`${n.id??r}-interpretation-${l}`);)l++;const h=`interpretation-${r}-${l}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:g,sources:v,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),S={version:4,id:`${n.id??r}-interpretation-${l}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},E={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],E],this.caseChanged=!0;const A={event:E,url:new URL(E.url,this.url).href,kind:"reading",recording:S};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let l=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(l)||r.has(h);m++)l=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+l};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(lr.sealed(e.event))return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading"||lr.sealed(e.event))return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
4610
|
+
`;source;messages;language="en";preferences=["en"];status;withPictures;static register(){customElements.get(Wc.TAG)||customElements.define(Wc.TAG,Wc)}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.messages||this.loadLocale()}async loadLocale(){this.preferences=Ps.preferencesFor(this),this.language=Fa([...this.preferences],Pa),this.messages=await A5.load(this.language),this.draw()}draw(){const e=this.messages,t=document.createElement("style");t.textContent=Wc.CSS;const i=document.createElement("button");i.type="button",i.className="open",i.setAttribute("part","button"),i.title=e.hint,i.setAttribute("aria-label",e.hint),i.setAttribute("aria-haspopup","menu"),i.innerHTML=Wc.ICON,this.getAttribute("variant")==="pill"&&i.append(Object.assign(document.createElement("span"),{textContent:e.button}));const s=document.createElement("div");s.className="menu",s.setAttribute("role","menu"),Ys.attach(i,s);const n=[["html",e.html,e.htmlHint],["print",e.print,e.printHint],["json",e.json,e.jsonHint],["csv",e.csv,e.csvHint]];s.append(...n.map(([o,l,h])=>{const d=document.createElement("button");return d.type="button",d.setAttribute("role","menuitem"),d.append(Object.assign(document.createElement("strong"),{textContent:l}),Object.assign(document.createElement("small"),{textContent:h})),d.addEventListener("click",()=>void this.export(o,s)),d}));const r=document.createElement("label");r.className="option",this.withPictures=Object.assign(document.createElement("input"),{type:"checkbox"});const a=document.createElement("span");a.append(Object.assign(document.createElement("strong"),{textContent:e.pictures}),Object.assign(document.createElement("small"),{textContent:e.picturesHint})),r.append(this.withPictures,a),s.append(r),this.status=Object.assign(document.createElement("p"),{className:"status",hidden:!0}),this.status.setAttribute("role","status"),s.append(this.status),i.addEventListener("click",()=>Ys.show(s,s.hidden)),this.shadowRoot.replaceChildren(t,i,s)}async export(e,t){const i=this.messages;if(this.source){this.status.textContent=i.working,this.status.hidden=!1;try{const[{CaseReportExport:s},n]=await Promise.all([Y(()=>import("./CaseReportExport-QyaWB9n9.js"),[],import.meta.url),this.source()]);await s.make(e,n,this.language,this.preferences,this.withPictures?.checked??!1,(r,a)=>{this.status.textContent=i.drawing.replace("{done}",String(r)).replace("{total}",String(a))}),this.status.hidden=!0,Ys.show(t,!1)}catch{this.status.textContent=i.failed}}}}const vN=Fi.catalog({en:()=>Y(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(c=>c.readingCheckTexts_en),fr:()=>Y(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(c=>c.readingCheckTexts_fr),es:()=>Y(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(c=>c.readingCheckTexts_es),it:()=>Y(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(c=>c.readingCheckTexts_it)});class lr{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Ji.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,s,n){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Ji.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new lr(a,new URL("case.json",n).href),l=o.tracks[0];return l.recording=e,l.base={url:s},l.event.id=o.proposedId(l),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Ji.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const l={type:"event",eventType:Ji.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],l],this.caseChanged=!0,l}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}static sealed(e){return e.sealed===!0}seal(e,t){t?e.event.sealed=!0:delete e.event.sealed,this.caseChanged=!0}clone(e,t){if(!e.recording)return;const i=e.kind==="reading"?this.accountOf(e):void 0;if(e.kind==="reading"&&!i)return;const s=t??e.event.title;return this.addObservation(structuredClone(e.recording),e.event.time,s,i?{account:i,by:e.event.by}:void 0)}keep(e,t,i=!1){!i&&lr.sealed(e.event)||(t=Mn.recording(t),e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title))}replaceJson(e){const i=(e.events??[]).filter(n=>n.eventType===Ji.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(l=>l.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Ji.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Ji.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!lr.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(l=>s(l)?t:l);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(l=>l!==void 0&&s(l)?t:l);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Ji.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let l=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${l}.json`)||o.has(`${n.id??r}-interpretation-${l}`);)l++;const h=`interpretation-${r}-${l}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:m,description:g,sources:v,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),S={version:4,id:`${n.id??r}-interpretation-${l}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},E={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],E],this.caseChanged=!0;const A={event:E,url:new URL(E.url,this.url).href,kind:"reading",recording:S};return this.tracks.push(A),A}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let l=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(l)||r.has(h);m++)l=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.by}:{},...i!==void 0?{title:i}:{},url:u+l};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};if(lr.sealed(e.event))return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(s=>s!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading"||lr.sealed(e.event))return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
4611
4611
|
`})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([o,l])=>e&&o.url!==void 0&&(t||this.transcriptChanged(l))).map(([o,l])=>({path:s(new URL(o.url,this.url).href),content:l.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
|
|
4612
4612
|
`},...n,...a]}}class _f{constructor(e,t,i,s){this.button=e,this.onPick=i,this.idOf=s;const n=this.panel=e.ownerDocument.createElement("div");n.id=t,n.className="add-menu",n.setAttribute("popover",""),n.setAttribute("role","menu");const r=`--add-menu-${t}`;e.style.setProperty("anchor-name",r),n.style.setProperty("position-anchor",r),e.setAttribute("popovertarget",t),e.setAttribute("aria-haspopup","menu"),e.after(n)}static CSS=`
|
|
4613
4613
|
.add-menu { padding: .3em 0; border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 4px; background: Canvas; color: CanvasText;
|
|
@@ -8859,9 +8859,9 @@ canvas[data-cursor="rotate"] {
|
|
|
8859
8859
|
`;class ph{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:s,lng:n,headingDeg:r}=i.pose;s===void 0||n===void 0||t.push({t:i.t,lat:s,lng:n,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new ph(t)}static TRAVEL_M=50;get travels(){return this.spanM>ph.TRAVEL_M}get moved(){return this.spanM>ph.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(dt(t,e.east,t,e.west).x),Math.abs(dt(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:s}=this.center,n=Math.max(this.spanM*(1+t),e)/2;return{north:mr(0,-n,i,s).lat,south:mr(0,n,i,s).lat,east:mr(n,0,i,s).lng,west:mr(-n,0,i,s).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class aa{constructor(e,t){this.rotationPassed=e,this.scale=t}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(e){if(e.instrument.mounted)return;const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>aa.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new aa(Math.max(1-(e.instrument.stabilization??0),aa.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,s=(d,u)=>Math.sin(2*Math.PI*d*t+u),[n,r,a,o,l,h]=aa.HZ;return{eastM:i*aa.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*aa.SWAY_M*(.6*s(a,2.2)+.4*s(l,.8)),upM:i*aa.BREATH_M*s(r,0),yawDeg:i*this.rotationPassed*aa.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*aa.DRIFT_PITCH_DEG*(.5*s(r,1.6)+.5*s(a,.4)),rollDeg:i*this.rotationPassed*aa.DRIFT_ROLL_DEG*s(n,2.9)}}}class Ti{constructor(e,t){this.stretches=e,this.rotationPassed=t}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(e){const t=ph.of(e);if(!t||t.points.length<2)return;const i=[];let s=0;for(let n=1;n<t.points.length;n++){const r=t.points[n-1],a=t.points[n],o=(a.t-r.t)/1e3;if(o<=0)continue;const l=dt(a.lat,a.lng,r.lat,r.lng),h=l.x,d=-l.z,u=Math.hypot(h,d),p=u/o,f=Ti.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:s,rampsIn:!0,rampsOut:!0}),s+=f*o}for(let n=0;n<i.length;n++){const r=i[n-1],a=i[n+1];i[n].rampsIn=r===void 0||r.stepHz===0,i[n].rampsOut=a===void 0||a.stepHz===0}if(i.some(n=>n.stepHz>0))return new Ti(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const s=Ti.of(e)?.offsetAt(t)??Ti.STILL;return i?s:Ti.add(s,aa.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Ti.SLOWEST_WALK_M_PER_S||e>Ti.FASTEST_WALK_M_PER_S?0:Ti.REFERENCE_STEP_HZ*Math.pow(e/Ti.REFERENCE_SPEED_M_PER_S,Ti.CADENCE_EXPONENT)}offsetAt(e){return Ti.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Ti.REFERENCE_SPEED_M_PER_S,s=(a,o,l,h)=>{if(a<0||a>Ti.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/Ti.JOLT_DECAY_S)*Math.sin(2*Math.PI*Ti.JOLT_HZ*d),p=h*o*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*l*i*u*this.rotationPassed,yawDeg:0}},n=t.rampsOut?s(e-t.endMs,Ti.STOP_LURCH_M,Ti.STOP_PITCH_DEG,1):void 0;if(n)return n;const r=t.rampsIn?s(e-t.startMs,Ti.START_LURCH_M,Ti.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return Ti.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(t,e),r=Ti.SWAY_M*n*Math.cos(s/2),a=n*this.rotationPassed*t.speedMPerS/Ti.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Ti.RISE_M_PER_M_PER_S*t.speedMPerS*n*Math.cos(s),rollDeg:Ti.HEAD_ROLL_DEG*a*Math.cos(s/2),pitchDeg:-1.25*a*Math.cos(s),yawDeg:Ti.HEAD_YAW_DEG*a*Math.cos(s/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,s=Math.min(i,(e.endMs-e.startMs)/2);if(s<=0)return 1;const n=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?n/s:1,e.rampsOut?r/s:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class $N{constructor(e,t){this.timeline=e,this.onFrame=t}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const s=this.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}this.onFrame(e,t)}}class Qr{static sessionDeclared=!1;static isLive(e){return e!==void 0&&typeof AudioContext<"u"&&e instanceof AudioContext}static unlock(e){if(Qr.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(Qr.sessionDeclared||typeof navigator>"u")){Qr.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const jS=.05,ZS=.08,JS=2,QS=3,KN=14,XN=.02;class e2{context;constructor(e){this.context=e}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}Qr.isLive(this.context)&&Qr.unlock(this.context)}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),Qr.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const s=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,jS);for(const{param:n,ratio:r}of e.pitch)n.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),s,jS)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const s=e.createOscillator();s.type="sawtooth";const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(n),s.connect(n),n.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(e,t){const i=e.createOscillator();i.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const n=e.createGain(),r=e.createGain();return r.gain.value=0,s.connect(n).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const n=e.createGain();return n.gain.value=0,i.connect(s).connect(n).connect(this.output(e)),i.start(),{key:t,nodes:[s,n],sources:[i],volumeParam:n.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const n=e.createGain();n.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const a=e.createGain();return a.gain.value=0,r.connect(a).connect(n.gain),i.connect(s).connect(n).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[s,n,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const s=this.context;if(!s)return;let n;try{n=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);return}if(i!==this.voiceToken||!this.context)return;const r=s.createBufferSource();r.buffer=n,r.loop=!0;const a=s.createGain();a.gain.value=0,r.connect(a).connect(this.output(s)),r.start(),this.voice={key:t,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*JS),e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*JS),e.sampleRate),i=t.getChannelData(0);let s=0,n=0;for(let r=0;r<i.length;r++)s=(s+.02*(Math.random()*2-1))/1.02,i[r]=s,n=Math.max(n,Math.abs(s));if(n>0)for(let r=0;r<i.length;r++)i[r]/=n;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*QS),e.sampleRate),i=t.getChannelData(0),s=Math.max(1,Math.floor(XN*e.sampleRate)),n=Math.round(QS*KN);for(let r=0;r<n;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let l=0;l<s&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],o*(1-l/s))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,ZS/3);const s=i+ZS;for(const n of e.sources){n.onended=()=>{n.disconnect();for(const r of e.nodes)r.disconnect()};try{n.stop(s)}catch{n.disconnect();for(const r of e.nodes)r.disconnect()}}}}class kf{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(e,t=kf.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(s=>` ${kf.text(s)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
8860
8860
|
${i.join(`
|
|
8861
8861
|
`)}`)}}class oa{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,s){if(!oa.isObject(e)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:oa.typeOf(e)});return}for(const[n,r]of Object.entries(e)){const a=i?`${i}.${n}`:n,o=t[n];o?this.field(r,o,a,s):s.push({kind:"unknown-key",path:a})}}field(e,t,i,s){if(oa.isStated(e)){this.field(e.value,t,i,s);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&s.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,s):oa.isObject(e)||s.push({kind:"wrong-type",path:i,expected:"object",found:oa.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((n,r)=>{const a=oa.isStated(n)?n.value:n;this.object(a,t.fields,`${i}.${r}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:oa.typeOf(e)});return;default:typeof e!==t.type?s.push({kind:"wrong-type",path:i,expected:t.type,found:oa.typeOf(e)}):typeof e=="number"&&(t.minimum!==void 0&&e<t.minimum||t.maximum!==void 0&&e>t.maximum)&&s.push({kind:"out-of-range",path:i,expected:`${t.minimum??"−∞"}–${t.maximum??"∞"}`,found:String(e)})}}static STATED_KEYS=new Set(["value","basis","rationale","how","range","source"]);static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return oa.isObject(e)&&"value"in e&&Object.keys(e).every(t=>oa.STATED_KEYS.has(t))}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class Vn{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,s=Math.max(0,e-i*1e3),n=Math.max(0,e-s);return{fromMs:s,toMs:e,ms:n,seconds:n/1e3}}static instants(e,t,i,s,n){if(!(s>0))return 1;const r=n>0?Vn.travelDegOver(e,t,i,i+s*1e3)/n/Vn.PIXELS_PER_INSTANT:0,a=Vn.flashesOver(e,s)*Vn.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(Vn.MAX_INSTANTS,o)}static travelDegOver(e,t,i,s){let n=0;for(const r of e){if(!r.track||r.track.length<2)continue;const a=Vn.directionAt(r,t,i),o=Vn.directionAt(r,t,s),l=Math.min(1,Math.max(-1,a.x*o.x+a.y*o.y+a.z*o.z));n=Math.max(n,Math.acos(l)*180/Math.PI)}return n}static flashesOver(e,t){let i=0;for(const s of e)for(const n of s.lights??[])n.pattern.kind==="flash"&&(i=Math.max(i,n.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const s=Zr(e,i),n=s.eastM,r=s.altitudeM-t,a=s.northM,o=Math.hypot(n,r,a);return o===0?{x:0,y:1,z:0}:{x:n/o,y:r/o,z:a/o}}static bodyInstants(e,t,i,s,n){if(!(s>i)||!(n>0))return 1;let r=0;for(const o of e){const l=Vn.bodyAt(o,i),h=Vn.bodyAt(o,s);if(!l||!h)continue;const d={x:l.eastM,y:l.upM-t,z:l.northM},u={x:h.eastM,y:h.upM-t,z:h.northM},p=Math.hypot(d.x,d.y,d.z),f=Math.hypot(u.x,u.y,u.z);if(p===0||f===0)continue;const m=Math.min(1,Math.max(-1,(d.x*u.x+d.y*u.y+d.z*u.z)/p/f));let g=Math.acos(m)*180/Math.PI,v=0;for(const b of Object.keys(h.motions))v=Math.max(v,Math.abs(h.motions[b]-(l.motions[b]??h.motions[b])));v>0&&(g+=v*2*(h.halfWidthM/Math.max(f,.001))*180/Math.PI),r=Math.max(r,g)}const a=Math.ceil(r/n/Vn.PIXELS_PER_INSTANT);return a<2?1:Math.min(Vn.MAX_INSTANTS,a)}static bodyAt(e,t){const i=e.track;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let s=0,n=i.length-1;for(;n-s>1;){const u=s+n>>1;i[u].t<=t?s=u:n=u}const r=i[s],a=i[n];if(r.eastM===void 0||r.northM===void 0||a.eastM===void 0||a.northM===void 0)return;const o=a.t>r.t?(t-r.t)/(a.t-r.t):0,l=(u,p)=>u+(p-u)*o,h={};for(const u of Object.keys(a.motions??{})){const p=r.motions?.[u],f=a.motions[u];h[u]=p===void 0?f:l(p,f)}const d=i.find(u=>u.sizeM)?.sizeM?.widthM??1;return{eastM:l(r.eastM,a.eastM),northM:l(r.northM,a.northM),upM:l(r.altitudeM??0,a.altitudeM??0),halfWidthM:d/2,motions:h}}}const eI=Math.PI/180,YN=180/Math.PI,qN=256,tI=19,jN=1.25;function iI(c,e){return 156543.03392*Math.cos(c*eI)/2**e}function sI(c,e){return iI(c,e)*qN}function ZN(c,e){let t=0;for(;t<tI&&sI(c,t+1)>=e;)t++;return t}function pM(c,e){return sI(c,e)}function nI(c,e){const t=e*jN;let i=0;for(;i<tI&&iI(c,i)>t;)i++;return i}function L0(c){const e=c*eI;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function rI(c,e,t){const i=2**t;return{x:(c+180)/360*i,y:L0(e)*i}}function aI(c,e,t){const i=L0(c.north),s=L0(c.south);return{x:(e-c.west)/(c.east-c.west),y:(L0(t)-i)/(s-i)}}function JN(c,e,t){const{x:i,y:s}=rI(c,e,t);return{x:Math.floor(i),y:Math.floor(s),z:t}}function QN(c){const e=2**c.z,t=c.x/e*360-180,i=(c.x+1)/e*360-180,s=t2(c.y,e);return{south:t2(c.y+1,e),north:s,west:t,east:i}}function t2(c,e){const t=c/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*YN}function oI(c,e,t,i){const s=JN(c,e,t),n=Math.floor(i/2),r=[];for(let l=-n;l<=n;l++)for(let h=-n;h<=n;h++)r.push({x:s.x+h,y:s.y+l,z:t});const a=r.map(QN),o={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:o}}const e8="#2ec4ff";class Kc{constructor(e){this.ctx=e}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(e,t){let i,s=1/0;for(const n of this.targets){const r=Math.hypot(n.x-e,n.y-t);r>n.radius||r>s||(i=n,s=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),this.paintTraces(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const s=aI(e,i,t);return{x:s.x*this.width,y:s.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const s=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),n=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,s.x,s.y,n.x-s.x,n.y-s.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const s=this.toCanvas(e.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:s.x,y:s.y,radius:7}),t.beginPath(),t.rect(s.x-3.5,s.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const n=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(s.x+Math.cos(n)*10,s.y+Math.sin(n)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(s=>this.toCanvas(e.bounds,s.lat,s.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const s of i.slice(1))t.lineTo(s.x,s.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const s=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(s.length===0)continue;const n=i.color??e8;if(i.kind==="point")t.beginPath(),t.moveTo(s[0].x,s[0].y-6),t.lineTo(s[0].x+6,s[0].y),t.lineTo(s[0].x,s[0].y+6),t.lineTo(s[0].x-6,s[0].y),t.closePath(),t.fillStyle=n,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(s[0].x,s[0].y);for(const r of s.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=n,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=s[0];if(i.kind==="line"&&e.position){const a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=s.reduce((o,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(o.x-a.x,o.y-a.y)?l:o)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:s}=e;if(i===void 0||s===void 0)return;const{ctx:n}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),a=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,l=s*Math.PI/180;n.save(),n.beginPath(),n.moveTo(r.x,r.y),n.arc(r.x,r.y,a,o-l,o+l),n.closePath();const h=n.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),n.fillStyle=h,n.fill(),n.restore()}paintMarkers(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((s,n)=>Number(s.current)-Number(n.current))){const s=this.toCanvas(e.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:s.x,y:s.y,radius:Kc.MARKER_RADIUS_PX}),t.beginPath(),t.arc(s.x,s.y,Kc.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,s.x,s.y)}}paintObserver(e,t){const{ctx:i}=this,s=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:s.x,y:s.y,radius:8});const n=e.markers.some(r=>{if(!r.current)return!1;const a=dt(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=Kc.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?Kc.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),n||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=n?3:2.5,i.strokeStyle=n?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const s=t?this.wrap(t,this.width-20):[];let n=this.height-4;i.textAlign="right";for(const p of s.slice().reverse())this.paintOutlinedText(p,this.width-6,n),n-=11;const r=(e.south+e.north)/2,o=Math.abs(dt(r,e.east,r,e.west).x)/this.width,l=Kc.SCALE_STEPS_M.find(p=>p/o<=this.width/3);if(l===void 0)return;const h=l/o,d=8,u=n-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,d,u-3)}paintOutlinedText(e,t,i){const{ctx:s}=this;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.75)",s.strokeText(e,t,i),s.fillStyle="#fff",s.fillText(e,t,i)}wrap(e,t){const i=[];let s="";for(const n of e.split(" ")){const r=s?`${s} ${n}`:n;s&&this.ctx.measureText(r).width>t?(i.push(s),s=n):s=r}return s&&i.push(s),i}}class Mi{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(e,t){return Mi.including(e.boundsAround(Mi.MIN_SPAN_M,Mi.MARGIN),t)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(e,t,i){const s=Math.min(Mi.MAX_ZOOM,Math.max(Mi.MIN_ZOOM,this.zoom*i)),n=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=n-(e-.5)/s,this.centerY=r-(t-.5)/s,this.zoom=s}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),s=Mi.mercatorY01(t.north),n=Mi.mercatorY01(t.south),r=Mi.mercatorY01(i.north),a=Mi.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+a)/2-s)/(n-s)}keepInView(e,t,i){if(!this.changed)return!1;const s=this.boundsWithin(e),n=Mi.mercatorY01(s.north),r=Mi.mercatorY01(s.south),a=(t.lng-s.west)/(s.east-s.west),o=(Mi.mercatorY01(t.lat)-n)/(r-n);return a>=i&&a<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-a,.5-o),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=Mi.mercatorY01(e.north),s=Mi.mercatorY01(e.south),n=e.east-e.west;return{west:e.west+(this.centerX-t)*n,east:e.west+(this.centerX+t)*n,north:Mi.latitudeAt(i+(this.centerY-t)*(s-i)),south:Mi.latitudeAt(i+(this.centerY+t)*(s-i))}}static including(e,t,i=3){const s=(e.north+e.south)/2,n=(e.east+e.west)/2,r=dt(s,e.east,s,n).x;let a=r;for(const o of t){const{x:l,z:h}=dt(o.lat,o.lng,s,n),d=Math.max(Math.abs(l),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:mr(0,-a,s,n).lat,south:mr(0,a,s,n).lat,east:mr(a,0,s,n).lng,west:mr(-a,0,s,n).lng}}static expand(e,t){const i=e.east-e.west,s=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-s*t,north:e.north+s*t}}static pointAt(e,t,i){const s=Mi.mercatorY01(e.north),n=Mi.mercatorY01(e.south);return{lat:Mi.latitudeAt(s+i*(n-s)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const na=256,t8=3,i8=129,s8=7,n8=32768;class lI{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,s=(e.west+e.east)/2,n=Math.abs(dt(i,e.east,i,e.west).x),r=Math.abs(dt(e.north,s,e.south,s).z),a=Math.max(n,r);let o=ZN(i,a),l=t8;if(t.width>=i8){const m=v=>2*Math.ceil((a/pM(i,v)+1)/2)+1;let g=nI(i,a/(t.width-1)/2);for(;g>o&&m(g)>s8;)g--;g>o&&(o=g,l=m(g))}const{tiles:h}=oI(s,i,o,l),d=l*na,u=new Float32Array(d*d),p=h[0];await Promise.all(h.map(m=>this.decodeTileInto(m,p,u,d)));const f=new Float32Array(t.width*t.height);for(let m=0;m<t.height;m++){const g=e.north+(e.south-e.north)*(m/(t.height-1));for(let v=0;v<t.width;v++){const b=e.west+(e.east-e.west)*(v/(t.width-1));f[m*t.width+v]=this.sampleAt(g,b,o,p,u,d)}}return{heights:f,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,s){const n=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(n);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${n}`);const a=await createImageBitmap(await r.blob()),o=document.createElement("canvas");o.width=na,o.height=na;const l=o.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,na,na),d=(e.x-t.x)*na,u=(e.y-t.y)*na;for(let p=0;p<na;p++)for(let f=0;f<na;f++){const m=(p*na+f)*4,g=h[m]*256+h[m+1]+h[m+2]/256-n8,v=d+f,b=u+p;i[b*s+v]=g}}sampleAt(e,t,i,s,n,r){const{x:a,y:o}=rI(t,e,i),l=(a-s.x)*na,h=(o-s.y)*na,d=Math.max(0,Math.min(r-1,Math.floor(l))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),m=l-d,g=h-u,v=n[u*r+d],b=n[u*r+p],w=n[f*r+d],y=n[f*r+p],M=v+(b-v)*m,x=w+(y-w)*m;return M+(x-M)*g}}class hv{constructor(e,t,i,s){this.width=e,this.height=t,this.samples=i,this.values=s}at(e,t,i=0){return this.values[(t*this.width+e)*this.samples+i]}static parse(e){const t=new DataView(e);if(e.byteLength<8||t.getUint16(0)!==18761||t.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=t.getUint32(4,!0),s=t.getUint16(i,!0),n=new Map;for(let v=0;v<s;v++){const b=i+2+v*12;n.set(t.getUint16(b,!0),{type:t.getUint16(b+2,!0),count:t.getUint32(b+4,!0),value:t.getUint32(b+8,!0)})}const r=(v,b)=>{const w=n.get(v);if(w===void 0){if(b===void 0)throw new Error(`TIFF without tag ${v}`);return b}return w.type===3?w.value&65535:w.value},a=v=>{const b=n.get(v);if(b===void 0)throw new Error(`TIFF without tag ${v}`);const w=b.type===3?2:4,y=[];if(b.count*w<=4){const M=new DataView(new ArrayBuffer(4));M.setUint32(0,b.value,!0);for(let x=0;x<b.count;x++)y.push(w===2?M.getUint16(x*2,!0):M.getUint32(0,!0))}else for(let M=0;M<b.count;M++)y.push(w===2?t.getUint16(b.value+M*2,!0):t.getUint32(b.value+M*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const o=r(256),l=r(257),h=r(277,1),d=a(258)[0],u=r(339,1)===3;if(!(u&&d===32||!u&&d===8))throw new Error(`Unsupported TIFF samples: ${d} bits`);const p=a(273),f=a(279),m=new Uint8Array(o*l*h*(d/8));let g=0;for(let v=0;v<p.length&&g<m.length;v++){const b=Math.min(f[v],m.length-g);m.set(new Uint8Array(e,p[v],b),g),g+=b}if(g<m.length)throw new Error("Truncated TIFF");return new hv(o,l,h,u?new Float32Array(m.buffer):m)}}class r8{constructor(e,t,i,s,n){this.heights=e,this.plants=t,this.buildings=i,this.size=s,this.metresPerPixel=n}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),s=Math.floor(this.size/2-t/this.metresPerPixel);if(i<0||s<0||i>=this.size||s>=this.size)return;const n=s*this.size+i;if(!(this.plants[n]||this.buildings[n]))return this.heights[n]}tallestStructureNear(e,t,i){let s;const n=Math.ceil(i/this.metresPerPixel);for(let r=-n;r<=n;r++)for(let a=-n;a<=n;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const o=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);o!==void 0&&(s===void 0||o>s)&&(s=o)}return s}}class Le{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(e,t){const[i,s]=e;return{east:(i-t.lng)*Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(s-t.lat)*Le.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>Le.toMetres(i,t))}static bearing(e,t){return(Math.atan2(t.east-e.east,t.north-e.north)*180/Math.PI+360)%360}static distanceToSegment(e,t,i){const s=i.east-t.east,n=i.north-t.north,r=s*s+n*n,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*s+(e.north-t.north)*n)/r));return Math.hypot(e.east-(t.east+a*s),e.north-(t.north+a*n))}static bridges(e,t,i,s){const n=e.elevatedRoads.map(o=>({path:Le.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>Le.path(o,t)),a=[];for(const o of Le.joined(e.bridges.map(l=>Le.path(l,t)))){const l=o[0],h=o[o.length-1],d=Math.hypot(h.east-l.east,h.north-l.north);if(d<Le.MIN_BRIDGE_M)continue;const u={east:(l.east+h.east)/2,north:(l.north+h.north)/2};if(Math.hypot(u.east,u.north)>i+d/2||Le.carriesRailway(l,h,r))continue;const[p,f]=Le.deckReach(l,h,s);a.push({eastM:Le.tenth((p.east+f.east)/2),northM:Le.tenth((p.north+f.north)/2),lengthM:Le.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:Le.roadOf(u,n).width,heightM:Le.tenth(Le.deckHeight(l,h,s)),headingDeg:Le.tenth(Le.bearing(l,h)%180),...Le.roadOf(u,n).name?{name:Le.roadOf(u,n).name}:{}})}return a.sort((o,l)=>Math.hypot(o.eastM,o.northM)-Math.hypot(l.eastM,l.northM)),a}static carriesRailway(e,t,i){const s={east:(e.east+t.east)/2,north:(e.north+t.north)/2},n=Le.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(Le.distanceToSegment(s,r[a],r[a+1])>Le.RAIL_MATCH_M)continue;const o=Math.abs(Le.bearing(r[a],r[a+1])%180-n);if(Math.min(o,180-o)<=Le.JOIN_DEG)return!0}return!1}static joined(e){const t=e.filter(i=>i.length>=2);for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const n=Le.join(t[i],t[s]);n!==void 0&&(t[i]=n,t.splice(s,1),s=i)}return t}static join(e,t){for(const i of[e,[...e].reverse()])for(const s of[t,[...t].reverse()]){const n=i[i.length-1],r=s[0];if(Math.hypot(n.east-r.east,n.north-r.north)>Le.JOIN_M)continue;const a=Math.abs(Le.bearing(i[0],n)-Le.bearing(r,s[s.length-1]));if(Math.min(a,360-a)<=Le.JOIN_DEG)return[...i,...s.slice(1)]}}static roadOf(e,t){let i;for(const a of t)for(let o=0;o+1<a.path.length;o++){const l=Le.distanceToSegment(e,a.path[o],a.path[o+1]);(i===void 0||l<i.distance)&&(i={distance:l,properties:a.properties})}if(i===void 0||i.distance>Le.ROAD_MATCH_M)return{width:Le.DEFAULT_DECK_M};const s=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(a=>typeof a=="string"&&a.length>0),n=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(n)&&n>0?Le.tenth(n+Le.DECK_MARGIN_M):i.properties.nature==="Sentier"?Le.FOOTBRIDGE_DECK_M:Le.DEFAULT_DECK_M;return s?{width:r,name:s}:{width:r}}static deckReach(e,t,i){const s=Math.hypot(t.east-e.east,t.north-e.north);if(i===void 0||s===0)return[e,t];const n={east:(e.east+t.east)/2,north:(e.north+t.north)/2},r={east:(t.east-e.east)/s,north:(t.north-e.north)/s},a=u=>(i.structureAt(n.east+r.east*u,n.north+r.north*u)??0)>=Le.DECK_SEEN_M,o=u=>i.structureAt(n.east+r.east*u,n.north+r.north*u)??0,l=u=>{let p;for(let m=0;m<=s/2+Le.DECK_REACH_M;m+=Le.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>Le.DECK_GAP_M)break;if(p===void 0)return s/2;let f=p;for(;f-p<Le.DECK_REACH_M&&o(u*(f+Le.DECK_STEP_M))>=Le.DECK_MEETS_M;)f+=Le.DECK_STEP_M;return Math.max(s/2,f+Le.DECK_BEARING_M)},h=l(-1),d=l(1);return[{east:n.east-r.east*h,north:n.north-r.north*h},{east:n.east+r.east*d,north:n.north+r.north*d}]}static deckHeight(e,t,i){if(i===void 0)return Le.DEFAULT_DECK_HEIGHT_M;const s=[],n=20;for(let r=4;r<=n-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/n,e.north+(t.north-e.north)*r/n);a!==void 0&&a>=1.5&&s.push(a)}return s.length===0?Le.DEFAULT_DECK_HEIGHT_M:(s.sort((r,a)=>r-a),s[Math.floor(s.length/2)])}static lines(e,t,i,s){const n=[];for(const r of e.lines){const a=String(r.properties.voltage??""),o=Le.kilovolts(a);if(o===void 0)continue;const l=Le.BY_VOLTAGE.find(d=>o<=d.upToKv)??Le.BY_VOLTAGE[Le.BY_VOLTAGE.length-1],h=Le.path(r,t);for(let d=0;d+1<h.length;d++){const u=h[d],p=h[d+1],f=Math.hypot(p.east-u.east,p.north-u.north);if(f<5||f>Le.MAX_SPAN_M||Le.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=Le.poleHeight(u,p,s)??l.poleM;n.push({eastM:Le.tenth((u.east+p.east)/2),northM:Le.tenth((u.north+p.north)/2),lengthM:Le.tenth(f),headingDeg:Le.tenth(Le.bearing(u,p)),heightM:Le.tenth(Math.max(4,m-l.dropM)),poleHeightM:Le.tenth(m),acrossM:[-l.spreadM,0,l.spreadM],voltage:a})}}return n.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),n.slice(0,Le.MAX_LINES)}static kilovolts(e){const t=/([\d.,]+)\s*kV/i.exec(e);if(t===null)return;const i=Number(t[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(e,t,i){if(i===void 0)return;const s=[e,t].map(n=>i.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=Le.MIN_POLE_M&&n<=Le.MAX_POLE_M);return s.length===0?void 0:s.reduce((n,r)=>n+r,0)/s.length}static tenth(e){return Math.round(e*10)/10}}class Yt{static covers(e,t){return e>=41.2&&e<=51.3&&t>=-5.4&&t<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Yt.WMS,this.wfs=e.wfsEndpoint??Yt.WFS}static radius(e){return Math.min(e,Yt.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,Yt.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=Yt.lidarRadius(t),s=Math.ceil(2*i/Yt.METRES_PER_PIXEL),[n,r]=await Promise.all([this.raster(e,i,s,Yt.HEIGHT_LAYER),this.raster(e,i,s,Yt.CLASS_LAYER)]);if(n.samples!==1||r.samples<3)throw new Sa("unreachable","The survey answered in a layout this does not read");const a=n.values;if(a.every(d=>d===Yt.NO_DATA))throw new Sa("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(s*s),l=new Uint8Array(s*s);for(let d=0;d<s*s;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];o[d]=p>u&&p>f?1:0,l[d]=u>120&&p<90&&f<90?1:0}const h=2*i/s;return{size:s,metresPerPixel:h,heights:a,vegetation:o,building:l,structures:new r8(a,o,l,s,h)}}async laserDate(e){return Yt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return Yt.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",e))}static latest(e){return e.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(e,t,i,s){const r=[s.lng-1e-4,s.lat-1e-4,s.lng+1e-4,s.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(e,`BBOX(${t},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(e,t){const i=Yt.radius(t),s=Math.min(Yt.MAX_PHOTO_PIXELS,Math.ceil(2*i/Yt.METRES_PER_PIXEL)),n=await this.raster(e,i,s,Yt.PHOTO_LAYER);if(n.samples<3)throw new Sa("unreachable","The photograph came in a layout this does not read");return{size:s,metresPerPixel:2*i/s,samples:n.samples,values:n.values}}async vectors(e,t,i){const s=Yt.radius(t),n=s/Yt.METRES_PER_DEGREE,r=s/(Yt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),o=`BBOX(geometrie,${[e.lng-r,e.lat-n,e.lng+r,e.lat+n].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,d,u,p,f]=await Promise.all([this.features("construction_lineaire",`${o} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${o} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${o} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",o,"voltage,geometrie"),i?this.features("batiment",o,Yt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(f,p,[e.lng-r,e.lat-n,e.lng+r,e.lat+n]):[],g=[...p,...m];return{bridges:l,elevatedRoads:h,elevatedRailways:d,lines:u,buildings:g,zones:f,mapDate:Yt.latest(g.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(e,t,i){const[s,n,r,a]=i,o=Yt.MAX_WHOLE_M/Yt.METRES_PER_DEGREE;let l;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=Yt.extent(d);if(u>=s&&p>=n&&f<=r&&m<=a)continue;const g=[Math.max(u,s-o),Math.max(p,n-o),Math.min(f,r+o),Math.min(m,a+o)];l=l?[Math.min(l[0],g[0]),Math.min(l[1],g[1]),Math.max(l[2],g[2]),Math.max(l[3],g[3])]:g}if(!l)return[];const h=new Set(t.map(d=>d.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(u=>u.toFixed(6)).join(",")},'EPSG:4326')`,Yt.BUILDING_PROPERTIES,1e3)).filter(u=>!h.has(u.properties.cleabs))}catch{return[]}}static extent(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(t=Math.min(t,a[0]),s=Math.max(s,a[0]),i=Math.min(i,a[1]),n=Math.max(n,a[1])):Array.isArray(a)&&a.forEach(r)};return r(e.geometry.coordinates),[t,i,s,n]}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),s=[];for(const n of i){const{type:r,coordinates:a}=n.geometry,o=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of o)s.push(l.map(h=>({lat:h[1],lng:h[0]})))}return s}async waterSurfaces(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${t} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${t} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${t} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(e,t,i,s){const n=t/Yt.METRES_PER_DEGREE,r=t/(Yt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-n,e.lng-r,e.lat+n,e.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new Sa("unreachable",l instanceof Error?l.message:String(l))}if(!o.ok)throw new Sa("unreachable",`The survey answered ${o.status}`);try{return hv.parse(await o.arrayBuffer())}catch(l){throw new Sa("unreachable",l instanceof Error?l.message:String(l))}}async features(e,t,i,s=200){const n=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:e.includes(":")?e:`BDTOPO_V3:${e}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(s),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${n}`)}catch(o){throw new Sa("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new Sa("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class zl{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(e,t){if(e.length<2||t.length<2)return!1;const i=t[0],s=t.map(a=>dt(a.lat,a.lng,i.lat,i.lng)),n=e.map(a=>dt(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<n.length-1;a++){const o=n[a],l=n[a+1],h=Math.hypot(l.x-o.x,l.z-o.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/zl.SAMPLE_M)),u=Math.atan2(l.x-o.x,-(l.z-o.z));for(let p=0;p<=d;p++){const f=p/d,m=zl.nearest(s,o.x+(l.x-o.x)*f,o.z+(l.z-o.z)*f);m.distanceM>zl.NEAR_M||zl.angleBetween(u,m.heading)<=zl.ALIGNED_DEG&&(r+=h/d)}}return r>=zl.LONG_ENOUGH_M}static nearest(e,t,i){let s={distanceM:1/0,heading:0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,l=a.z-r.z,h=o*o+l*l,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*o+(i-r.z)*l)/h)),u=Math.hypot(t-(r.x+o*d),i-(r.z+l*d));u<s.distanceM&&(s={distanceM:u,heading:Math.atan2(o,-l)})}return s}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class Ht{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Ht.WMS,this.timeoutMs=e.timeoutMs??Ht.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Ht.MAX_WINDOW_M,this.geoplatform=new Yt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const s={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!Yt.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(dt(s.lat,e.east,s.lat,e.west).x),r=Math.abs(dt(e.north,s.lng,e.south,s.lng).z);t=this.finer(t,n,r);const a={x:n/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},o={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:e.south-o.y/Ht.METRES_PER_DEGREE,north:e.north+o.y/Ht.METRES_PER_DEGREE,west:e.west-o.x/(Ht.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:e.east+o.x/(Ht.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=m=>Math.min(Ht.MAX_PIXELS,Math.max(Ht.MIN_PIXELS,Math.ceil(m/Ht.METRES_PER_PIXEL))),d={width:h(n+2*o.x),height:h(r+2*o.y)},u={x:(n+2*o.x)/d.width,y:(r+2*o.y)/d.height};let p=new Error("No layer of the IGN's relief answered");const f=Math.max(u.x,u.y)>Ht.COARSE_METRES_PER_PIXEL;for(const m of f?[...Ht.LAYERS].reverse():Ht.LAYERS)try{const g=await this.heights(l,d,m);m===Ht.LAYERS[0]&&await this.layBridgeDecks(g,l,d,i?.route);const v=this.sample(g,t,e,l,u,a);if(v)return{heights:v,width:t.width,height:t.height,bounds:e};p=new Error(`${m} does not cover this place`)}catch(g){p=g}throw p}finer(e,t,i){if(e.width<Ht.MESH_FROM_VERTICES||e.height<Ht.MESH_FROM_VERTICES)return e;const s=(n,r)=>{const a=Math.ceil(n/Ht.FINE_SPACING_M),o=Math.max(r-1,Math.min(Ht.MAX_SEGMENTS,a));return o%2===0?o:o+1};return{width:s(t,e.width)+1,height:s(i,e.height)+1}}async raster(e,t,i){const s=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[e.south,e.west,e.north,e.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(t.width),HEIGHT:String(t.height),FORMAT:"image/geotiff"}),n=await this.fetchImpl(`${this.wms}?${s}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok)throw new Error(`The IGN's relief answered ${n.status}`);return hv.parse(await n.arrayBuffer())}async heights(e,t,i){const s=await this.raster(e,t,i);if(s.samples!==1||!(s.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return s}async layBridgeDecks(e,t,i,s){if(!(!s||s.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(n=>n>Ht.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>zl.follows(s,a));if(n.length===0)return;const r=Float32Array.from(e.values);await this.layClassifiedDecks(e,t,i,n),this.layRouteDecks(e,r,t,n)}catch{}}async layClassifiedDecks(e,t,i,s){try{const n=await this.raster(t,i,Ht.CLASS_LAYER);if(n.samples<3||n.width!==e.width||n.height!==e.height)return;const r=(g,[v,b,w])=>n.values[g*n.samples]===v&&n.values[g*n.samples+1]===b&&n.values[g*n.samples+2]===w,a=e.width,o=e.height,l=new Uint8Array(a*o);let h=!1;for(let g=0;g<l.length;g++)r(g,Ht.DECK)&&(l[g]=1,h=!0);if(!h)return;const d=Ht.DECK_END_PIXELS,u=[];for(let g=0;g<l.length;g++){if(l[g]!==1)continue;const v=g%a,b=(g-v)/a;for(let w=-d;w<=d;w++)for(let y=-d;y<=d;y++){const M=v+y,x=b+w;if(M<0||x<0||M>=a||x>=o)continue;const S=x*a+M;l[S]===0&&r(S,Ht.NO_CLASS)&&u.push(S)}}for(const g of u)l[g]=1;const p=this.paint(s,t,a,o),f=this.touching(l,p,a,o);if(f.every(g=>g===0))return;const m=await this.heights(t,i,Ht.SURFACE_LAYER);if(m.width!==a||m.height!==o)return;for(let g=0;g<f.length;g++){if(f[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Ht.NO_DATA_BELOW&&v>e.values[g]&&(e.values[g]=v)}}catch{}}layRouteDecks(e,t,i,s){const{width:n,height:r}=e,a=(i.north+i.south)/2,o=(i.east-i.west)*Ht.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ht.METRES_PER_DEGREE,h=o/n,d=l/r,u=v=>({x:(v.lng-i.west)/(i.east-i.west)*o,y:(i.north-v.lat)/(i.north-i.south)*l}),p=(v,b)=>{const w=Math.floor(v/h),y=Math.floor(b/d);if(w<0||y<0||w>=n||y>=r)return;const M=t[y*n+w];return Number.isFinite(M)&&M>Ht.NO_DATA_BELOW?M:void 0},f=Ht.DECK_HALF_WIDTH_M,m=Ht.DECK_APPROACH_M,g=(v,b)=>{const w=Math.hypot(v.x-b.x,v.y-b.y)||1,y={x:(v.x-b.x)/w,y:(v.y-b.y)/w},M=[0,m/2,m].map(x=>p(v.x+y.x*x,v.y+y.y*x)).filter(x=>x!==void 0);return M.length>0?Math.max(...M):void 0};for(const v of Ht.chains(s.map(b=>b.map(u)))){const b=[0];for(let D=1;D<v.length;D++)b.push(b[D-1]+Math.hypot(v[D].x-v[D-1].x,v[D].y-v[D-1].y));const w=b[b.length-1];if(w<1||w>Ht.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),M=g(v[v.length-1],v[v.length-2]);if(y===void 0||M===void 0)continue;const x=f+m,S=Math.max(0,Math.floor((Math.min(...v.map(D=>D.x))-x)/h)),E=Math.min(n-1,Math.ceil((Math.max(...v.map(D=>D.x))+x)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(D=>D.y))-x)/d)),T=Math.min(r-1,Math.ceil((Math.max(...v.map(D=>D.y))+x)/d));for(let D=A;D<=T;D++)for(let k=S;k<=E;k++){const O=Ht.nearestAlong(v,b,{x:(k+.5)*h,y:(D+.5)*d});if(O.distance>f||O.s<-m||O.s>w+m)continue;const L=y+(M-y)*Math.min(1,Math.max(0,O.s/w)),R=D*n+k;t[R]>=L||(e.values[R]=L)}}}static chains(e){const t=e.filter(n=>n.length>=2).map(n=>[...n]),i=[],s=(n,r)=>Math.hypot(n.x-r.x,n.y-r.y)<=1;for(;t.length>0;){let n=t.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<t.length;a++){const o=t[a],l=n[0],h=n[n.length-1];if(s(h,o[0]))n=[...n,...o.slice(1)];else if(s(h,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else if(s(l,o[o.length-1]))n=[...o.slice(0,-1),...n];else if(s(l,o[0]))n=[...[...o].reverse().slice(0,-1),...n];else continue;t.splice(a,1),r=!0;break}}i.push(n)}return i}static nearestAlong(e,t,i){let s={s:0,distance:1/0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,l=a.y-r.y,h=o*o+l*l;if(h<1e-9)continue;let d=((i.x-r.x)*o+(i.y-r.y)*l)/h;n>0&&(d=Math.max(0,d)),n<e.length-2&&(d=Math.min(1,d));const u=Math.hypot(i.x-(r.x+o*d),i.y-(r.y+l*d));u<s.distance&&(s={s:t[n]+d*Math.sqrt(h),distance:u})}return s}paint(e,t,i,s){const n=new Uint8Array(i*s),r=o=>(o-t.west)/(t.east-t.west)*i,a=o=>(t.north-o)/(t.north-t.south)*s;for(const o of e)for(let l=0;l<o.length-1;l++){const h=r(o[l].lng),d=a(o[l].lat),u=r(o[l+1].lng),p=a(o[l+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let m=0;m<=f;m++){const g=Math.floor(h+(u-h)*m/f),v=Math.floor(d+(p-d)*m/f);for(let b=-1;b<=1;b++)for(let w=-1;w<=1;w++){const y=g+w,M=v+b;y>=0&&M>=0&&y<i&&M<s&&(n[M*i+y]=1)}}}return n}touching(e,t,i,s){const n=new Uint8Array(e.length),r=new Uint8Array(e.length);for(let a=0;a<e.length;a++){if(e[a]===0||r[a]===1)continue;const o=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const d=l.pop();o.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let m=-1;m<=1;m++){const g=u+m,v=p+f;if(g<0||v<0||g>=i||v>=s)continue;const b=v*i+g;e[b]===1&&r[b]===0&&(r[b]=1,l.push(b))}}if(h)for(const d of o)n[d]=1}return n}sample(e,t,i,s,n,r){const{width:a,height:o}=t,l=new Float32Array(a*o),h=new Uint8Array(a*o),d=Math.min(r.x,this.maxWindowM)/n.x,u=Math.min(r.y,this.maxWindowM)/n.y;let p=0;for(let f=0;f<o;f++){const m=i.north+(i.south-i.north)*(o===1?.5:f/(o-1)),g=(s.north-m)/(s.north-s.south)*e.height-.5;for(let v=0;v<a;v++){const w=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-s.west)/(s.east-s.west)*e.width-.5,y=d>1||u>1?this.tent(e,w,g,Math.max(1,d),Math.max(1,u)):this.bilinear(e,w,g),M=f*a+v;y===void 0?p++:(l[M]=y,h[M]=1)}}if(!(p===a*o||p/(a*o)>Ht.MAX_HOLE_SHARE))return this.fill(l,h,a,o),l}tent(e,t,i,s,n){let r=0,a=0,o=0;const l=Math.max(0,Math.ceil(i-n)),h=Math.min(e.height-1,Math.floor(i+n)),d=Math.max(0,Math.ceil(t-s)),u=Math.min(e.width-1,Math.floor(t+s));for(let p=l;p<=h;p++){const f=1-Math.abs(p-i)/n;if(!(f<=0))for(let m=d;m<=u;m++){const g=f*(1-Math.abs(m-t)/s);if(g<=0)continue;o+=g;const v=e.at(m,p);!Number.isFinite(v)||v<Ht.NO_DATA_BELOW||(r+=g*v,a+=g)}}return o>0&&a>=o*.5?r/a:void 0}bilinear(e,t,i){const s=Math.max(0,Math.min(e.width-1,Math.floor(t))),n=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,s+1),a=Math.min(e.height-1,n+1),o=Math.max(0,Math.min(1,t-s)),l=Math.max(0,Math.min(1,i-n)),h=e.at(s,n),d=e.at(r,n),u=e.at(s,a),p=e.at(r,a);for(const g of[h,d,u,p])if(!Number.isFinite(g)||g<Ht.NO_DATA_BELOW)return;const f=h+(d-h)*o,m=u+(p-u)*o;return f+(m-f)*l}fill(e,t,i,s){let n=t.reduce((r,a)=>r+(a?0:1),0);for(;n>0;){const r=[];for(let a=0;a<s;a++)for(let o=0;o<i;o++){const l=a*i+o;if(t[l])continue;let h=0,d=0;for(let u=-1;u<=1;u++)for(let p=-1;p<=1;p++){const f=a+u,m=o+p;f<0||m<0||f>=s||m>=i||!t[f*i+m]||(h+=e[f*i+m],d++)}d>0&&r.push([l,h/d])}if(r.length===0)return;for(const[a,o]of r)e[a]=o,t[a]=1;n-=r.length}}}class a8{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let s=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(e,t,i)}catch(r){s=r}throw s}}const P0=256,o8=5;async function cI(c,e,t,i){const s=(c.south+c.north)/2,n=(c.west+c.east)/2,r=Math.abs(dt(s,c.east,s,c.west).x),a=Math.abs(dt(c.north,n,c.south,n).z),o=Math.max(r,a),{zoom:l,gridSize:h}=l8(s,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=oI(n,s,l,h),p=h*P0,f=document.createElement("canvas");f.width=p,f.height=p;const m=f.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=d[0];await Promise.all(d.map(async y=>{const M=t(y),x=await i(M);if(!x.ok)throw new Error(`Imagery tile fetch failed (${x.status}): ${M}`);const S=await createImageBitmap(await x.blob());m.drawImage(S,(y.x-g.x)*P0,(y.y-g.y)*P0)}));const v=Math.min(Math.max(e.width,e.height),p);if(v===p)return{source:f,width:p,height:p,bounds:u};const b=document.createElement("canvas");b.width=v,b.height=v;const w=b.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(f,0,0,p,p,0,0,v,v),{source:b,width:v,height:v,bounds:u}}function l8(c,e,t){let i=nI(c,e/Math.max(1,t)),s=i2(c,i,e);for(;s>o8&&i>0;)i--,s=i2(c,i,e);return{zoom:i,gridSize:s,mPerPixel:pM(c,i)/P0}}function i2(c,e,t){const i=Math.ceil(t/2/pM(c,e));return Math.max(3,2*i+1)}class hI{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return cI(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Rr{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(e,t=Rr.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(e);if(!i)return[...t];const[s,n,r,a]=i.slice(1).map(Number),o=(s+r)/2,l=(n+a)/2,h=Rr.FRANCE;return o>=h.south&&o<=h.north&&l>=h.west&&l<=h.east?[Rr.FRANCE_ENDPOINT,...t.filter(u=>u!==Rr.FRANCE_ENDPOINT)]:[...t]}fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=Rr.queue.then(e,e);return Rr.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??Rr.endpointsFor(e))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(Rr.HANG_MS)});if(n.ok)return await n.json();if(t=new Error(`${new URL(i).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){t=new Error(`${new URL(i).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,Rr.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class Hl{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(e={}){this.client=new Rr(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Hl.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(e){const t=[];for(const i of e.elements??[]){const s=i.geometry,n=i.tags;!n||!s||s.length<2||t.push({id:`osm-${i.id??t.length}`,name:n.name,surface:Hl.surfaceOf(n),widthM:Hl.widthOf(n),...Hl.paintOf(n),points:s.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",s=e.oneway,n=s==="yes"||s==="1"||s==="true"||s===void 0&&(t==="motorway"||i),r=s==="-1"||s==="reverse",a=Number.parseInt(e.lanes??"",10),o=Number.parseInt(e.maxspeed??"",10),l=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(n||r)?"dual":t?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...s!==void 0||t==="motorway"||i?{direction:r?"backward":n?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:Hl.WIDTH_M[e.highway]??Hl.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const Eb="https://ufoathome.org/roads/index.json";class _d{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??_d.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.ways)?(this.attributionRead=n.attribution,this.contemporaryRead=n.contemporary,n.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8862
|
-
`);let t=_d.shared.get(e);return t||(t=this.fetchFirstAvailable(),_d.shared.set(e,t),t.then(i=>{i.length===0&&_d.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.
|
|
8863
|
-
`);let t=Dd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Dd.shared.set(e,t),t.then(i=>{i.length===0&&Dd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.2")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Sb?[t,Sb]:[Sb]).map(i=>i+e)}}class xr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=xr.key(e);let i=xr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),xr.asked.set(t,i),i.catch(()=>xr.asked.delete(t))),structuredClone(await i)}static forget(){xr.asked.clear()}static key(e){return`v${xr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await xr.openCache(),s=xr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<xr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&xr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-xr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class Yl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Yt(e)}static covers(e){return Yt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>Yl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=Yl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),l=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=Yl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=Yl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Yl.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class _n{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new Rr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${_n.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${_n.ROUTES})$"];out body;`;return _n.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=_n.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>dt(v.lat,v.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let d=0;const u=n.filter(v=>v.service===!!r.service);for(const v of _n.samples(a)){d++;const b=_n.waysAt(u,v);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=v=>[...v.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(l)),g=[...h.entries()].filter(([,v])=>v*4>=d).sort((v,b)=>b[1]-v[1]||v[0].localeCompare(b[0])).map(([v])=>v);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=_n.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=_n.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=_n.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>dt(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=_n.SAMPLE_M/2;a<s;a+=_n.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(_n.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],l=n.path[a+1],h=l.x-o.x,d=l.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=_n.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class kd{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new Rr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${kd.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${_n.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=_n.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=_n.voltageOf(r),l=kd.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=kd.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:kd.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class d8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!Yl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Hs{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Hs.key(e);let i=Hs.asked.get(t)??Hs.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Hs.asked.set(t,i),s.catch(()=>Hs.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Hs.asked.clear(),Hs.failedAt=-1/0}static key(e){return`v${Hs.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Hs.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Hs.openCache(),s=Hs.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-o<Hs.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-Hs.failedAt<Hs.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Hs.failedAt=this.now(),n)return n;throw a}return i&&Hs.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Hs.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Hs.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const Ab="https://ufoathome.org/railways/index.json";class Rd{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Rd.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8864
|
-
`);let t=Rd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Rd.shared.set(e,t),t.then(i=>{i.length===0&&Rd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.2")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==Ab?[t,Ab]:[Ab]).map(i=>i+e)}}function dI(){return{elevation:uI(),imagery:pI(),roads:fI(),water:mI(),railways:gI()}}function uI(){return new a8(new Ht,new lI)}function pI(){return new hI}function fI(){return new _d({fallback:new c8(new Xl,new Hl)})}function mI(){return new Dd({fallback:new xr(new h8(new Rf,new Xc))})}function gI(){return new Rd({fallback:new Hs(new d8(new Yl,new kd))})}const u8=new Set,Qd="show-observer-map",eu="hide-milestones",sh="minified";class ei extends HTMLElement{static get observedAttributes(){return["src",Qd,eu,sh]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Mi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=tv.create();issues=[];issueCheck=0;sightingAudio=new e2;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new e2(e)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>ei.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");ei.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(e){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!e){this.fitControls();return}const t=document.createElement("button");t.type="button",t.id="video-button",t.innerHTML=Je.VIDEO,this.videoElement=t,this.labelVideoButton(),t.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(e,t)},{once:!0}),this.moreButton.after(t),this.fitControls()}async loadVideoButton(e,t){const{VideoButton:i}=await Y(async()=>{const{VideoButton:n}=await import("./VideoButton-CqCZ65oK.js");return{VideoButton:n}},[],import.meta.url);if(this.videoElement!==t)return;const s=new i(e,t);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const e=this.videoElement;!e||this.videoButton||(e.title=this.messages?.recordVideo??"",e.setAttribute("aria-label",e.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(e){e!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,e&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(e){const t=this.currentTime,i=e.caption&&this.sighting.milestones.length>0?Pm(this.sighting.milestones,t):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),r=e.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...e.time?{time:this.formatPosition(t)}:{},...r&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-n.left)/n.width,top:(r.top-n.top)/n.height,width:r.width/n.width,height:r.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<ei.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},ei.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const s=Mi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${WN}</style>${VN}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Eu(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Kc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Qd&&this.applyObserverMapDefault(),e===eu&&this.setMilestonesShown(!this.hasAttribute(eu)),e===sh){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(sh)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(vI)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await Oa.recording(e)}get sightingData(){return If(this.currentSighting)}set sightingData(e){const t=Mn.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=$f(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;set titleShown(e){this.titleHidden=!e,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await Y(async()=>{const{default:r}=await import("./sightingSchema-B8Xs45w9.js");return{default:r}},[],import.meta.url);s=new oa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],kf.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(f8,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=(this.messages?.recordingIssues??"").replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=kf.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(e){this.cited=[...e],this.refreshCitedMarks()}refreshCitedMarks(){const e=this.player.seekableDuration;this.citedMarks.replaceChildren(...(e>0?this.cited:[]).map(t=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=ue.INTERVIEW,i.style.left=`${Math.min(Math.max(t.at*1e3/e,0),1)*100}%`;const s=t.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(t.at*1e3)),i}))}sayTimeMoved(e){Math.abs(e-this.timeSaid)<ei.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(p8,{bubbles:!0,composed:!0,detail:{at:e/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;if(!this.referenceOpacityTouched&&e.length>0){const t=String(e[0].opacity);this.referenceOpacityInput.value!==t&&(this.referenceOpacityInput.value=t,this.severalReferences||this.dispatchReferenceView())}for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(r,l),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),ei.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),ei.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?dh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(o,l),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=ei.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){if(e.buttons!==0){this.seekPreview.hidden=!0;return}const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=ei.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Pm(a,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Eu(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const s=ei.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Pm(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Vn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<ei.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(ei.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/ei.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/ei.EXPOSURE_STEP_PX),n=Math.min(ei.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=$t.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(e,t){this.sayTimeMoved(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:u8;this.canvasRenderer.setStarPoints($t.starPointsOf(this.sighting.instrument,st(this.sighting,e)?.fNumber));const s=(st(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,d=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,l]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?oi.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(Pw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new $N(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*ei.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){ei.icons.get(e)!==t&&(ei.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},ei.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),ei.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(Qd),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;ei.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=ph.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=Mi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?Mi.expand(e,ei.OBSERVER_MAP_IMAGERY_AHEAD):e,s=Mi.IMAGERY_PX*(t?1+2*ei.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:pI();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,s=this.observerMapView.changed?Mi.expand(e,ei.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,d)=>{for(const u of t)if(!(u.x+u.width<l-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=ei.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=st(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},ei.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Pm(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?dh(this.currentSighting.milestones):[]){const a=st(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Yr.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg($t.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,dh(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",ei.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=st(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Zr(i,e),{lat:n,lng:r}=mr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const s=st(this.currentSighting,this.currentTime),n=Yr.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Ti.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=ei.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),ei.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){ei.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}ei.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;ei.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Ls(Ps.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fa(Ps.preferencesFor(this),Pa);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await g5.load(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+t,this.timeEndLabel.title=(this.messages?.duration??"")+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.videoButton&&(this.videoButton.messages=e),this.labelVideoButton(),this.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=xh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?H1(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Dl(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?n2(s2(this.realStartMs+i)):Dl(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Dl(e):Dl(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Dl(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Dl(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Dl(this.currentSighting.timeline.duration):this.canShowClockTime?n2(s2(this.realStartMs+this.realDurationMs)):Dl(this.realDurationMs)}}function s2(c){const e=new Date(c);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function n2(c){if(c.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return c.second?`${e(c.hour)}:${e(c.minute??0)}:${e(c.second)}`:`${e(c.hour)}:${e(c.minute??0)}`}function Dl(c){const e=Math.round(c/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Hy="rr0-ufo";function dv(){customElements.get(Hy)||customElements.define(Hy,ei)}const p8="timechange",f8="recordingissues",vI="minifiedreset";class Sp{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+Sp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sp.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Cd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const g=n.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=dt(g.lat,g.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},a=r(t-Cd.HALF_SPAN_MS),o=r(t+Cd.HALF_SPAN_MS),l=r(t);if(!a||!o||!l)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Cd.HALF_SPAN_MS/1e3;if(h/d<Cd.MIN_SPEED_MS)return 0;const u=o.altitudeM!==void 0&&a.altitudeM!==void 0?o.altitudeM-a.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(a.eastM,a.northM)-a.aboveM,p=Math.atan2(u,h)*180/Math.PI;if(l.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((l.heading-f)*Math.PI/180))}}const m8=.08,r2=.15,a2=2,g8=2e3;class o2{context;constructor(e){this.context=e}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}Qr.isLive(this.context)&&Qr.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);Qr.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<g8),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const l=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*a2*.5,M},h=l(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=l(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const g=l(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();g.connect(v).connect(b).connect(s);const w=[n,r,h,p,g];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,v,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const l=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,l,m8),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,v*n)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,r2/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},r2*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*a2,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Cf{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Cf.BY_KIND[e??"generic"]??Cf.BY_KIND.generic}}class Dn{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(e){return Dn.ROAD_KINDS.includes(e)}static roadOf(e){return e&&Dn.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!Dn.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=Dn.insulationDb(e),i=[3,4,5].map(s=>t[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(e){return e?e.windowsOpen===!0?Dn.WINDOWS_OPEN_DB:Dn.isRoad(e.kind)?Dn.ROAD_CLOSED_DB:Dn.CANOPIED.includes(e.kind)?Dn.CANOPY_DB:Dn.FUSELAGE_DB:Dn.OPEN_AIR}}class nh{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=nh.SAMPLE_MS,r=[];for(let l=i;l<=s+n/2;l+=n){const h=t(l-n/2),d=t(l+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let l=0;l<r.length;l++){const h=r[l],d=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*n/1e3);if(h<nh.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:g,gear:o})}return new nh(a,i)}at(e){const t=(e-this.startMs)/nh.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class wg{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=h=>{const d=e.observerTrack.getInterpolatedPoseAt(h),u=d?.lat??s?.lat,p=d?.lng??s?.lng;if(u===void 0||p===void 0||!s)return;const f=dt(u,p,s.lat,s.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle,o=Dn.roadOf(a);if(a&&o){const h=Cf.of(o),d=this.drive(`observer:${o}`,wg.trackKey(e),()=>nh.of(h,n,0,r));d&&i.push({id:"observer",profile:h,state:d.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const l=n(t);for(const h of e.decor){if(!h.engine||!l)continue;const d=Cf.of(h.engine.kind),u=g=>{const v=Zr(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,wg.decorKey(h,r),()=>nh.of(d,u,0,r));if(!p)continue;const f=Zr(h,t),m=Math.hypot(f.eastM-l.eastM,f.northM-l.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:d,state:p.at(t),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:m})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const v8="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",b8=`
|
|
8862
|
+
`);let t=_d.shared.get(e);return t||(t=this.fetchFirstAvailable(),_d.shared.set(e,t),t.then(i=>{i.length===0&&_d.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.3")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==Eb?[t,Eb]:[Eb]).map(i=>i+e)}}class Xl{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(e={}){this.platform=new Yt(e)}static covers(e){return Yt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,s)=>Xl.wayOf(i,s))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const s=String(e.properties.nature??""),n=Xl.BY_NATURE[s]??Xl.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),l=Xl.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=Xl.KINDS[s],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:n.surface,widthM:Number.isFinite(r)&&r>0?r:n.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class c8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(Xl.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class Rf{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Yt(e)}static covers(e){return Yt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,s)=>Rf.surfacesOf(i,s))}static surfacesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="Polygon"?[s]:i==="MultiPolygon"?s:[],r=String(e.properties.cleabs??`ign-water-${t}`);return n.flatMap((a,o)=>{const l=a.map(h=>Rf.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:n.length>1?`${r}-${o}`:r,rings:l}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class Xc{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new Rr(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return Xc.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const s=[],n=new Set;for(const r of t){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(n.add(h.ref),i.get(h.ref))),o=Xc.rings(a("inner"));for(const[l,h]of Xc.rings(a("outer")).entries()){const d=o.filter(u=>Xc.contains(h,u[0]));s.push({id:`osm-r${r.id}-${l}`,rings:[h,...d]})}}for(const r of t)if(!(r.type!=="way"||!r.tags||r.id===void 0||n.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Xc.rings([i.get(r.id)??[]]))s.push({id:`osm-w${r.id}`,rings:[a]});return s}static rings(e){const t=(n,r)=>n.lat===r.lat&&n.lng===r.lng,i=e.filter(n=>n.length>=2).map(n=>[...n]),s=[];for(;i.length>0;){let n=i.pop(),r=!0;for(;!t(n[0],n[n.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],l=n[n.length-1];if(t(l,o[0]))n=[...n,...o.slice(1)];else if(t(l,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}n.length>=4&&t(n[0],n[n.length-1])&&s.push(n.slice(0,-1))}return s}static contains(e,t){let i=!1;for(let s=0,n=e.length-1;s<e.length;n=s++){const r=e[s],a=e[n];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class h8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(Rf.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const Sb="https://ufoathome.org/water/index.json";class Dd{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Dd.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.surfaces)?(this.attributionRead=n.attribution,n.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8863
|
+
`);let t=Dd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Dd.shared.set(e,t),t.then(i=>{i.length===0&&Dd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.3")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==Sb?[t,Sb]:[Sb]).map(i=>i+e)}}class xr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=xr.key(e);let i=xr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),xr.asked.set(t,i),i.catch(()=>xr.asked.delete(t))),structuredClone(await i)}static forget(){xr.asked.clear()}static key(e){return`v${xr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await xr.openCache(),s=xr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<xr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&xr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-xr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class Yl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Yt(e)}static covers(e){return Yt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>Yl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=Yl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),l=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=Yl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=Yl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Yl.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(l)?l:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class _n{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new Rr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${_n.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${_n.ROUTES})$"];out body;`;return _n.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=_n.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(v=>dt(v.lat,v.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let d=0;const u=n.filter(v=>v.service===!!r.service);for(const v of _n.samples(a)){d++;const b=_n.waysAt(u,v);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&l.set(w.voltageV,(l.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=v=>[...v.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(l)),g=[...h.entries()].filter(([,v])=>v*4>=d).sort((v,b)=>b[1]-v[1]||v[0].localeCompare(b[0])).map(([v])=>v);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=_n.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=_n.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=_n.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>dt(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=_n.SAMPLE_M/2;a<s;a+=_n.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(_n.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],l=n.path[a+1],h=l.x-o.x,d=l.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=_n.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class kd{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new Rr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${kd.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${_n.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=_n.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=_n.voltageOf(r),l=kd.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=kd.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:kd.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class d8{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!Yl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Hs{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Hs.key(e);let i=Hs.asked.get(t)??Hs.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Hs.asked.set(t,i),s.catch(()=>Hs.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Hs.asked.clear(),Hs.failedAt=-1/0}static key(e){return`v${Hs.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Hs.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Hs.openCache(),s=Hs.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-o<Hs.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-Hs.failedAt<Hs.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Hs.failedAt=this.now(),n)return n;throw a}return i&&Hs.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Hs.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Hs.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const Ab="https://ufoathome.org/railways/index.json";class Rd{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Rd.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
8864
|
+
`);let t=Rd.shared.get(e);return t||(t=this.fetchFirstAvailable(),Rd.shared.set(e,t),t.then(i=>{i.length===0&&Rd.shared.delete(e)})),this.index=t}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.185.3")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==Ab?[t,Ab]:[Ab]).map(i=>i+e)}}function dI(){return{elevation:uI(),imagery:pI(),roads:fI(),water:mI(),railways:gI()}}function uI(){return new a8(new Ht,new lI)}function pI(){return new hI}function fI(){return new _d({fallback:new c8(new Xl,new Hl)})}function mI(){return new Dd({fallback:new xr(new h8(new Rf,new Xc))})}function gI(){return new Rd({fallback:new Hs(new d8(new Yl,new kd))})}const u8=new Set,Qd="show-observer-map",eu="hide-milestones",sh="minified";class ei extends HTMLElement{static get observedAttributes(){return["src",Qd,eu,sh]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Mi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=tv.create();issues=[];issueCheck=0;sightingAudio=new e2;liveSightingAudio;hearInto(e){e?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new e2(e)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>ei.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");ei.setIcon(this.moreButton,e?Je.UNFOLDED:Je.FOLDED);const t=e?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(e){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!e){this.fitControls();return}const t=document.createElement("button");t.type="button",t.id="video-button",t.innerHTML=Je.VIDEO,this.videoElement=t,this.labelVideoButton(),t.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(e,t)},{once:!0}),this.moreButton.after(t),this.fitControls()}async loadVideoButton(e,t){const{VideoButton:i}=await Y(async()=>{const{VideoButton:n}=await import("./VideoButton-CqCZ65oK.js");return{VideoButton:n}},[],import.meta.url);if(this.videoElement!==t)return;const s=new i(e,t);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const e=this.videoElement;!e||this.videoButton||(e.title=this.messages?.recordVideo??"",e.setAttribute("aria-label",e.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(e){e!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,e&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(e){const t=this.currentTime,i=e.caption&&this.sighting.milestones.length>0?Pm(this.sighting.milestones,t):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),r=e.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...e.time?{time:this.formatPosition(t)}:{},...r&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-n.left)/n.width,top:(r.top-n.top)/n.height,width:r.width/n.width,height:r.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.y),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<ei.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},ei.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const s=Mi.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${WN}</style>${VN}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Eu(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Kc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.citedMarks=this.shadow.getElementById("cited-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Qd&&this.applyObserverMapDefault(),e===eu&&this.setMilestonesShown(!this.hasAttribute(eu)),e===sh){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(sh)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(vI)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await Oa.recording(e)}get sightingData(){return If(this.currentSighting)}set sightingData(e){const t=Mn.recording(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=$f(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;set titleShown(e){this.titleHidden=!e,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let s=[];try{const{default:n}=await Y(async()=>{const{default:r}=await import("./sightingSchema-B8Xs45w9.js");return{default:r}},[],import.meta.url);s=new oa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],kf.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(f8,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=(this.messages?.recordingIssues??"").replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=kf.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(e){this.cited=[...e],this.refreshCitedMarks()}refreshCitedMarks(){const e=this.player.seekableDuration;this.citedMarks.replaceChildren(...(e>0?this.cited:[]).map(t=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=ue.INTERVIEW,i.style.left=`${Math.min(Math.max(t.at*1e3/e,0),1)*100}%`;const s=t.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(t.at*1e3)),i}))}sayTimeMoved(e){Math.abs(e-this.timeSaid)<ei.TIME_SAID_EVERY_MS||(this.timeSaid=e,this.dispatchEvent(new CustomEvent(p8,{bubbles:!0,composed:!0,detail:{at:e/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(e){this.toolbar.classList.toggle("hidden",!e),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of t)this.controlsRight.insertBefore(s,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;if(!this.referenceOpacityTouched&&e.length>0){const t=String(e[0].opacity);this.referenceOpacityInput.value!==t&&(this.referenceOpacityInput.value=t,this.severalReferences||this.dispatchReferenceView())}for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(r,l),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),ei.setIcon(this.referencesButton,i?Je.PICTURES_ON:Je.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),ei.setIcon(this.tracesButton,this.tracesShownState?Je.TRACES_ON:Je.TRACES_OFF);const e=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?dh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const s=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(o,l),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=ei.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){if(e.buttons!==0){this.seekPreview.hidden=!0;return}const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=ei.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?Pm(a,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Eu(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const s=ei.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?Pm(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=Vn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<ei.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(ei.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/ei.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/ei.EXPOSURE_STEP_PX),n=Math.min(ei.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=$t.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(e,t){this.sayTimeMoved(e),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:u8;this.canvasRenderer.setStarPoints($t.starPointsOf(this.sighting.instrument,st(this.sighting,e)?.fNumber));const s=(st(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,d=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,l]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?oi.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(Pw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new $N(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*ei.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Je.PLAY:Je.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){ei.icons.get(e)!==t&&(ei.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},ei.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,this.updateStartState(),ei.setIcon(this.playPauseButton,e?Je.PAUSE:Je.PLAY);const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(Qd),t=e===null?this.sighting.observerMap??this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const e=!this.observerMapPanel.hidden;ei.setIcon(this.observerMapButton,e?Je.MAP_ON:Je.MAP_OFF);const t=e?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=ph.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=Mi.fitted(this.observerPath,t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?Mi.expand(e,ei.OBSERVER_MAP_IMAGERY_AHEAD):e,s=Mi.IMAGERY_PX*(t?1+2*ei.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:pI();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,s=this.observerMapView.changed?Mi.expand(e,ei.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,d)=>{for(const u of t)if(!(u.x+u.width<l-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=ei.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=st(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},ei.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Pm(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?dh(this.currentSighting.milestones):[]){const a=st(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?Yr.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg($t.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,dh(this.sighting.milestones).map(t=>t.t)),this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",ei.setIcon(this.milestonesButton,this.milestonesShown?Je.MILESTONES_ON:Je.MILESTONES_OFF);const e=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=st(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Zr(i,e),{lat:n,lng:r}=mr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const s=st(this.currentSighting,this.currentTime),n=Yr.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return Ti.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=ei.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),ei.setIcon(this.miniMuteButton,this.mutedState?Je.MUTED:Je.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){ei.setIcon(this.muteButton,Je.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}ei.setIcon(this.muteButton,this.mutedState?Je.MUTED:Je.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;ei.setIcon(this.fullscreenButton,e?Je.EXIT_FULLSCREEN:Je.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Ls(Ps.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fa(Ps.preferencesFor(this),Pa);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await g5.load(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;updateTimeLabelTitles(){const e=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+t,this.timeEndLabel.title=(this.messages?.duration??"")+t,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.videoButton&&(this.videoButton.messages=e),this.labelVideoButton(),this.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=xh(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?H1(e.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return Dl(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?n2(s2(this.realStartMs+i)):Dl(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Dl(e):Dl(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Dl(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return Dl(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Dl(this.currentSighting.timeline.duration):this.canShowClockTime?n2(s2(this.realStartMs+this.realDurationMs)):Dl(this.realDurationMs)}}function s2(c){const e=new Date(c);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function n2(c){if(c.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return c.second?`${e(c.hour)}:${e(c.minute??0)}:${e(c.second)}`:`${e(c.hour)}:${e(c.minute??0)}`}function Dl(c){const e=Math.round(c/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Hy="rr0-ufo";function dv(){customElements.get(Hy)||customElements.define(Hy,ei)}const p8="timechange",f8="recordingissues",vI="minifiedreset";class Sp{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+Sp.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-Sp.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=Sp.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}class Cd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const g=n.getInterpolatedPoseAt(Math.max(0,m));if(!g||g.lat===void 0||g.lng===void 0)return;const v=dt(g.lat,g.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:g.headingDeg,aboveM:g.elevationM??0,altitudeM:g.altitudeM}},a=r(t-Cd.HALF_SPAN_MS),o=r(t+Cd.HALF_SPAN_MS),l=r(t);if(!a||!o||!l)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*Cd.HALF_SPAN_MS/1e3;if(h/d<Cd.MIN_SPEED_MS)return 0;const u=o.altitudeM!==void 0&&a.altitudeM!==void 0?o.altitudeM-a.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(a.eastM,a.northM)-a.aboveM,p=Math.atan2(u,h)*180/Math.PI;if(l.heading===void 0)return p;const f=Math.atan2(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((l.heading-f)*Math.PI/180))}}const m8=.08,r2=.15,a2=2,g8=2e3;class o2{context;constructor(e){this.context=e}noiseBuffer;voices=new Map;level=1;master;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}Qr.isLive(this.context)&&Qr.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);Qr.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<g8),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const l=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*a2*.5,M},h=l(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=l(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const g=l(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();g.connect(v).connect(b).connect(s);const w=[n,r,h,p,g];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,v,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const l=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,l,m8),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const g=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,g);const v=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,v*n)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,r2/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},r2*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*a2,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Cf{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Cf.BY_KIND[e??"generic"]??Cf.BY_KIND.generic}}class Dn{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(e){return Dn.ROAD_KINDS.includes(e)}static roadOf(e){return e&&Dn.isRoad(e.kind)?e.kind:void 0}static aircraftOf(e){return e&&!Dn.isRoad(e.kind)?e.kind:void 0}static transmission(e){const t=Dn.insulationDb(e),i=[3,4,5].map(s=>t[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(e){return e?e.windowsOpen===!0?Dn.WINDOWS_OPEN_DB:Dn.isRoad(e.kind)?Dn.ROAD_CLOSED_DB:Dn.CANOPIED.includes(e.kind)?Dn.CANOPY_DB:Dn.FUSELAGE_DB:Dn.OPEN_AIR}}class nh{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=nh.SAMPLE_MS,r=[];for(let l=i;l<=s+n/2;l+=n){const h=t(l-n/2),d=t(l+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=1;for(let l=0;l<r.length;l++){const h=r[l],d=(r[Math.min(l+1,r.length-1)]-r[Math.max(l-1,0)])/(2*n/1e3);if(h<nh.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),g=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:g,gear:o})}return new nh(a,i)}at(e){const t=(e-this.startMs)/nh.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class wg{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=h=>{const d=e.observerTrack.getInterpolatedPoseAt(h),u=d?.lat??s?.lat,p=d?.lng??s?.lng;if(u===void 0||p===void 0||!s)return;const f=dt(u,p,s.lat,s.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle,o=Dn.roadOf(a);if(a&&o){const h=Cf.of(o),d=this.drive(`observer:${o}`,wg.trackKey(e),()=>nh.of(h,n,0,r));d&&i.push({id:"observer",profile:h,state:d.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const l=n(t);for(const h of e.decor){if(!h.engine||!l)continue;const d=Cf.of(h.engine.kind),u=g=>{const v=Zr(h,g);return{eastM:v.eastM,northM:v.northM}},p=this.drive(`decor:${h.id}`,wg.decorKey(h,r),()=>nh.of(d,u,0,r));if(!p)continue;const f=Zr(h,t),m=Math.hypot(f.eastM-l.eastM,f.northM-l.northM,f.altitudeM);i.push({id:`decor:${h.id}`,profile:d,state:p.at(t),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:m})}return i}drive(e,t,i){const s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const v8="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",b8=`
|
|
8865
8865
|
<div class="stage" id="stage">
|
|
8866
8866
|
<div class="frame" id="frame">
|
|
8867
8867
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -11477,7 +11477,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
11477
11477
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
11478
11478
|
}
|
|
11479
11479
|
`,transparent:!0,depthWrite:!1,side:nn,fog:!1,blending:Eh,blendSrc:Sh,blendDst:mf})}static wallReflectance(e,t,i){const s=i(e,1,t);return 2*s/(1+s)}setSurroundings(e){this.uniforms.uSurroundings.value=e}static reflectedResponse(e,t){return Xe.respond(t*Xe.relativeOfResponse(Math.max(e,1e-5)))}}class Sr{static SIZE=64;static MOVE_M=.01;holder=new as;cameras=[];faces=[];target=new pi(Sr.SIZE,Sr.SIZE);white=new vr({color:new le(1,1,1),side:nn});scene=new ea;cabin;meshes=0;eye=new I;scratch=new I;constructor(){const e=[[new I(1,0,0),new I(0,1,0)],[new I(-1,0,0),new I(0,1,0)],[new I(0,1,0),new I(0,0,1)],[new I(0,-1,0),new I(0,0,-1)],[new I(0,0,1),new I(0,1,0)],[new I(0,0,-1),new I(0,1,0)]];for(const[t,i]of e){const s=new Rn(90,1,.02,20);s.up.copy(i),s.lookAt(t),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(Sr.SIZE*Sr.SIZE*4))}this.scene.background=new le(0,0,0)}get any(){return this.cabin!==void 0}update(e,t,i){if(!t){this.forget();return}t.updateWorldMatrix(!0,!0);const s=this.scratch.copy(i);t.worldToLocal(s);let n=0;t.traverse(r=>{r.isMesh&&n++}),!(t===this.cabin&&n===this.meshes&&s.distanceTo(this.eye)<Sr.MOVE_M)&&(this.cabin=t,this.meshes=n,this.eye.copy(s),this.draw(e,t))}hides(e){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let t=0;t<6;t++){const i=this.cameras[t],s=this.scratch.copy(e).transformDirection(i.matrixWorldInverse);if(s.z>=0)continue;const n=s.x/-s.z,r=s.y/-s.z;if(Math.abs(n)>1||Math.abs(r)>1)continue;const a=Math.min(Sr.SIZE-1,Math.floor((n+1)/2*Sr.SIZE)),o=Math.min(Sr.SIZE-1,Math.floor((r+1)/2*Sr.SIZE));return this.faces[t][(o*Sr.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(e,t){t.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];t.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof dl))return;const l=new be(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const s=e.getRenderTarget(),n=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),e.setRenderTarget(this.target),e.clear(),e.render(this.scene,a),_g.now(e,this.target,0,0,Sr.SIZE,Sr.SIZE,this.faces[r])}e.setRenderTarget(s),e.shadowMap.autoUpdate=n;for(const r of i)r.removeFromParent()}}const Nb="https://ufoathome.org/models/index.json";class Cp{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??z9()}async entries(e){const t=await this.load();return e?t.filter(i=>[i.kind].flat().includes(e)):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
11480
|
-
`);let t=Cp.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cp.shared.set(e,t),t.then(i=>{i.length===0&&Cp.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function z9(){const c=`?v=${encodeURIComponent("0.185.
|
|
11480
|
+
`);let t=Cp.shared.get(e);return t||(t=this.fetchFirstAvailable(),Cp.shared.set(e,t),t.then(i=>{i.length===0&&Cp.shared.delete(e)})),this.loading=t}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function z9(){const c=`?v=${encodeURIComponent("0.185.3")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==Nb?[e,Nb]:[Nb]).map(t=>t+c)}const ew=et.point("decorModels").provide(et.BUILT_IN,[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new Cp}]);class Op{constructor(e,t=ew){this.preferredId=e,this.sources=t}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const e=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(e?[e,...this.sources.filter(i=>i!==e)]:[]).map(i=>{let s=this.built.get(i);return s||(s=i.create(),this.built.set(i,s)),s})}entries(e){const t=this.catalogues()[0];return t?t.entries(e):Promise.resolve([])}async entry(e){for(const t of this.catalogues()){const i=await t.entry(e).catch(()=>{});if(i)return i}}async moduleOf(e){const t=et.point("decorModels");for(const i of this.sources){const s=t.ownerOf(i.id);if(!(s===void 0||s===et.BUILT_IN)&&await this.catalogueOf(i).entry(e).catch(()=>{}))return s}}catalogueOf(e){return this.catalogues(),this.built.get(e)}}async function Fb(c){const{GLTFLoader:e}=await Y(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-D7spTlJl.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,s)=>{t.load(c,n=>i(Object.assign(n.scene,{animations:n.animations})),void 0,n=>s(new Error(`Could not load 3D model ${c}: ${n instanceof Error?n.message:String(n)}`)))})}class Kr{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new be(new er(2,2),new Nt({uniforms:{uColor:{value:new le(0,0,0)},uRadius:{value:1}},vertexShader:Kr.VERTEX,fragmentShader:Kr.FRAGMENT,transparent:!0,depthWrite:!1,blending:ln,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(e,t,i,s){const n=Math.max(e,s*Kr.MIN_ANGLE_RAD),r=Kr.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(Kr.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Kr.MAX_SHARE*Kr.FILL*Math.PI))}static VERTEX=`
|
|
11481
11481
|
uniform float uRadius;
|
|
11482
11482
|
varying vec2 vOffset;
|
|
11483
11483
|
void main() {
|