trackswap 0.2.2 → 0.2.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/index.js CHANGED
@@ -1,29 +1,29 @@
1
- var Q=class extends Error{constructor(t,_,I={}){super(_),this.name="TrackSwapError",this.code=t,this.format=I.format,this.cause=I.cause}};function t_(R,t,_,I){if(R instanceof Q)return R;let A=R instanceof Error?R.message:String(R);return new Q(t,`${_}: ${A}`,{format:I,cause:R})}var y=class{constructor(){this.version="1.0.0";this.priority=100}async initialize(t){t.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(t){t.metadata.delete(`plugin:${this.name}:initialized`)}async validate(t){return!0}};var n_="trackswap-0.2.2-health-ir-v1",ot=new Set(["timestampCorrelationMesgs","monitoringInfoMesgs","monitoringMesgs","monitoringHrDataMesgs","stressLevelMesgs","respirationRateMesgs","spo2DataMesgs","hrvStatusSummaryMesgs","hrvValueMesgs","sleepLevelMesgs","sleepAssessmentMesgs","napEventMesgs","hsaStepDataMesgs","hsaSpo2DataMesgs","hsaStressDataMesgs","hsaRespirationDataMesgs","hsaHeartRateDataMesgs","hsaBodyBatteryDataMesgs","hsaWristTemperatureDataMesgs","skinTempOvernightMesgs","sleepDisruptionSeverityPeriodMesgs","sleepDisruptionOvernightSeverityMesgs"]),rt=new Set([...ot].filter(R=>R!=="timestampCorrelationMesgs")),mt=new Set(["fileIdMesgs","fileCreatorMesgs","deviceInfoMesgs","deviceSettingsMesgs","softwareMesgs","ohrSettingsMesgs","eventMesgs","activityMesgs","sessionMesgs","lapMesgs","recordMesgs","lengthMesgs","courseMesgs","coursePointMesgs","workoutMesgs","workoutStepMesgs","trainingFileMesgs"]),ct=[{field:"steps",metric:"steps",unit:"count",rolloverModulus:2**32,rolloverBits:32},{field:"distance",metric:"distance_m",unit:"m",rolloverModulus:2**32/100,rolloverBits:32},{field:"activeTime",metric:"active_time_s",unit:"s",rolloverModulus:2**32/1e3,rolloverBits:32},{field:"activeCalories",metric:"active_energy_kcal",unit:"kcal",rolloverModulus:2**16,rolloverBits:16},{field:"calories",metric:"total_energy_kcal",unit:"kcal",rolloverModulus:2**16,rolloverBits:16}],at=[{field:"ascent",metric:"ascent_m",unit:"m",intervalStrategy:"previous_timestamp"},{field:"descent",metric:"descent_m",unit:"m",intervalStrategy:"previous_timestamp"},{field:"moderateActivityMinutes",metric:"moderate_activity_time_s",unit:"s",multiplier:60,intervalStrategy:"value_duration"},{field:"vigorousActivityMinutes",metric:"vigorous_activity_time_s",unit:"s",multiplier:60,intervalStrategy:"value_duration"}],Ht=631065600,I_=2**16,Mt=18*60*60,xt=new Set([65519,65518]),et=5;function X(R){return R&&typeof R=="object"?R:{}}function V(R){if(typeof R=="number")return Number.isFinite(R)?R:void 0;if(typeof R!="string"||R.trim()==="")return;let t=Number(R);return Number.isFinite(t)?t:void 0}function v(R){if(R instanceof Date&&Number.isFinite(R.valueOf()))return R;if(typeof R!="string"&&typeof R!="number"||typeof R=="string"&&R.trim()==="")return;let t=new Date(R);return Number.isFinite(t.valueOf())?t:void 0}function St(R){return st(R)?.toISOString().replace(/Z$/,"")}function st(R){if(R instanceof Date&&Number.isFinite(R.valueOf()))return R;if(typeof R=="string"&&!/^\s*[-+]?\d+(?:\.\d+)?\s*$/.test(R))return v(R);let t=V(R);if(!(t===void 0||t<0))return new Date((t+Ht)*1e3)}function p(R,t,_){return{messageName:R,messageIndex:t,fieldName:_}}function Dt(R,t){return Object.fromEntries(t.map(_=>[_,R[_]]).filter(([,_])=>typeof _=="number"?Number.isFinite(_):["string","boolean"].includes(typeof _)))}function Vt(R){return Object.fromEntries(Object.entries(R).filter(([,t])=>Array.isArray(t)&&t.length>0).map(([t,_])=>[t,_?.length??0]))}function pt(R){let t=[];return((R.activityMesgs?.length??0)>0||(R.sessionMesgs?.length??0)>0)&&t.push("activity"),[...rt].some(_=>(R[_]?.length??0)>0)&&t.push("health"),((R.workoutMesgs?.length??0)>0||(R.workoutStepMesgs?.length??0)>0)&&t.push("workout"),(R.courseMesgs?.length??0)>0&&t.push("course"),t.length===0&&((R.deviceInfoMesgs?.length??0)>0||(R.fileIdMesgs?.length??0)>0)&&t.push("device"),t.length>0?t:["unknown"]}function _I(R){let t=String(R??"").trim().toLowerCase().replace(/[_\s-]+/g,"");return t.includes("awake")?"awake":t.includes("deep")?"deep":t.includes("light")?"light":t.includes("rem")?"rem":t.includes("unmeasurable")?"unmeasurable":t.includes("sleep")?"sleeping":`vendor:${t||"unknown"}`}function tI(R,t=0){return new Date(R.valueOf()+t*1e3).toISOString().slice(0,10)}function Bt(R,t,_=0){return tI(new Date(Math.max(R.valueOf(),t.valueOf()-1)),_)}function Ct(R){let t=V(R);return t===void 0?void 0:t*60}function II(R,t){let _=[],I=(n,L,E,f,G)=>{let U=v(E.timestamp),K=st(E.localTimestamp);if(!U||!K)return;let s=Math.round((K.valueOf()-U.valueOf())/1e3),B=p(n,L,"localTimestamp");if(Math.abs(s)>Mt){t(B);return}_.push({at:U,offsetSeconds:s,priority:f,strategy:G,source:B})};(R.timestampCorrelationMesgs??[]).forEach((n,L)=>{I("timestampCorrelationMesgs",L,X(n),3,"timestamp_correlation")});for(let n of["monitoringInfoMesgs","monitoringMesgs","skinTempOvernightMesgs"])(R[n]??[]).forEach((L,E)=>{I(n,E,X(L),1,"inferred")});(R.napEventMesgs??[]).forEach((n,L)=>{let E=X(n);for(let[f,G]of[["startTime","startTimezoneOffset"],["endTime","endTimezoneOffset"]]){let U=v(E[f]),K=Ct(E[G]);if(!U||K===void 0)continue;let s=p("napEventMesgs",L,G);if(Math.abs(K)>Mt){t(s);continue}_.push({at:U,offsetSeconds:K,priority:2,strategy:"explicit_offset",source:s})}}),_.sort((n,L)=>n.at.valueOf()-L.at.valueOf()||L.priority-n.priority);let A=_.filter((n,L)=>L===0||n.at.valueOf()!==_[L-1].at.valueOf()).map(({at:n,offsetSeconds:L})=>({at:n,offsetSeconds:L})),T=_.find(({strategy:n})=>n==="timestamp_correlation")?.strategy??_.find(({strategy:n})=>n==="explicit_offset")?.strategy??_.find(({strategy:n})=>n==="inferred")?.strategy??"unknown";return{offsets:A,strategy:T}}function AI(R,t){let _=V(R);if(!t||!Number.isInteger(_)||_<0||_>=I_)return;let I=Math.floor(t.valueOf()/1e3)-Ht,A=Math.floor(I/I_)*I_+_;return A<I&&(A+=I_),new Date((A+Ht)*1e3)}function TI(R){let t,_,I,A,T,n;return(R.monitoringMesgs??[]).map(L=>{let E=X(L),G=v(E.timestamp)??AI(E.timestamp16,t);G&&(t=G),G&&(!_||G>_)&&(I=_,_=G);let U=I;E.activityType!==void 0&&(A=E.activityType),E.deviceIndex!==void 0&&(n=E.deviceIndex);let K=E.intensity??E.activityLevel;return K!==void 0&&(T=K),{message:E,timestamp:G,intervalStartTime:U,deviceIndex:n,activityType:A,intensity:T}})}function Z(R,t){let _;for(let I of R){if(I.at>t)break;_=I.offsetSeconds}return _??R[0]?.offsetSeconds}function A_(R,t){if(t!==void 0)return new Date(R.valueOf()+t*1e3).toISOString().replace(/Z$/,"")}function nI(R,t,_,I){return t>=R?{value:t-R}:R>=_*.75&&R<_&&t>=0&&t<=_*.25?{value:_-R+t,rolloverBits:I}:null}function Kt(R){return R>=1&&R<=100?"valid":R===-1?"off_wrist":R===-2?"motion":R===-3?"not_enough_data":R===-4?"recovering":R===-5?"unidentified":R===-16?"gap":R===0||R>100?"invalid":"unknown"}function RI(R){return R>=0&&R<=100?"valid":Kt(R)}function LI(R){return R===255?"invalid":R===254?"motion":R===253?"off_wrist":R===252?"not_enough_data":R===2.4?"gap":R>=1&&R<=100?"valid":"invalid"}function i(R,t,_){return new Date(R.valueOf()+t*_*1e3)}function EI(R){let t=new Map,_={};R.warnings.forEach(I=>{_[I.code]=(_[I.code]??0)+1;let A=t.get(I.code)??[];A.length<et&&(A.push(I),t.set(I.code,A))}),R.warningCounts=_,R.warnings=[...t.values()].flat()}function OI(R){return R===-1?"off_wrist":R===-2?"motion":R===-3?"invalid":R>0&&R<=100?"valid":"invalid"}function ht(R,t={},_={}){let I=Vt(R),A=Object.fromEntries(Object.entries(I).filter(([H])=>ot.has(H))),T=Object.fromEntries(Object.entries(I).filter(([H])=>!ot.has(H)&&!mt.has(H))),n={sdkProfileVersion:_.sdkProfileVersion,parserVersion:n_,messageCounts:I,recognizedMessageCounts:A,unknownMessageCounts:T,invalidValueCounts:{},warningCounts:{},warnings:[]};t.includeUnknownMessages&&(n.unknownMessages=Object.fromEntries(Object.keys(T).map(H=>[H,R[H]??[]])));let L=[],E=[],f=[],G=[],U=[],K=II(R,H=>{n.warnings.push({code:"GARMIN_HEALTH_INVALID_TIMEZONE_OFFSET",message:"Ignored an implausible FIT timezone offset",source:H})}),{offsets:s}=K,B=H=>{let d=H.offsetSeconds??Z(s,H.timestamp);if(H.offsetSeconds=d,H.localTimestamp??=A_(H.timestamp,d),L.push(H),U.push(H.timestamp),H.status!=="valid"){let o=`${H.metric}:${H.status}`;n.invalidValueCounts[o]=(n.invalidValueCounts[o]??0)+1}},k=new Map;TI(R).forEach(({message:H,timestamp:d,intervalStartTime:o,deviceIndex:C,activityType:D,intensity:F},l)=>{if(!d){n.warnings.push({code:"GARMIN_HEALTH_NO_TIMESTAMP",message:"Monitoring message has no valid timestamp",source:p("monitoringMesgs",l)});return}U.push(d);let W=V(H.heartRate);if(W!==void 0){let g=W>0?"valid":"gap";B({metric:"heart_rate_bpm",timestamp:d,localTimestamp:St(H.localTimestamp),value:g==="valid"?W:void 0,unit:"bpm",status:g,aggregation:"instant",source:p("monitoringMesgs",l,"heartRate"),attributes:g==="valid"?void 0:{rawValue:W}})}let M=V(H.temperature);M!==void 0&&B({metric:"temperature_c",timestamp:d,localTimestamp:St(H.localTimestamp),value:M,unit:"degC",status:"valid",aggregation:"mean",source:p("monitoringMesgs",l,"temperature")});for(let g of ct){let h=V(H[g.field]);if(h===void 0)continue;let b=[C??"device",D??"activity",g.field].join(":"),w=k.get(b);if(w&&d>w.timestamp){let N=nI(w.value,h,g.rolloverModulus,g.rolloverBits);if(N){N.rolloverBits&&n.warnings.push({code:"GARMIN_HEALTH_ACCUMULATOR_ROLLOVER",message:`${g.field} accumulator rolled over at ${N.rolloverBits} bits`,source:p("monitoringMesgs",l,g.field)});let e=Z(s,w.timestamp);E.push({metric:g.metric,startTime:w.timestamp,endTime:d,localStartTime:A_(w.timestamp,e),offsetSeconds:e,value:N.value,unit:g.unit,status:"valid",activityType:D===void 0?void 0:String(D),intensity:F===void 0?void 0:String(F),source:p("monitoringMesgs",l,g.field),attributes:t.health?.retainCumulativeValues===!1?void 0:{rawCumulativeValue:h}})}else n.warnings.push({code:"GARMIN_HEALTH_ACCUMULATOR_RESET",message:`${g.field} accumulator decreased; a new accumulation window was started`,source:p("monitoringMesgs",l,g.field)})}k.set(b,{timestamp:d,value:h})}for(let g of at){let h=V(H[g.field]);if(h===void 0||h<0)continue;let b=h*(g.multiplier??1),w=g.intervalStrategy==="value_duration"?new Date(d.valueOf()-b*1e3):o;if(!w||w>=d)continue;let N=Z(s,w);U.push(w),E.push({metric:g.metric,startTime:w,endTime:d,localStartTime:A_(w,N),offsetSeconds:N,value:b,unit:g.unit,status:"valid",activityType:D===void 0?void 0:String(D),intensity:F===void 0?void 0:String(F),source:p("monitoringMesgs",l,g.field)})}}),(R.monitoringHrDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp);if(!C)return;[{field:"currentDayRestingHeartRate",metric:"resting_heart_rate_bpm"},{field:"restingHeartRate",metric:"resting_heart_rate_7_day_bpm"}].forEach(({field:F,metric:l})=>{let W=V(o[F]);if(W===void 0)return;let M=W>0?"valid":"invalid";B({metric:l,timestamp:C,value:M==="valid"?W:void 0,unit:"bpm",status:M,aggregation:"latest",source:p("monitoringHrDataMesgs",d,F),attributes:M==="valid"?void 0:{rawValue:W}})})}),(R.stressLevelMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.stressLevelTime),D=V(o.stressLevelValue);if(!C||D===void 0)return;let F=Kt(D);B({metric:"stress_level",timestamp:C,value:F==="valid"?D:void 0,unit:"score",status:F,aggregation:"instant",source:p("stressLevelMesgs",d,"stressLevelValue"),attributes:F==="valid"?void 0:{rawValue:D}})}),(R.respirationRateMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.respirationRate);if(!C||D===void 0)return;let F=OI(D);B({metric:"respiration_rate_bpm",timestamp:C,value:F==="valid"?D:void 0,unit:"breaths/min",status:F,aggregation:"instant",source:p("respirationRateMesgs",d,"respirationRate"),attributes:F==="valid"?void 0:{rawValue:D}})}),(R.spo2DataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.readingSpo2);if(!C||D===void 0)return;let F=V(o.readingConfidence),l=D<=0||D>100?"invalid":F!==void 0&&F<=0?"low_confidence":"valid";B({metric:"spo2_percent",timestamp:C,value:l==="invalid"?void 0:D,unit:"percent",status:l,quality:F,aggregation:"instant",source:p("spo2DataMesgs",d,"readingSpo2"),attributes:{measurementMode:o.mode===void 0?null:String(o.mode),...l==="invalid"?{rawValue:D}:{}}})}),(R.hrvValueMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.value);if(!C||D===void 0)return;let F=D>0?"valid":"invalid";B({metric:"hrv_rmssd_ms",timestamp:C,value:F==="valid"?D:void 0,unit:"ms",status:F,aggregation:"mean",source:p("hrvValueMesgs",d,"value"),attributes:{windowSeconds:300,...F==="valid"?{}:{rawValue:D}}})}),(R.hrvStatusSummaryMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp);f.push({summaryType:"hrv_status",externalId:`fit:hrv-status:${C?.toISOString()??d}`,startTime:C,metrics:Dt(o,["weeklyAverage","lastNightAverage","lastNight5MinHigh","baselineLowUpper","baselineBalancedLower","baselineBalancedUpper","status"]),source:p("hrvStatusSummaryMesgs",d)}),C&&U.push(C)}),(R.monitoringInfoMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp);f.push({summaryType:"device",externalId:`fit:monitoring-info:${C?.toISOString()??d}`,startTime:C,offsetSeconds:C?Z(s,C):void 0,metrics:Dt(o,["restingMetabolicRate","activityType","cyclesToDistance","cyclesToCalories"]),source:p("monitoringInfoMesgs",d)}),C&&U.push(C)}),(R.skinTempOvernightMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp);if(!C)return;[{field:"averageDeviation",metric:"skin_temperature_deviation_c"},{field:"average7DayDeviation",metric:"skin_temperature_7_day_deviation_c"},{field:"nightlyValue",metric:"skin_temperature_nightly_c"}].forEach(({field:F,metric:l})=>{let W=V(o[F]);W!==void 0&&B({metric:l,timestamp:C,localTimestamp:St(o.localTimestamp),value:W,unit:"degC",status:"valid",aggregation:"mean",source:p("skinTempOvernightMesgs",d,F)})})});let P=(R.sleepLevelMesgs??[]).map((H,d)=>({message:X(H),messageIndex:d,timestamp:v(X(H).timestamp)})).filter(H=>H.timestamp!==void 0).sort((H,d)=>H.timestamp.valueOf()-d.timestamp.valueOf());if(P.length>=2){let H=X(R.sleepAssessmentMesgs?.[0]),d=[];for(let F=0;F<P.length-1;F+=1){let l=P[F],W=P[F+1];if(W.timestamp<=l.timestamp)continue;let M={segmentType:_I(l.message.sleepLevel),startTime:l.timestamp,endTime:W.timestamp,status:"valid",source:p("sleepLevelMesgs",l.messageIndex,"sleepLevel")},g=d.at(-1);g&&g.segmentType===M.segmentType&&g.endTime.valueOf()===M.startTime.valueOf()?g.endTime=M.endTime:d.push(M)}let o=P[0].timestamp,C=P.at(-1).timestamp;U.push(o,C);let D=Z(s,C);G.push({sessionType:"sleep",externalId:`fit:sleep:${o.toISOString()}:${C.toISOString()}`,startTime:o,endTime:C,startOffsetSeconds:Z(s,o),endOffsetSeconds:D,calendarDate:Bt(o,C,D),segments:d,metrics:Dt(H,["combinedAwakeScore","awakeTimeScore","awakeningsCountScore","deepSleepScore","sleepDurationScore","lightSleepScore","overallSleepScore","sleepQualityScore","sleepRecoveryScore","remSleepScore","sleepRestlessnessScore","awakeningsCount","interruptionsScore","averageStressDuringSleep"]),source:p("sleepLevelMesgs",P[0].messageIndex),attributes:{calendarDateStrategy:D===void 0?"sleep_end_utc_fallback_date":"sleep_end_local_date"}})}else P.length>0&&n.warnings.push({code:"GARMIN_HEALTH_SLEEP_BOUNDARY_INCOMPLETE",message:"Sleep level data does not contain enough boundaries",source:p("sleepLevelMesgs",P[0].messageIndex)});for(let H of["sleepDisruptionSeverityPeriodMesgs","sleepDisruptionOvernightSeverityMesgs"])(R[H]??[]).forEach((d,o)=>{let C=X(d),D=v(C.timestamp);!D||C.severity===void 0||(U.push(D),f.push({summaryType:"sleep",externalId:`fit:${H}:${C.messageIndex??o}:${D.toISOString()}`,startTime:D,offsetSeconds:Z(s,D),metrics:{severity:String(C.severity)},source:p(H,o,"severity")}))});return(R.napEventMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.startTime),D=v(o.endTime),F=o.isDeleted===!0;if(!C||!D||D<C||!F&&D.valueOf()===C.valueOf())return;let l=Ct(o.startTimezoneOffset),W=Ct(o.endTimezoneOffset);U.push(C,D),G.push({sessionType:"nap",externalId:`fit:nap:${o.messageIndex??d}:${C.toISOString()}`,startTime:C,endTime:D,startOffsetSeconds:l,endOffsetSeconds:W,calendarDate:Bt(C,D,W??l),deleted:F,segments:[],metrics:{},source:p("napEventMesgs",d),attributes:{source:o.source===void 0?null:String(o.source),feedback:o.feedback===void 0?null:String(o.feedback),updateTimestamp:v(o.updateTimestamp)?.toISOString()??null}})}),(R.hsaStepDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.steps)?o.steps:[];!C||!D||D<=0||xt.has(D)||F.forEach((l,W)=>{let M=V(l);if(M===void 0||M<0)return;let g=i(C,D,W),h=new Date(g.valueOf()+D*1e3),b=Z(s,g);U.push(g,h),E.push({metric:"steps",startTime:g,endTime:h,localStartTime:A_(g,b),offsetSeconds:b,value:M,unit:"count",status:"valid",source:p("hsaStepDataMesgs",d,"steps"),attributes:{sequenceIndex:W,intervalSeconds:D}})})}),(R.hsaSpo2DataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.readingSpo2)?o.readingSpo2:[],l=Array.isArray(o.confidence)?o.confidence:[];!C||!D||D<=0||F.forEach((W,M)=>{let g=V(W);if(g===void 0)return;let h=V(l[M]),b=g<70||g>100||g===240?"invalid":h!==void 0&&h<=0?"low_confidence":"valid";B({metric:"spo2_percent",timestamp:i(C,D,M),value:b==="invalid"?void 0:g,unit:"percent",status:b,quality:h,aggregation:"instant",source:p("hsaSpo2DataMesgs",d,"readingSpo2"),attributes:{sequenceIndex:M,intervalSeconds:D,...b==="invalid"?{rawValue:g}:{}}})})}),(R.hsaStressDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.stressLevel)?o.stressLevel:[];!C||!D||D<=0||F.forEach((l,W)=>{let M=V(l);if(M===void 0)return;let g=RI(M);B({metric:"stress_level",timestamp:i(C,D,W),value:g==="valid"?M:void 0,unit:"score",status:g,aggregation:"instant",source:p("hsaStressDataMesgs",d,"stressLevel"),attributes:{sequenceIndex:W,intervalSeconds:D,...g==="valid"?{}:{rawValue:M}}})})}),(R.hsaRespirationDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.respirationRate)?o.respirationRate:[];!C||!D||D<=0||F.forEach((l,W)=>{let M=V(l);if(M===void 0)return;let g=LI(M);B({metric:"respiration_rate_bpm",timestamp:i(C,D,W),value:g==="valid"?M:void 0,unit:"breaths/min",status:g,aggregation:"instant",source:p("hsaRespirationDataMesgs",d,"respirationRate"),attributes:{sequenceIndex:W,intervalSeconds:D,...g==="valid"?{}:{rawValue:M}}})})}),(R.hsaHeartRateDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.heartRate)?o.heartRate:[],l=V(o.status);!C||!D||D<=0||F.forEach((W,M)=>{let g=V(W);if(g===void 0)return;let h=g===0?"gap":l===1?"valid":l===0?"low_confidence":"unknown";B({metric:"heart_rate_bpm",timestamp:i(C,D,M),value:h==="gap"?void 0:g,unit:"bpm",status:h,aggregation:"instant",source:p("hsaHeartRateDataMesgs",d,"heartRate"),attributes:{sequenceIndex:M,intervalSeconds:D,measurementStatus:l??null,...h==="gap"?{rawValue:g}:{}}})})}),(R.hsaWristTemperatureDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval),F=Array.isArray(o.value)?o.value:[];!C||!D||D<=0||F.forEach((l,W)=>{let M=V(l);M!==void 0&&B({metric:"wrist_temperature_c",timestamp:i(C,D,W),value:M,unit:"degC",status:"valid",aggregation:"instant",source:p("hsaWristTemperatureDataMesgs",d,"value"),attributes:{sequenceIndex:W,intervalSeconds:D}})})}),(R.hsaBodyBatteryDataMesgs??[]).forEach((H,d)=>{let o=X(H),C=v(o.timestamp),D=V(o.processingInterval)??0;if(!C||D<=0)return;[{field:"level",metric:"body_battery_level",unit:"score"},{field:"charged",metric:"body_battery_charged",unit:"score"},{field:"uncharged",metric:"body_battery_drained",unit:"score"}].forEach(({field:l,metric:W,unit:M})=>{(Array.isArray(o[l])?o[l]:[]).forEach((h,b)=>{let w=V(h);if(w===void 0)return;let N=l==="level"&&w===-16?"gap":l==="level"&&(w<0||w>100)?"invalid":"valid";B({metric:W,timestamp:i(C,D,b),value:N==="valid"?w:void 0,unit:M,status:N,aggregation:"instant",source:p("hsaBodyBatteryDataMesgs",d,l),attributes:{sequenceIndex:b,intervalSeconds:D,...N==="valid"?{}:{rawValue:w}}})})})}),L.sort((H,d)=>H.timestamp.valueOf()-d.timestamp.valueOf()),E.sort((H,d)=>H.startTime.valueOf()-d.startTime.valueOf()),G.sort((H,d)=>H.startTime.valueOf()-d.startTime.valueOf()),U.sort((H,d)=>H.valueOf()-d.valueOf()),EI(n),{schemaVersion:"1",observedStart:U[0],observedEnd:U.at(-1),timezone:{strategy:K.strategy,offsets:s},points:L,intervals:t.health?.reconstructIntervals===!1?[]:E,summaries:f,sessions:G,diagnostics:n}}var T_=class extends y{constructor(){super(...arguments);this.name="HealthStructurePlugin";this.priority=20}structureData(_,I){let A=I.userData?.fitDocumentOptions??{},T=pt(_);return{healthDocument:T.includes("health")?ht(_,A,{sdkProfileVersion:I.metadata.get("fit-sdk-profile-version")}):void 0,fitDocumentMetadata:{detectedKinds:T,messageCounts:Vt(_)}}}};var R_=(S=>(S[S.GENERIC=0]="GENERIC",S[S.RUNNING=1]="RUNNING",S[S.CYCLING=2]="CYCLING",S[S.TRANSITION=3]="TRANSITION",S[S.FITNESS_EQUIPMENT=4]="FITNESS_EQUIPMENT",S[S.SWIMMING=5]="SWIMMING",S[S.BASKETBALL=6]="BASKETBALL",S[S.SOCCER=7]="SOCCER",S[S.TENNIS=8]="TENNIS",S[S.AMERICAN_FOOTBALL=9]="AMERICAN_FOOTBALL",S[S.TRAINING=10]="TRAINING",S[S.WALKING=11]="WALKING",S[S.CROSS_COUNTRY_SKIING=12]="CROSS_COUNTRY_SKIING",S[S.ALPINE_SKIING=13]="ALPINE_SKIING",S[S.SNOWBOARDING=14]="SNOWBOARDING",S[S.ROWING=15]="ROWING",S[S.MOUNTAINEERING=16]="MOUNTAINEERING",S[S.HIKING=17]="HIKING",S[S.MULTISPORT=18]="MULTISPORT",S[S.PADDLING=19]="PADDLING",S[S.FLYING=20]="FLYING",S[S.E_BIKING=21]="E_BIKING",S[S.MOTORCYCLING=22]="MOTORCYCLING",S[S.BOATING=23]="BOATING",S[S.DRIVING=24]="DRIVING",S[S.GOLF=25]="GOLF",S[S.HANG_GLIDING=26]="HANG_GLIDING",S[S.HORSEBACK_RIDING=27]="HORSEBACK_RIDING",S[S.HUNTING=28]="HUNTING",S[S.FISHING=29]="FISHING",S[S.INLINE_SKATING=30]="INLINE_SKATING",S[S.ROCK_CLIMBING=31]="ROCK_CLIMBING",S[S.SAILING=32]="SAILING",S[S.ICE_SKATING=33]="ICE_SKATING",S[S.SKY_DIVING=34]="SKY_DIVING",S[S.SNOWSHOEING=35]="SNOWSHOEING",S[S.SNOWMOBILING=36]="SNOWMOBILING",S[S.STAND_UP_PADDLEBOARDING=37]="STAND_UP_PADDLEBOARDING",S[S.SURFING=38]="SURFING",S[S.WAKEBOARDING=39]="WAKEBOARDING",S[S.WATER_SKIING=40]="WATER_SKIING",S[S.KAYAKING=41]="KAYAKING",S[S.RAFTING=42]="RAFTING",S[S.WINDSURFING=43]="WINDSURFING",S[S.KITESURFING=44]="KITESURFING",S[S.TACTICAL=45]="TACTICAL",S[S.JUMPMASTER=46]="JUMPMASTER",S[S.BOXING=47]="BOXING",S[S.FLOOR_CLIMBING=48]="FLOOR_CLIMBING",S[S.BASEBALL=49]="BASEBALL",S[S.DIVING=53]="DIVING",S[S.HIIT=62]="HIIT",S[S.RACKET=64]="RACKET",S[S.WHEELCHAIR_PUSH_WALK=65]="WHEELCHAIR_PUSH_WALK",S[S.WHEELCHAIR_PUSH_RUN=66]="WHEELCHAIR_PUSH_RUN",S[S.MEDITATION=67]="MEDITATION",S[S.DISC_GOLF=69]="DISC_GOLF",S[S.CRICKET=71]="CRICKET",S[S.RUGBY=72]="RUGBY",S[S.HOCKEY=73]="HOCKEY",S[S.LACROSSE=74]="LACROSSE",S[S.VOLLEYBALL=75]="VOLLEYBALL",S[S.WATER_TUBING=76]="WATER_TUBING",S[S.WAKESURFING=77]="WAKESURFING",S[S.MIXED_MARTIAL_ARTS=80]="MIXED_MARTIAL_ARTS",S[S.SNORKELING=82]="SNORKELING",S[S.DANCE=83]="DANCE",S[S.JUMP_ROPE=84]="JUMP_ROPE",S[S.ALL=254]="ALL",S))(R_||{});var L_=(O=>(O[O.GENERIC=0]="GENERIC",O[O.TREADMILL=1]="TREADMILL",O[O.STREET=2]="STREET",O[O.TRAIL=3]="TRAIL",O[O.TRACK=4]="TRACK",O[O.SPIN=5]="SPIN",O[O.INDOOR_CYCLING=6]="INDOOR_CYCLING",O[O.ROAD=7]="ROAD",O[O.MOUNTAIN=8]="MOUNTAIN",O[O.DOWNHILL=9]="DOWNHILL",O[O.RECUMBENT=10]="RECUMBENT",O[O.CYCLOCROSS=11]="CYCLOCROSS",O[O.HAND_CYCLING=12]="HAND_CYCLING",O[O.TRACK_CYCLING=13]="TRACK_CYCLING",O[O.INDOOR_ROWING=14]="INDOOR_ROWING",O[O.ELLIPTICAL=15]="ELLIPTICAL",O[O.STAIR_CLIMBING=16]="STAIR_CLIMBING",O[O.LAP_SWIMMING=17]="LAP_SWIMMING",O[O.OPEN_WATER=18]="OPEN_WATER",O[O.FLEXIBILITY_TRAINING=19]="FLEXIBILITY_TRAINING",O[O.STRENGTH_TRAINING=20]="STRENGTH_TRAINING",O[O.WARM_UP=21]="WARM_UP",O[O.MATCH=22]="MATCH",O[O.EXERCISE=23]="EXERCISE",O[O.CHALLENGE=24]="CHALLENGE",O[O.INDOOR_SKIING=25]="INDOOR_SKIING",O[O.CARDIO_TRAINING=26]="CARDIO_TRAINING",O[O.INDOOR_WALKING=27]="INDOOR_WALKING",O[O.E_BIKE_FITNESS=28]="E_BIKE_FITNESS",O[O.BMX=29]="BMX",O[O.CASUAL_WALKING=30]="CASUAL_WALKING",O[O.SPEED_WALKING=31]="SPEED_WALKING",O[O.BIKE_TO_RUN_TRANSITION=32]="BIKE_TO_RUN_TRANSITION",O[O.RUN_TO_BIKE_TRANSITION=33]="RUN_TO_BIKE_TRANSITION",O[O.SWIM_TO_BIKE_TRANSITION=34]="SWIM_TO_BIKE_TRANSITION",O[O.ATV=35]="ATV",O[O.MOTOCROSS=36]="MOTOCROSS",O[O.BACKCOUNTRY=37]="BACKCOUNTRY",O[O.RESORT=38]="RESORT",O[O.RC_DRONE=39]="RC_DRONE",O[O.WINGSUIT=40]="WINGSUIT",O[O.WHITEWATER=41]="WHITEWATER",O[O.SKATE_SKIING=42]="SKATE_SKIING",O[O.YOGA=43]="YOGA",O[O.PILATES=44]="PILATES",O[O.INDOOR_RUNNING=45]="INDOOR_RUNNING",O[O.GRAVEL_CYCLING=46]="GRAVEL_CYCLING",O[O.E_BIKE_MOUNTAIN=47]="E_BIKE_MOUNTAIN",O[O.COMMUTING=48]="COMMUTING",O[O.MIXED_SURFACE=49]="MIXED_SURFACE",O[O.NAVIGATE=50]="NAVIGATE",O[O.TRACK_ME=51]="TRACK_ME",O[O.MAP=52]="MAP",O[O.SINGLE_GAS_DIVING=53]="SINGLE_GAS_DIVING",O[O.MULTI_GAS_DIVING=54]="MULTI_GAS_DIVING",O[O.GAUGE_DIVING=55]="GAUGE_DIVING",O[O.APNEA_DIVING=56]="APNEA_DIVING",O[O.APNEA_HUNTING=57]="APNEA_HUNTING",O[O.VIRTUAL_ACTIVITY=58]="VIRTUAL_ACTIVITY",O[O.OBSTACLE=59]="OBSTACLE",O[O.BREATHING=62]="BREATHING",O[O.SAIL_RACE=65]="SAIL_RACE",O[O.ULTRA=67]="ULTRA",O[O.INDOOR_CLIMBING=68]="INDOOR_CLIMBING",O[O.BOULDERING=69]="BOULDERING",O[O.HIIT=70]="HIIT",O[O.AMRAP=73]="AMRAP",O[O.EMOM=74]="EMOM",O[O.TABATA=75]="TABATA",O[O.PICKLEBALL=84]="PICKLEBALL",O[O.PADEL=85]="PADEL",O[O.INDOOR_WHEELCHAIR_WALK=86]="INDOOR_WHEELCHAIR_WALK",O[O.INDOOR_WHEELCHAIR_RUN=87]="INDOOR_WHEELCHAIR_RUN",O[O.INDOOR_HAND_CYCLING=88]="INDOOR_HAND_CYCLING",O[O.SQUASH=94]="SQUASH",O[O.BADMINTON=95]="BADMINTON",O[O.RACQUETBALL=96]="RACQUETBALL",O[O.TABLE_TENNIS=97]="TABLE_TENNIS",O[O.FLY_CANOPY=110]="FLY_CANOPY",O[O.FLY_PARAGLIDE=111]="FLY_PARAGLIDE",O[O.FLY_PARAMOTOR=112]="FLY_PARAMOTOR",O[O.FLY_PRESSURIZED=113]="FLY_PRESSURIZED",O[O.FLY_NAVIGATE=114]="FLY_NAVIGATE",O[O.FLY_TIMER=115]="FLY_TIMER",O[O.FLY_ALTIMETER=116]="FLY_ALTIMETER",O[O.FLY_WX=117]="FLY_WX",O[O.FLY_VFR=118]="FLY_VFR",O[O.FLY_IFR=119]="FLY_IFR",O[O.ALL=254]="ALL",O))(L_||{});function wt(R,t){if(!t)return;let _=t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();for(let I of Object.keys(R)){if(!Number.isNaN(Number(I))||I.toUpperCase()!==_)continue;let A=R[I];return typeof A=="number"?A:void 0}}function SI(R){let t=R.metadata?.fileName?.trim();if(t)return t;let _=R.metadata?.originType;return _?`${_.toLowerCase()}-course`:"course"}function Xt(R){let t=R.activities?.[0],I=[...(R.activities?.flatMap(A=>A.laps??[])??[]).flatMap(A=>A.records??[]),...R.routes?.flatMap(A=>A.records??[])??[],...R.points??[]].filter(A=>A.timestamp!=null&&A.positionLat!=null&&A.positionLong!=null).sort((A,T)=>new Date(A.timestamp).getTime()-new Date(T.timestamp).getTime()).map(A=>({timestamp:A.timestamp,latitude:A.positionLat,longitude:A.positionLong,distance:A.distance,altitude:A.enhancedAltitude??A.altitude,speed:A.enhancedSpeed??A.speed}));if(I.length===0)throw new Error("Cannot build a FIT course without timestamped coordinates");return{name:SI(R),sport:wt(R_,t?.sport)??2,subSport:wt(L_,t?.subSport)??0,records:I,timeCreated:I[0].timestamp}}function vt(){return process.env.TRACKSWAP_FIT_DEBUG==="1"||process.env.TRACKSWAP_DEBUG==="1"}function Y(...R){vt()}function c(...R){vt()}var E_=class{constructor(){this.stage="parse"}async process(t){let _=Date.now();if(!t.rawData)throw new Error("FIT data cannot be empty");try{let I=await this.parseWithFitSDK(t.rawData,t);return t.rawMessages=I,Y("\u{1F389} FIT parsing raw messages:",I),t.performance.parseTime=Date.now()-_,Y(`\u{1F527} FIT parsing completed, contains message types: ${Object.keys(I).join(", ")}`),t}catch(I){throw new Error(`FIT parsing failed: ${I.message}`)}}async parseWithFitSDK(t,_){let{Decoder:I,Profile:A,Stream:T}=await import("@garmin/fitsdk"),n=[A.version?.major,A.version?.minor,A.version?.patch].filter(U=>U!==void 0);n.length>0&&_.metadata.set("fit-sdk-profile-version",n.join("."));let L=T.fromBuffer(t);if(!I.isFIT(L))throw new Error("Not a valid FIT file");let E=new I(L),{messages:f,errors:G}=E.read();return G&&G.length>0&&c("FIT parsing warnings:",G),f}};function DI(R){let t={...R};return t.position_lat!=null&&t.positionLat==null&&(t.positionLat=t.position_lat),t.position_long!=null&&t.positionLong==null&&(t.positionLong=t.position_long),t}var O_=class{constructor(t){this.getConverters=t;this.stage="extract"}async process(t){let _=Date.now();if(!t.rawMessages)throw new Error("Raw messages cannot be empty");let I={};for(let[A,T]of Object.entries(t.rawMessages)){if(!Array.isArray(T)||T.length===0){I[A]=T;continue}let n=this.getConverters(A);if(n.length===0)I[A]=A==="recordMesgs"?T.map(L=>DI(L)):T,Y(`\u{1F4CB} Message type "${A}" has no converter, using raw data`);else{let L=n[0];try{let E=L.convertMessages(T,t);I[A]=E,Y(`\u2705 Message type "${A}" using converter ${L.name}`)}catch(E){t.errors.push(E),I[A]=T,c(`FIT converter "${L.name}" failed for ${A}; raw messages were retained`,E)}}}return t.rawMessages=I,t.performance.extractTime=Date.now()-_,t}},S_=class{constructor(t){this.getStructurePlugins=t;this.stage="structure"}async process(t){let _=Date.now();if(!t.rawMessages)throw new Error("Message data cannot be empty");let I={},A=this.getStructurePlugins();for(let T of A)try{let n=T.structureData(t.rawMessages,t);I={...I,...n},Y(`\u{1F527} Structure plugin ${T.name} processing completed`)}catch(n){throw t.errors.push(n),new Error(`FIT structure plugin "${T.name}" failed: ${n.message}`)}return t.result=I,t.performance.structureTime=Date.now()-_,t}},D_=class{constructor(){this.stage="complete"}async process(t){t.performance.endTime=Date.now();let _=t.performance.endTime-t.performance.startTime;return t.metadata.set("performance",{totalTime:_,parseTime:t.performance.parseTime,extractTime:t.performance.extractTime,structureTime:t.performance.structureTime}),t.stats&&(t.stats.endTime=Date.now(),t.rawMessages&&(t.stats.processedTokens=this.countTotalMessages(t.rawMessages))),Y(`\u2705 FIT processing completed, total time: ${_}ms`),t}countTotalMessages(t){let _=0;return Object.values(t).forEach(I=>{Array.isArray(I)&&(_+=I.length)}),_}};import J from"dayjs";var o_=class extends y{constructor(){super(...arguments);this.name="SessionStructurePlugin";this.priority=10}structureData(_,I){let{sessionMesgs:A,lapMesgs:T,recordMesgs:n,lengthMesgs:L}=_;if(!A?.length)return c("No structured session found, data structure is incomplete"),{};let E=A.map(U=>{let K=J(U.startTime).valueOf(),s=K+(U.totalElapsedTime??0)*1e3,B=J(U.timestamp).valueOf(),k=Math.max(Number.isFinite(s)?s:Number.NEGATIVE_INFINITY,Number.isFinite(B)?B:Number.NEGATIVE_INFINITY),P=U.firstLapIndex,H=U.numLaps,d=typeof P=="number"&&typeof H=="number"?(T??[]).filter(D=>{let F=D.messageIndex;return typeof F=="number"&&F>=P&&F<P+H}):[],o=(d.length>0?d:(T??[]).filter(D=>{let F=J(D.startTime).valueOf();return Number.isFinite(F)&&F>=K&&F<=k+2e3})).sort((D,F)=>J(D.startTime).valueOf()-J(F.startTime).valueOf()),C=o.map((D,F)=>{let l=J(D.startTime).valueOf(),W=J(o[F+1]?.startTime).valueOf(),M=l+(D.totalElapsedTime??0)*1e3,g=Number.isFinite(W)&&W>l,h=g?W:Math.max(M,k),b=n?.filter(Ot=>{let m=J(Ot.timestamp).valueOf();return m>=l&&(g?m<h:m<=h)})||[],w=D.firstLengthIndex??void 0,N=D.numLengths??void 0,e=[];if(w!==void 0&&N!==void 0){let Ot=w+N;e=L?.filter(m=>m.messageIndex>=w&&m.messageIndex<Ot)||[]}return{...D,recordMesgs:b,lengthMesgs:e,messageIndex:D.messageIndex!==void 0?D.messageIndex:0}});return{...U,lapMesgs:C,messageIndex:U.messageIndex!==void 0?U.messageIndex:0}}),f=new Set;for(let U of E)for(let K of U.lapMesgs??[])for(let s of K.recordMesgs??[])s?.timestamp!=null&&f.add(J(s.timestamp).valueOf());let G=0;for(let U of n??[]){if(U?.timestamp==null)continue;let K=J(U.timestamp).valueOf();f.has(K)||G++}return G>0&&(I.metadata.set("fit-unassigned-record-count",G),c(`SessionStructurePlugin: ${G} record(s) did not fall into any lap time window`)),{sessionMesgs:E}}},H_=class extends y{constructor(){super(...arguments);this.name="CourseStructurePlugin";this.priority=10}structureData(_,I){let{courseMesgs:A,lapMesgs:T,recordMesgs:n}=_;if(!A?.length)return{};let L=2e3;return{courseMesgs:A.map(f=>{let G=T?.map(U=>{let K=J(U.startTime).valueOf(),s=J(U.timestamp).valueOf(),B=n?.filter(k=>{let P=J(k.timestamp).valueOf();return P>=K-L&&P<=s+L})||[];return{...U,recordMesgs:B}})||[];return{...f,lapMesgs:G}})}}},C_=class extends y{constructor(){super(...arguments);this.name="FileHeaderPlugin";this.priority=1}structureData(_,I){let{fileIdMesgs:A,fileCreatorMesgs:T,deviceInfoMesgs:n}=_;if(A?.length&&A[0]){let L=A[0];I.fileHeader={type:L.type,manufacturer:L.manufacturer,product:L.product}}return{fileIdMesgs:A,fileCreatorMesgs:T,deviceInfoMesgs:n}}};var f_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.structurePlugins=[];this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultPluginsRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new E_,new O_(t=>this.getConverters(t)),new S_(()=>this.structurePlugins),new D_],Y("\u{1F527} FIT core pipeline processors initialized (fixed and not modifiable)")}async registerDefaultPlugins(){if(this.defaultPluginsRegistered)return;let t=[new C_,new o_,new H_,new T_];for(let _ of t)this.addStructurePlugin(_),this.registeredPlugins.add(_.name);this.defaultPluginsRegistered=!0,Y("\u2705 Default FIT structure plugins auto-registered (FileHeader, Session, Course, etc.)")}addConverterForMessageType(t,_){this.converterPlugins.has(t)||this.converterPlugins.set(t,[]);let I=this.converterPlugins.get(t);I.push(_),I.sort((A,T)=>(A.priority||100)-(T.priority||100))}addStructurePlugin(t){this.structurePlugins.push(t),this.structurePlugins.sort((_,I)=>(_.priority||100)-(I.priority||100))}async registerMessageConverter(t){if(this.registeredPlugins.has(t.name))throw new Error(`Message converter plugin ${t.name} already exists`);t.supportedMessageTypes.forEach(I=>{this.addConverterForMessageType(I,t)}),this.registeredPlugins.add(t.name);let _=t.priority!==void 0?` (priority: ${t.priority})`:"";Y(`\u{1F4E6} Registered FIT message converter: ${t.name}${_}, supported message types: ${t.supportedMessageTypes.join(", ")}`),t.supportedMessageTypes.forEach(I=>{let T=(this.converterPlugins.get(I)||[]).map(n=>`${n.name}(${n.priority||100})`);Y(` \u{1F4CB} Message type "${I}" converter priority: ${T.join(" > ")}`)})}async registerStructurePlugin(t){if(this.registeredPlugins.has(t.name))throw new Error(`Structure plugin ${t.name} already exists`);this.addStructurePlugin(t),this.registeredPlugins.add(t.name);let _=t.priority!==void 0?` (priority: ${t.priority})`:"";Y(`\u{1F3D7}\uFE0F Registered FIT structure plugin: ${t.name}${_}`)}async registerMiddleware(t){let _=this.middlewarePlugins.findIndex(A=>A.name===t.name);_!==-1?(this.middlewarePlugins[_]=t,Y(`\u{1F504} Updated FIT middleware: ${t.name}`)):(this.middlewarePlugins.push(t),this.middlewarePlugins.sort((A,T)=>(A.priority||100)-(T.priority||100)),Y(`\u{1F50C} Registered FIT middleware: ${t.name}`));let I=[];t.onParse&&I.push("onParse"),t.onExtractMessages&&I.push("onExtractMessages"),t.onStructure&&I.push("onStructure"),t.onComplete&&I.push("onComplete"),t.onError&&I.push("onError"),I.length>0&&Y(` \u{1F3A3} Supported hooks: ${I.join(", ")}`)}getConverter(t){let _=this.converterPlugins.get(t);return _&&_.length>0?_[0]:void 0}getConverters(t){return this.converterPlugins.get(t)||[]}unregisterPlugin(t){if(!this.registeredPlugins.has(t))return!1;for(let[A,T]of this.converterPlugins){let n=T.findIndex(L=>L.name===t);n!==-1&&(T.splice(n,1),T.length===0&&this.converterPlugins.delete(A))}let _=this.structurePlugins.findIndex(A=>A.name===t);_!==-1&&this.structurePlugins.splice(_,1);let I=this.middlewarePlugins.findIndex(A=>A.name===t);return I!==-1&&this.middlewarePlugins.splice(I,1),this.registeredPlugins.delete(t),Y(`\u{1F5D1}\uFE0F Removed FIT plugin: ${t}`),!0}async initialize(){if(this.initialized)return;await this.registerDefaultPlugins();let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.structurePlugins,...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.initialize?.(t);this.initialized=!0}async destroy(){if(!this.initialized)return;let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.structurePlugins,...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.destroy?.(t);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(t,_,I){let A=_;for(let T of this.middlewarePlugins){let n=T[t];if(n)try{A=await n.call(T,A,I)||A}catch(L){I.errors.push(L),await T.onError?.(L,I)}}return A}async parseByBuffer(t,_={}){await this.initialize();let I=this.createContext();I.rawData=t,I.userData=_.userData,I.metadata.set("decoder",this);try{for(let A of this.processors)try{switch(A.stage==="parse"&&I.rawData&&(I.rawData=await this.executeMiddlewareHook("onParse",I.rawData,I)),I=await A.process(I),A.stage){case"parse":break;case"extract":I.rawMessages&&(I.rawMessages=await this.executeMiddlewareHook("onExtractMessages",I.rawMessages,I));break;case"structure":I.result&&(I.result=await this.executeMiddlewareHook("onStructure",I.result,I));break;case"complete":I.result&&(I.result=await this.executeMiddlewareHook("onComplete",I.result,I));break}}catch(T){I.errors.push(T);for(let n of this.middlewarePlugins)await n.onError?.(T,I);throw new Error(`FIT pipeline stage "${A.stage}" failed: ${T.message}`)}return Y("\u{1F389} FIT parsing completed",I.result),I.result}catch(A){throw A}}};var oI={file:{course:6,device:1,settings:2,sport:3,activity:4,workout:5,schedules:7,weight:9,totals:10,goals:11,blood_pressure:14,monitoring_a:15,activity_summary:20,monitoring_daily:28,monitoring_b:32,segment_list:35,exd_configuration:40,invalid:0},sport:{generic:0,running:1,cycling:2,transition:3,fitness_equipment:4,swimming:5,basketball:6,soccer:7,tennis:8,american_football:9,training:10,walking:11,cross_country_skiing:12,alpine_skiing:13,snowboarding:14,rowing:15,mountaineering:16,hiking:17,multisport:18,paddling:19,invalid:254},event:{timer:0,workout:3,workout_step:4,power_down:5,power_up:6,off_course:7,session:8,lap:9,course_point:10,battery:11,virtual_partner_pace:12,hr_high_alert:13,hr_low_alert:14,speed_high_alert:15,speed_low_alert:16,cad_high_alert:17,cad_low_alert:18,power_high_alert:19,power_low_alert:20,recovery_hr:21,battery_low:22,time_duration_alert:23,distance_duration_alert:24,calorie_duration_alert:25,activity:26,fitness_equipment:27,length:28,user_marker:32,sport_point:33,calibration:36,front_gear_change:42,rear_gear_change:43,rider_position_change:44,elev_high_alert:45,elev_low_alert:46,comm_timeout:47,invalid:255},event_type:{start:0,stop:1,consecutive_depreciated:2,marker:3,stop_all:4,begin_depreciated:5,end_depreciated:6,end_all_depreciated:7,stop_disable:8,stop_disable_all:9,invalid:255},course_point:{generic:0,summit:1,valley:2,water:3,food:4,danger:5,left:6,right:7,straight:8,first_aid:9,fourth_category:10,third_category:11,second_category:12,first_category:13,hors_category:14,sprint:15,left_fork:16,right_fork:17,middle_fork:18,slight_left:19,sharp_left:20,slight_right:21,sharp_right:22,u_turn:23,segment_start:24,segment_end:25,invalid:255}},r=R=>{let t=oI[R];return{size:1,baseType:0,mapValue:_=>typeof _=="string"?t[_]??255:_,setValue:function(_,I){this.setUint8(_,I)}}},ft={enum_file:r("file"),enum_activity:r("sport"),enum_sport:r("sport"),enum_sub_sport:r("sport"),enum_event:r("event"),enum_event_type:r("event_type"),enum_course_point:r("course_point"),uint8:{size:1,baseType:2,setValue:DataView.prototype.setUint8},sint8:{size:1,baseType:1,setValue:DataView.prototype.setInt8},uint16:{size:2,baseType:132,setValue:DataView.prototype.setUint16},sint16:{size:2,baseType:131,setValue:DataView.prototype.setInt16},uint32:{size:4,baseType:134,setValue:DataView.prototype.setUint32},sint32:{size:4,baseType:133,setValue:DataView.prototype.setInt32},string:{size:0,baseType:7,mapValue:R=>Array.from(Yt(R)),setValue:CI},distance:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:R=>Math.round(R*1e3)},speed:{size:2,baseType:132,setValue:DataView.prototype.setUint16,mapValue:R=>Math.round(R*100)},altitude:{size:2,baseType:132,setValue:DataView.prototype.setUint16,mapValue:R=>Math.round((R+500)*5)},seconds:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:R=>Math.round(R*1e3)},date_time:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:R=>{let t;return R instanceof Date?(t=Math.floor(R.getTime()/1e3),t-631065600):typeof R=="string"?(t=Math.floor(new Date(R).getTime()/1e3),t-631065600):R<631065600?Math.floor(R):(R>9999999999?t=Math.floor(R/1e3):t=Math.floor(R),t-631065600)}},semicircles:{size:4,baseType:133,setValue:DataView.prototype.setInt32,mapValue:R=>Math.round(R/180*2147483648)}};function Pt(R){return Array.from(Yt(R)).length+1}function*Yt(R){for(let t of HI(R))t<128?yield t:t<2048?(yield 192|t>>6,yield 128|t&63):t<65536?(yield 224|t>>12,yield 128|t>>6&63,yield 128|t&63):(yield 240|t>>18,yield 128|t>>12&63,yield 128|t>>6&63,yield 128|t&63);yield 0}function*HI(R){for(let t=0;t<R.length;){let _=R.codePointAt(t);if(_===void 0)break;yield _,t+=_>65535?2:1}}function CI(R,t){for(let _=0;_<t.length;_++)this.setUint8(R+_,t[_])}var dI={file_id:{mesgNum:0,fieldDefns:[{name:"type",number:0,type:"enum_file"},{name:"time_created",number:4,type:"date_time"}]},session:{mesgNum:18,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"start_time",number:2,type:"date_time"},{name:"total_elapsed_time",number:7,type:"seconds"},{name:"total_timer_time",number:8,type:"seconds"},{name:"start_position_lat",number:3,type:"semicircles"},{name:"start_position_long",number:4,type:"semicircles"},{name:"total_distance",number:9,type:"distance"},{name:"total_ascent",number:21,type:"uint16"},{name:"total_descent",number:22,type:"uint16"},{name:"sport",number:5,type:"enum_sport"},{name:"sub_sport",number:6,type:"enum_sub_sport"},{name:"first_lap_index",number:11,type:"uint16"},{name:"num_laps",number:26,type:"uint16"}]},lap:{mesgNum:19,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"start_time",number:2,type:"date_time"},{name:"start_position_lat",number:3,type:"semicircles"},{name:"start_position_long",number:4,type:"semicircles"},{name:"end_position_lat",number:5,type:"semicircles"},{name:"end_position_long",number:6,type:"semicircles"},{name:"total_elapsed_time",number:7,type:"seconds"},{name:"total_timer_time",number:8,type:"seconds"},{name:"total_distance",number:9,type:"distance"},{name:"total_ascent",number:21,type:"uint16"},{name:"total_descent",number:22,type:"uint16"}]},record:{mesgNum:20,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"position_lat",number:0,type:"semicircles"},{name:"position_long",number:1,type:"semicircles"},{name:"altitude",number:2,type:"altitude"},{name:"distance",number:5,type:"distance"},{name:"heart_rate",number:3,type:"uint8"},{name:"cadence",number:4,type:"uint8"},{name:"speed",number:6,type:"speed"},{name:"power",number:7,type:"uint16"}]},event:{mesgNum:21,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"event",number:0,type:"enum_event"},{name:"event_type",number:1,type:"enum_event_type"},{name:"event_group",number:4,type:"uint8"}]},course:{mesgNum:31,fieldDefns:[{name:"name",number:5,type:"string"},{name:"sport",number:4,type:"enum_sport"},{name:"sub_sport",number:7,type:"enum_sub_sport"}]},activity:{mesgNum:34,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"total_timer_time",number:0,type:"seconds"},{name:"num_sessions",number:1,type:"uint16"},{name:"type",number:2,type:"enum_activity"},{name:"event",number:3,type:"enum_event"},{name:"event_type",number:4,type:"enum_event_type"},{name:"local_timestamp",number:5,type:"date_time"},{name:"event_group",number:6,type:"uint8"}]},course_point:{mesgNum:32,fieldDefns:[{name:"timestamp",number:1,type:"date_time"},{name:"position_lat",number:2,type:"semicircles"},{name:"position_long",number:3,type:"semicircles"},{name:"distance",number:4,type:"distance"},{name:"type",number:5,type:"enum_course_point"}]}},UI=(R,t)=>R.map(_=>({..._,value:t[_.name]})).filter(({value:_})=>_!==void 0),d_=class R{static check(t,_,I,A){if(_===void 0)throw new Error(`Message '${t}' not known`);if(I===void 0)throw new Error(`Message '${t}' has no field definitions`);let T=I.map(L=>L.name),n=Object.keys(A).filter(L=>!T.includes(L));if(n.length)throw new Error(`Message '${t}' has no field definitions named '${n}'`)}constructor(t,_,I){let A=dI[_];if(!A)throw new Error(`Unknown message type: ${_}`);let{mesgNum:T,fieldDefns:n}=A;R.check(_,T,n,I),this.localNum=t,this.mesgNum=T,this.fields=UI(n,I)}get mesgDefn(){let t=this.fields.map(({number:_,type:I,value:A})=>{let T=ft[I];if(!T)throw new Error(`Unknown type: ${I}`);let{size:n,baseType:L}=T;return I==="string"?{number:_,size:Pt(A),baseType:L}:{number:_,size:n,baseType:L}});return{localNum:this.localNum,mesgNum:this.mesgNum,fieldDefns:t}}isSameDefn(t){let _=(L,E)=>L.number===E.number&&L.size===E.size&&L.baseType===E.baseType,I=(L,E)=>L.length===E.length&&L.every((f,G)=>_(f,E[G])),{localNum:A,mesgNum:T,fieldDefns:n}=this.mesgDefn;return T===t.mesgNum&&A===t.localNum&&I(n,t.fieldDefns)}get defnRecord(){let{localNum:t,mesgNum:_,fieldDefns:I}=this.mesgDefn,A=6+3*I.length,T=new DataView(new ArrayBuffer(A));T.setUint8(0,64|t),T.setUint8(2,1),T.setUint16(3,_),T.setUint8(5,I.length);let n=6;for(let L of I)T.setUint8(n++,L.number),T.setUint8(n++,L.size),T.setUint8(n++,L.baseType);return T.buffer}get dataRecord(){let{fieldDefns:t}=this.mesgDefn,_=1+t.reduce((T,{size:n})=>T+n,0),I=new DataView(new ArrayBuffer(_));I.setUint8(0,this.localNum);let A=1;for(let{number:T,type:n,value:L}of this.fields){let E=ft[n];if(!E)throw new Error(`Unknown type: ${n}`);let{size:f,setValue:G}=E,U;"mapValue"in E?U=E.mapValue(L):U=L,G&&G.call(I,A,U),A+=f}return I.buffer}};var FI=[0,52225,55297,5120,61441,15360,10240,58369,40961,27648,30720,46081,20480,39937,34817,17408],bt=(R,t)=>(R>>>4^FI[R&15^t])&65535,GI=(R,t,_)=>bt(bt(R,t),_),gI=(R,t)=>GI(R,t&15,t>>>4);function dt(R,t=0){let _=t,I=R instanceof ArrayBuffer?new Uint8Array(R):R;for(let A=0;A<I.length;A++)_=gI(_,I[A]);return _}import lI from"dayjs";var Nt=14,WI=16,MI=2078,BI=776358228,U_=class{constructor(t={}){this.localNum={};this.mesgDefn=[];this.messages=[];this.options={compact:t.compact??!0,defaultActivity:t.defaultActivity??"cycling",defaultSubActivity:t.defaultSubActivity??"generic"}}async encode(t){return this.reset(),this.buildFITContent(t,"activity"),Buffer.from(await this.blob.arrayBuffer())}async encodeCourse(t){return this.reset(),this.buildFITContent(t,"course"),Buffer.from(await this.blob.arrayBuffer())}async encodeToBlob(t,_="activity"){return this.reset(),this.buildFITContent(t,_),this.blob}reset(){this.localNum={},this.mesgDefn=[],this.messages=[]}buildFITContent(t,_){this.buildFileId(t,_),_==="course"?this.buildCourseContent(t):this.buildActivityContent(t)}buildActivityContent(t){let _=t.sessionMesgs||[];if(_.length===0)throw new Error("Activity file must contain at least one Session");let I=0,A=[],T=[];for(let n of _){if(n.lapMesgs&&this.buildEventsFromLaps(n.lapMesgs,A),n.lapMesgs)for(let L of n.lapMesgs)L.recordMesgs&&this.buildRecords(L.recordMesgs);n.lapMesgs&&this.buildLaps(n.lapMesgs),this.buildSession(n),I++,this.buildActivityFromSession(n,T)}A.forEach(n=>this.buildEvent(n)),T.forEach(n=>this.buildActivity(n))}buildCourseContent(t){let _=t.sessionMesgs||[];if(_.length===0)throw new Error("Course file must contain track data");let I=_[0];if(this.buildCourse({name:"course",sport:this.options.defaultActivity}),I.lapMesgs){let A=[];for(let L of I.lapMesgs)L.recordMesgs&&A.push(...L.recordMesgs);A.sort((L,E)=>L.timestamp&&E.timestamp?new Date(L.timestamp).getTime()-new Date(E.timestamp).getTime():(L.distance||0)-(E.distance||0));let T=A[0],n=A[A.length-1];if(I.startTime&&this.buildEvent({timestamp:I.startTime,event:"timer",eventType:"start",eventGroup:0}),A.forEach(L=>this.buildRecord(L)),n.timestamp&&this.buildEvent({timestamp:n.timestamp,event:"timer",eventType:"stop_all",eventGroup:0}),I.lapMesgs)for(let L=0;L<I.lapMesgs.length;L++)this.buildLap(I.lapMesgs[L])}}buildFileId(t,_){let I=t.fileIdMesgs?.[0]||{};this.writeMesg("file_id",{type:_,time_created:I.timeCreated?this.parseTimestamp(I.timeCreated):Date.now(),manufacturer:I.manufacturer,product:I.product,serial_number:I.serialNumber})}buildSession(t){this.writeMesg("session",{timestamp:t.timestamp?t.timestamp:void 0,start_time:t.startTime?t.startTime:void 0,total_elapsed_time:t.totalElapsedTime,total_timer_time:t.totalTimerTime,start_position_lat:t.startPositionLat!=null&&Number.isFinite(t.startPositionLat)?this.convertToSemicircles(t.startPositionLat):void 0,start_position_long:t.startPositionLong!=null&&Number.isFinite(t.startPositionLong)?this.convertToSemicircles(t.startPositionLong):void 0,total_distance:t.totalDistance,total_ascent:t.totalAscent,total_descent:t.totalDescent,sport:t.sport||this.options.defaultActivity,sub_sport:t.subSport||this.options.defaultSubActivity,first_lap_index:t.firstLapIndex||0,num_laps:t.numLaps||t.lapMesgs?.length||1})}buildLaps(t){t.forEach(_=>this.buildLap(_))}buildLap(t){this.writeMesg("lap",{timestamp:t?.timestamp?t.timestamp:void 0,start_time:t?.startTime?t.startTime:void 0,start_position_lat:t?.startPositionLat!=null&&Number.isFinite(t.startPositionLat)?this.convertToSemicircles(t.startPositionLat):void 0,start_position_long:t?.startPositionLong!=null&&Number.isFinite(t.startPositionLong)?this.convertToSemicircles(t.startPositionLong):void 0,end_position_lat:t?.endPositionLat!=null&&Number.isFinite(t.endPositionLat)?this.convertToSemicircles(t.endPositionLat):void 0,end_position_long:t?.endPositionLong!=null&&Number.isFinite(t.endPositionLong)?this.convertToSemicircles(t.endPositionLong):void 0,total_elapsed_time:t?.totalElapsedTime,total_timer_time:t?.totalTimerTime,total_distance:t?.totalDistance,total_ascent:t?.totalAscent,total_descent:t?.totalDescent})}buildRecords(t){t.forEach(_=>this.buildRecord(_))}buildRecord(t){this.writeMesg("record",{timestamp:t.timestamp,position_lat:t?.positionLat!=null&&Number.isFinite(t.positionLat)?this.convertToSemicircles(t.positionLat):void 0,position_long:t?.positionLong!=null&&Number.isFinite(t.positionLong)?this.convertToSemicircles(t.positionLong):void 0,altitude:t?.altitude,enhancedAltitude:t?.enhancedAltitude,distance:t?.distance,heart_rate:t?.heartRate,cadence:t?.cadence,speed:t?.speed,enhancedSpeed:t?.enhancedSpeed,power:t?.power})}buildEvent(t){this.writeMesg("event",{timestamp:t.timestamp?t.timestamp:void 0,event:t.event,event_type:t.eventType,event_group:t.eventGroup})}buildActivity(t){this.writeMesg("activity",{timestamp:t.timestamp?t.timestamp:void 0,total_timer_time:t.totalTimerTime,num_sessions:t.numSessions,type:t.type,event:t.event,event_type:t.eventType,local_timestamp:t.localTimestamp?this.parseTimestamp(t.localTimestamp):void 0,event_group:t.eventGroup})}buildCourse(t){this.writeMesg("course",{name:t.name,sport:t.sport})}buildEventsFromLaps(t,_){t.forEach((I,A)=>{I.startTime&&_.push({timestamp:I.startTime,event:"timer",eventType:"start",eventGroup:A}),I.timestamp&&_.push({timestamp:I.timestamp,event:"timer",eventType:A===t.length-1?"stop_all":"stop",eventGroup:A})})}buildActivityFromSession(t,_){_.push({timestamp:t.timestamp,totalTimerTime:t.totalTimerTime,numSessions:1,type:t.sport||this.options.defaultActivity,event:"activity",eventType:"stop",eventGroup:0})}parseTimestamp(t){return typeof t=="number"?t:lI(t).valueOf()}convertToSemicircles(t){if(t!=null&&Number.isFinite(t))return Math.round(t*2**31/180)}validateRequiredFields(t){if(!t.sessionMesgs||t.sessionMesgs.length===0)throw new Error("FIT file must contain at least one Session")}writeMesg(t,_){let I=Object.fromEntries(Object.entries(_).filter(([L,E])=>E!==void 0));if(Object.keys(I).length===0)return;let A=this.localNum[t];A===void 0&&(A=this.localNum[t]=Object.keys(this.localNum).length);let T=new d_(A,t,I),n=this.mesgDefn[A];(!n||!T.isSameDefn(n))&&(this.messages.push(T.defnRecord),this.mesgDefn[A]=T.mesgDefn),this.messages.push(T.dataRecord)}get blob(){let t=[this.header,...this.messages,this.trailer];return new Blob(t,{type:"application/octet-stream"})}get dataLen(){return this.messages.reduce((t,_)=>t+_.byteLength,0)}get dataCrc(){return this.messages.reduce((t,_)=>dt(_,t),0)}get header(){let t=new DataView(new ArrayBuffer(Nt));return t.setUint8(0,Nt),t.setUint8(1,WI),t.setUint16(2,MI,!0),t.setUint32(4,this.dataLen,!0),t.setUint32(8,BI),t.setUint16(12,dt(t.buffer.slice(0,12)),!0),t.buffer}get trailer(){let t=new DataView(new ArrayBuffer(2));return t.setUint16(0,this.dataCrc,!0),t.buffer}async encoder(t){return this.encode(t)}};import{Encoder as sI}from"@garmin/fitsdk";var VI="development",pI=1,KI=1;function hI(R,t){if(!Number.isFinite(R))throw new Error(`${t} must be a finite number.`)}function F_(R,t){return hI(R,t),Math.abs(R)<=180?Math.round(R*2147483648/180):Math.round(R)}function wI(R){if(!R.name||R.name.trim().length===0)throw new Error("Course name is required.");if(!Array.isArray(R.records)||R.records.length===0)throw new Error("Course must contain at least one record point.");let t=R.records.map((I,A)=>{if(I==null)throw new Error(`Course record #${A+1} is missing.`);if(I.timestamp==null)throw new Error(`Course record #${A+1} is missing timestamp.`);return{...I,positionLat:F_(I.latitude,`records[${A}].latitude`),positionLong:F_(I.longitude,`records[${A}].longitude`)}}),_=(R.coursePoints??[]).map((I,A)=>{if(I==null)throw new Error(`Course point #${A+1} is missing.`);if(I.timestamp==null)throw new Error(`Course point #${A+1} is missing timestamp.`);return{...I,type:I.type??0,positionLat:F_(I.latitude,`coursePoints[${A}].latitude`),positionLong:F_(I.longitude,`coursePoints[${A}].longitude`)}});return{...R,sport:R.sport??2,subSport:R.subSport??0,records:t,coursePoints:_,manufacturer:R.manufacturer??VI,product:R.product??pI,serialNumber:R.serialNumber??KI,timeCreated:R.timeCreated??t[0].timestamp}}function XI(R){let t=wI(R),_=t.records[0],I=t.records[t.records.length-1],A=_.timestamp,T=I.timestamp,n=[{mesgNum:0,data:{type:6,manufacturer:t.manufacturer,product:t.product,serialNumber:t.serialNumber,timeCreated:t.timeCreated}},{mesgNum:31,data:{name:t.name,sport:t.sport,subSport:t.subSport}},{mesgNum:19,data:{startTime:A,timestamp:T,startPositionLat:_.positionLat,startPositionLong:_.positionLong,endPositionLat:I.positionLat,endPositionLong:I.positionLong,totalDistance:I.distance}},{mesgNum:21,data:{timestamp:A,event:0,eventType:0}}];return t.records.forEach(L=>{n.push({mesgNum:20,data:{timestamp:L.timestamp,positionLat:L.positionLat,positionLong:L.positionLong,distance:L.distance,altitude:L.altitude,speed:L.speed}})}),t.coursePoints.forEach((L,E)=>{n.push({mesgNum:32,data:{messageIndex:E,timestamp:L.timestamp,positionLat:L.positionLat,positionLong:L.positionLong,distance:L.distance,type:L.type,name:L.name,favorite:L.favorite}})}),n.push({mesgNum:21,data:{timestamp:T,event:0,eventType:4}}),n}function $t(R){let t=new sI;return XI(R).forEach(I=>{t.onMesg(I.mesgNum,I.data)}),t.close()}var q=class{constructor(){this.version="1.0.0";this.priority=100}supports(t){return this.supportedTags.includes(t)}async initialize(t){t.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(t){t.metadata.delete(`plugin:${this.name}:initialized`)}async validate(t){return!0}parseFloat(t){if(!(typeof t>"u"))return typeof t=="number"?t:typeof t=="string"&&parseFloat(t)||0}parseInt(t){return typeof t=="number"?Math.floor(t):typeof t=="string"&&parseInt(t,10)||0}parseString(t){return String(t||"")}parseBoolean(t){return typeof t=="boolean"?t:typeof t=="string"?t.toLowerCase()==="true":!1}parseDate(t){if(!t)return;let _=new Date(t);return isNaN(_.getTime())?void 0:_}hasRequiredAttributes(t,_){return _.every(I=>t.attributes?.[I])}extractAttributes(t,_,I){t.attributes&&Object.entries(t.attributes).forEach(([A,T])=>{let n=I[A];n&&(_[n]=String(T??""))})}processChildren(t,_,I){t.children?.forEach(A=>{let T=I[A.tag];T&&T(A,_)})}getChildValue(t,_){let I=t.children?.find(A=>A.tag===_);return I?.value?String(I.value):void 0}getChildByTag(t,_){return t.children?.find(I=>I.tag===_)}getChildrenByTag(t,_){return t.children?.filter(I=>I.tag===_)||[]}convertExtensions(t){let _={};return t.children?.forEach(I=>{_[I.tag]=this.convertExtensionContent(I)}),_}convertExtensionContent(t){if(t.children?.length){let _={};return t.children.forEach(I=>{_[I.tag]=this.convertExtensionContent(I)}),_}else return t.value}};var $=class extends q{parseCoordinate(t){let _=this.parseFloat(t);return _===0?void 0:_}parseGPXTime(t){if(!t)return;let _=new Date(t);return isNaN(_.getTime())?void 0:_}extractNumericAttributes(t,_,I){t.attributes&&Object.entries(t.attributes).forEach(([A,T])=>{let n=I[A];n&&n in _&&typeof T<"u"&&(_[n]=this.parseFloat(T))})}};var G_=class extends ${constructor(){super(...arguments);this.name="wpt-converter";this.supportedTags=["wpt","trkpt","rtept"];this.version="1.0.0"}convert(_,I){if(!this.hasRequiredAttributes(_,["lat","lon"])){I.warnings.push(`${this.name}: point without latitude or longitude was ignored`);return}let A={lat:this.parseFloat(_.attributes?.lat),lon:this.parseFloat(_.attributes?.lon)};return this.processChildren(_,A,{ele:(T,n)=>n.ele=this.parseFloat(T.value),time:(T,n)=>n.time=new Date(this.parseString(T.value)),speed:(T,n)=>n.speed=this.parseFloat(T.value),power:(T,n)=>n.power=this.parseFloat(T.value),cadence:(T,n)=>n.cadence=this.parseFloat(T.value),heartRate:(T,n)=>n.heartRate=this.parseFloat(T.value),course:(T,n)=>n.course=this.parseFloat(T.value),name:(T,n)=>n.name=this.parseString(T.value),cmt:(T,n)=>n.cmt=this.parseString(T.value),desc:(T,n)=>n.desc=this.parseString(T.value),src:(T,n)=>n.src=this.parseString(T.value),sym:(T,n)=>n.sym=this.parseString(T.value),type:(T,n)=>n.type=this.parseString(T.value),fix:(T,n)=>n.fix=this.parseString(T.value),sat:(T,n)=>n.sat=this.parseFloat(T.value),hdop:(T,n)=>n.hdop=this.parseFloat(T.value),vdop:(T,n)=>n.vdop=this.parseFloat(T.value),pdop:(T,n)=>n.pdop=this.parseFloat(T.value),ageofdgpsdata:(T,n)=>n.ageofdgpsdata=this.parseFloat(T.value),geoidheight:(T,n)=>n.geoidheight=this.parseFloat(T.value),magvar:(T,n)=>n.magvar=this.parseFloat(T.value),dgpsid:(T,n)=>n.dgpsid=this.parseFloat(T.value),extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("extensions");if(E){let f=E.convert(T,I);f&&(this.mapExtensionsToPoint(f,n),n.extensions=f)}},link:(T,n)=>{n.link||(n.link=[]);let E=I.metadata.get("decoder")?.getConverter("link")?.convert(T,I);E&&n.link&&n.link.push(E)}}),A}mapExtensionsToPoint(_,I){Object.entries(_).forEach(([A,T])=>{if(T!==void 0&&(typeof T=="string"||typeof T=="number")){let n=L=>(Array.isArray(L)?L:[L]).some(f=>{let G=A.toLowerCase(),U=f.toLowerCase();return G===U||G.endsWith(`:${U}`)});n("speed")?I.speed=this.parseFloat(T):n("hr")?I.heartRate=this.parseFloat(T):n(["cad","cadence"])?I.cadence=this.parseFloat(T):n(["PowerInWatts","power"])&&(I.power=this.parseFloat(T))}})}},g_=class extends ${constructor(){super(...arguments);this.name="rte-converter";this.supportedTags=["rte"]}convert(_,I){let A={rtept:[]};return this.processChildren(_,A,{name:(T,n)=>n.name=this.parseString(T.value),cmt:(T,n)=>n.cmt=this.parseString(T.value),desc:(T,n)=>n.desc=this.parseString(T.value),src:(T,n)=>n.src=this.parseString(T.value),number:(T,n)=>n.number=this.parseFloat(T.value),type:(T,n)=>n.type=this.parseString(T.value),rtept:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("wpt")?.convert(T,I);E&&n.rtept&&n.rtept.push(E)},extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("extensions");E&&(n.extensions=E.convert(T,I))},link:(T,n)=>{n.link||(n.link=[]);let E=I.metadata.get("decoder")?.getConverter("link")?.convert(T,I);E&&n.link&&n.link.push(E)}}),A}},l_=class extends ${constructor(){super(...arguments);this.name="trk-converter";this.supportedTags=["trk"]}convert(_,I){let A={trkseg:[]};return this.processChildren(_,A,{name:(T,n)=>n.name=this.parseString(T.value),cmt:(T,n)=>n.cmt=this.parseString(T.value),desc:(T,n)=>n.desc=this.parseString(T.value),src:(T,n)=>n.src=this.parseString(T.value),number:(T,n)=>n.number=this.parseFloat(T.value),type:(T,n)=>n.type=this.parseString(T.value),trkseg:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("trkseg")?.convert(T,I);E&&n.trkseg&&n.trkseg.push(E)},extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("extensions");E&&(n.extensions=E.convert(T,I))},link:(T,n)=>{n.link||(n.link=[]);let E=I.metadata.get("decoder")?.getConverter("link")?.convert(T,I);E&&n.link&&n.link.push(E)}}),A}},W_=class extends ${constructor(){super(...arguments);this.name="trkseg-converter";this.supportedTags=["trkseg"]}convert(_,I){let A={trkpt:[]};return this.processChildren(_,A,{trkpt:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("wpt")?.convert(T,I);E&&n.trkpt&&n.trkpt.push(E)},extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("extensions");E&&(n.extensions=E.convert(T,I))}}),A}},M_=class extends ${constructor(){super(...arguments);this.name="link-converter";this.supportedTags=["link"]}convert(_,I){let A={};return _.attributes?.href&&(A.href=_.attributes.href),this.processChildren(_,A,{text:(T,n)=>n.text=this.parseString(T.value),type:(T,n)=>n.type=this.parseString(T.value)}),A}},B_=class extends ${constructor(){super(...arguments);this.name="metadata-converter";this.supportedTags=["metadata"]}convert(_,I){let A={};return this.processChildren(_,A,{name:(T,n)=>n.name=this.parseString(T.value),desc:(T,n)=>n.desc=this.parseString(T.value),keywords:(T,n)=>n.keywords=this.parseString(T.value),time:(T,n)=>n.time=new Date(this.parseString(T.value)),author:(T,n)=>{let L=I.metadata.get("decoder");n.author=L?.getConverter("author")?.convert(T,I)},copyright:(T,n)=>{let L=I.metadata.get("decoder");n.copyright=L?.getConverter("copyright")?.convert(T,I)},bounds:(T,n)=>{let L=I.metadata.get("decoder");n.bounds=L?.getConverter("bounds")?.convert(T,I)},extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("extensions");E&&(n.extensions=E.convert(T,I))},link:(T,n)=>{n.link||(n.link=[]);let E=I.metadata.get("decoder")?.getConverter("link")?.convert(T,I);E&&n.link&&n.link.push(E)}}),A}},s_=class extends ${constructor(){super(...arguments);this.name="person-converter";this.supportedTags=["author"]}convert(_,I){let A={};return _.value&&!_.children?.length?(A.name=this.parseString(_.value),A):(this.processChildren(_,A,{name:(T,n)=>n.name=this.parseString(T.value),email:(T,n)=>{let L=I.metadata.get("decoder");n.email=L?.getConverter("email")?.convert(T,I)},link:(T,n)=>{let L=I.metadata.get("decoder");n.link=L?.getConverter("link")?.convert(T,I)}}),A)}},V_=class extends ${constructor(){super(...arguments);this.name="email-converter";this.supportedTags=["email"]}convert(_,I){return{id:_.attributes?.id,domain:_.attributes?.domain}}},p_=class extends ${constructor(){super(...arguments);this.name="copyright-converter";this.supportedTags=["copyright"]}convert(_,I){let A={};return _.attributes?.author&&(A.author=_.attributes.author),this.processChildren(_,A,{year:(T,n)=>n.year=this.parseString(T.value),license:(T,n)=>n.license=this.parseString(T.value)}),A}},K_=class extends ${constructor(){super(...arguments);this.name="bounds-converter";this.supportedTags=["bounds"]}convert(_,I){let A={};return this.extractAttributes(_,A,{minlat:"minlat",minlon:"minlon",maxlat:"maxlat",maxlon:"maxlon"}),A}},h_=class extends ${constructor(){super(...arguments);this.name="extensions-converter";this.supportedTags=["extensions"]}convert(_,I){let A={};return _.children?.forEach(T=>{this.flattenExtensionElement(T,A)}),A}flattenExtensionElement(_,I){if(!_.children?.length&&_.value!==void 0){I[_.tag]=this.parseExtensionValue(_.value);return}_.children?.length&&_.children.forEach(A=>{this.flattenExtensionElement(A,I)})}parseExtensionValue(_){if(_===void 0)return;let I=String(_),A=parseFloat(I);return!isNaN(A)&&isFinite(A)?A:I}};import{Parser as vI}from"htmlparser2";var w_=class{constructor(){this.stage="tokenize"}async process(t){let _=Date.now();if(!t.xmlContent)throw new Error("XML content cannot be empty");let I=[],A=new vI({onopentag(T,n){I.push({type:"open",tag:T,attributes:n})},ontext(T){let n=T.replace(/\n/g,"").trim();n&&I.push({type:"text",tag:"text",value:n})},onclosetag(T){I.push({type:"close",tag:T})}},{xmlMode:!0});return A.write(t.xmlContent),A.end(),t.tokens=I,t.performance.tokenizeTime=Date.now()-_,t}},X_=class{constructor(){this.stage="ast_generate"}async process(t){let _=Date.now();if(!t.tokens)throw new Error("Tokens cannot be empty");let I=[],A,T=null;for(let n of t.tokens)if(n.type==="open"){let L={tag:n.tag,attributes:n.attributes||{},children:[]};A?T&&T.children?.push(L):A=L,I.push(L),T=L}else n.type==="text"&&T?T.value=n.value:n.type==="close"&&(I.pop(),T=I[I.length-1]||null);return t.ast=A,t.performance.astTime=Date.now()-_,t}},v_=class{constructor(t){this.getConverter=t;this.stage="convert"}async process(t){let _=Date.now();if(!t.ast)throw new Error("AST cannot be empty");if(t.ast.tag!=="gpx")throw new Error(`Not a valid GPX document: expected <gpx>, received <${t.ast.tag}>`);let I={};return t.ast.attributes&&Object.entries(t.ast.attributes).forEach(([A,T])=>{A.startsWith("xmlns:")?I[A]=T.replace(/&#39;/g,"'"):A==="xsi:schemaLocation"?I[A]=T.replace(/&#39;/g,"'"):I[A]=T}),t.ast.children?.forEach(A=>{let T=this.getConverter(A.tag);if(!T){t.warnings.push(`Unsupported GPX element "${A.tag}" was ignored`);return}try{let n=T.convert(A,t);n&&this.assignResult(I,A.tag,n)}catch(n){throw t.errors.push(n),new Error(`GPX converter "${T.name}" failed for ${A.tag}: ${n.message}`)}}),t.result=I,t.performance.convertTime=Date.now()-_,t}assignResult(t,_,I){switch(_){case"metadata":t.metadata=I;break;case"wpt":t.wpt||(t.wpt=[]),t.wpt.push(I);break;case"rte":t.rte||(t.rte=[]),t.rte.push(I);break;case"trk":t.trk||(t.trk=[]),t.trk.push(I);break;case"extensions":t.extensions=I;break}}},P_=class{constructor(){this.stage="complete"}async process(t){t.performance.endTime=Date.now();let _=t.performance.endTime-t.performance.startTime;return t.metadata.set("performance",{totalTime:_,tokenizeTime:t.performance.tokenizeTime,astTime:t.performance.astTime,convertTime:t.performance.convertTime}),t}};var Y_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultConvertersRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new w_,new X_,new v_(t=>this.getConverter(t)),new P_]}async registerDefaultConverters(){if(this.defaultConvertersRegistered)return;let t=[new G_,new g_,new l_,new W_,new M_,new B_,new s_,new V_,new p_,new K_,new h_];for(let _ of t)_.supportedTags?.forEach(I=>{this.addConverterForTag(I,_)}),this.registeredPlugins.add(_.name);this.defaultConvertersRegistered=!0}addConverterForTag(t,_){this.converterPlugins.has(t)||this.converterPlugins.set(t,[]);let I=this.converterPlugins.get(t);I.push(_),I.sort((A,T)=>(A.priority||100)-(T.priority||100))}async registerConverter(t){if(this.registeredPlugins.has(t.name))throw new Error(`Converter plugin ${t.name} already exists`);t.supportedTags?.forEach(_=>{this.addConverterForTag(_,t)}),this.registeredPlugins.add(t.name)}async registerMiddleware(t){let _=this.middlewarePlugins.findIndex(I=>I.name===t.name);_!==-1?this.middlewarePlugins[_]=t:this.middlewarePlugins.push(t)}getConverter(t){let _=this.converterPlugins.get(t);return _&&_.length>0?_[0]:void 0}getAllConverters(t){return this.converterPlugins.get(t)||[]}unregisterConverter(t){let _;for(let[I,A]of this.converterPlugins){let T=A.findIndex(n=>n.name===t);T!==-1&&(_=A[T],A.splice(T,1),A.length===0&&this.converterPlugins.delete(I))}_&&this.registeredPlugins.delete(t)}unregisterMiddleware(t){let _=this.middlewarePlugins.findIndex(I=>I.name===t);_!==-1&&this.middlewarePlugins.splice(_,1)}listConverters(){return Array.from(this.converterPlugins.keys())}listConverterPlugins(){return Array.from(this.registeredPlugins)}listMiddlewares(){return this.middlewarePlugins.map(t=>t.name)}listProcessors(){return this.processors.map(t=>t.constructor.name)}getConverterDetails(t){let _={};if(t){let I=this.converterPlugins.get(t);I&&(_[t]=I.map(A=>({name:A.name,priority:A.priority||100})))}else for(let[I,A]of this.converterPlugins)_[I]=A.map(T=>({name:T.name,priority:T.priority||100}));return _}getMiddlewareDetails(){return this.middlewarePlugins.map(t=>{let _=[];return t.onTokenize&&_.push("onTokenize"),t.onAstGenerate&&_.push("onAstGenerate"),t.onConvert&&_.push("onConvert"),t.onComplete&&_.push("onComplete"),t.onError&&_.push("onError"),{name:t.name,hooks:_}})}async initialize(){if(this.initialized)return;await this.registerDefaultConverters();let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.initialize?.(t);this.initialized=!0}async destroy(){if(!this.initialized)return;let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.destroy?.(t);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(t,_,I){let A=_;for(let T of this.middlewarePlugins){let n=T[t];if(n)try{A=await n.call(T,A,I)||A}catch(L){I.errors.push(L),await T.onError?.(L,I)}}return A}async parserByBuffer(t){await this.initialize();let _=this.createContext();_.rawData=t,_.xmlContent=t.toString("utf-8"),_.metadata.set("decoder",this);for(let I of this.processors)try{switch(_=await I.process(_),I.stage){case"tokenize":_.tokens&&(_.tokens=await this.executeMiddlewareHook("onTokenize",_.tokens,_));break;case"ast_generate":_.ast&&(_.ast=await this.executeMiddlewareHook("onAstGenerate",_.ast,_));break;case"convert":_.result&&(_.result=await this.executeMiddlewareHook("onConvert",_.result,_));break;case"complete":_.result&&(_.result=await this.executeMiddlewareHook("onComplete",_.result,_));break}}catch(A){_.errors.push(A);for(let T of this.middlewarePlugins)await T.onError?.(A,_);throw new Error(`GPX pipeline stage "${I.stage}" failed: ${A.message}`)}return _.result}convertExtensions(t){let _={},{attributes:I,tag:A,value:T}=t;if(I&&Object.entries(I).forEach(([n,L])=>{_[n]=L}),t?.children?.length)t.children?.forEach(n=>{_[n.tag]=this.convertExtensions(n)});else if(T!==void 0)return T;return _}};import Qt from"dayjs";import PI from"dayjs/plugin/utc.js";var Ut={temperature:"atemp",wtemp:"wtemp",heartRate:"hr",cadence:"cad"};var Ft={temperature:"Temperature",Depth:"Depth"};Qt.extend(PI);var b_=class{constructor(t={}){this.formatElevation=t=>{let _=parseFloat(t);return isNaN(_)?t:this.roundTo(_,2).toString()};this.compact=t.compact??!0}async encode(t){let _=this.buildGPXXML(t);return Buffer.from(_,"utf-8")}encodeToString(t){return this.buildGPXXML(t)}buildGPXXML(t){let _=this.buildXMLHeader(t),I=this.buildGPXContent(t),T=`${_}${I}
2
- </gpx>`;return this.compact?this.compressXML(T):T}compressXML(t){return t.replace(/>\s+</g,"><").replace(/^\s+|\s+$/gm,"").replace(/\s+/g," ").trim()}buildXMLHeader(t){let _=this.escapeXMLAttribute(t.creator||"TrackSwap"),I=this.escapeXMLAttribute(t.version||"1.1");return['<?xml version="1.0" encoding="UTF-8"?>',`<gpx creator="${_}" version="${I}"`,' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',' xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd'," http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd"," http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd"," http://www.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd",' http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd"',' xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"',' xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"',' xmlns:gpxpx="http://www.garmin.com/xmlschemas/PowerExtension/v1"',' xmlns:gpx_style="http://www.topografix.com/GPX/gpx_style/0/2"',' xmlns="http://www.topografix.com/GPX/1/1">'].join(`
3
- `)}buildGPXContent(t){let{metadata:_,wpt:I=[],rte:A=[],trk:T=[],extensions:n}=t,L=[];return _&&L.push(this.buildMetadata(_)),I.forEach(E=>{L.push(this.buildWaypoint(E,"wpt"))}),A.forEach(E=>{L.push(this.buildRoute(E))}),T.forEach(E=>{L.push(this.buildTrack(E))}),n&&L.push(this.buildExtensions(n)),L.join(`
4
- `)}buildMetadata(t){let _=["<metadata>"];return this.addOptionalElement(_,"name",t.name),this.addOptionalElement(_,"desc",t.desc),t.author&&_.push(this.buildAuthor(t.author)),t.copyright&&_.push(this.buildCopyright(t.copyright)),t.link&&this.addLinks(_,t.link),t.time&&_.push(this.buildTimeElement(t.time)),this.addOptionalElement(_,"keywords",t.keywords),t.bounds&&_.push(this.buildBounds(t.bounds)),t.extensions&&_.push(this.buildExtensions(t.extensions)),_.push("</metadata>"),_.join(`
5
- `)}buildAuthor(t){let _=["<author>"];return this.addOptionalElement(_,"name",t.name),t.email&&_.push(`<email id="${this.escapeXML(t.email.id||"")}" domain="${this.escapeXML(t.email.domain||"")}"/>`),t.link&&_.push(this.buildLink(t.link)),_.push("</author>"),_.join(`
6
- `)}buildCopyright(t){let _=[`<copyright author="${this.escapeXML(t.author||"")}">`];return this.addOptionalElement(_,"year",t.year),this.addOptionalElement(_,"license",t.license),_.push("</copyright>"),_.join(`
7
- `)}buildBounds(t){let _=this.escapeXMLAttribute((t.minlat||0).toString()),I=this.escapeXMLAttribute((t.minlon||0).toString()),A=this.escapeXMLAttribute((t.maxlat||0).toString()),T=this.escapeXMLAttribute((t.maxlon||0).toString());return`<bounds minlat="${_}" minlon="${I}" maxlat="${A}" maxlon="${T}"/>`}buildWaypoint(t,_){let I=t.lat,A=t.lon,T=typeof I=="number"&&Number.isFinite(I)&&I>=-90&&I<=90,n=typeof A=="number"&&Number.isFinite(A)&&A>=-180&&A<=180;if(!T||!n)return"";let L=[`<${_} lat="${this.escapeXMLAttribute(this.formatCoordinate(I))}" lon="${this.escapeXMLAttribute(this.formatCoordinate(A))}">`];this.addOptionalElement(L,"ele",t.ele?.toString(),this.formatElevation),t?.time&&L.push(this.buildTimeElement(t.time)),this.addStandardWaypointElements(L,t);let E=this.processPointExtensions(t,t.extensions??{});return Object.keys(E).length>0&&L.push(this.buildExtensions(E)),L.push(`</${_}>`),L.join(`
8
- `)}addStandardWaypointElements(t,_){this.addOptionalElement(t,"magvar",_.magvar?.toString()),this.addOptionalElement(t,"geoidheight",_.geoidheight?.toString()),this.addOptionalElement(t,"name",_.name),this.addOptionalElement(t,"cmt",_.cmt),this.addOptionalElement(t,"desc",_.desc),this.addOptionalElement(t,"src",_.src),_.link&&this.addLinks(t,_.link),this.addOptionalElement(t,"sym",_.sym),this.addOptionalElement(t,"type",_.type),this.addOptionalElement(t,"fix",_.fix),this.addOptionalElement(t,"sat",_.sat?.toString()),this.addOptionalElement(t,"hdop",_.hdop?.toString()),this.addOptionalElement(t,"vdop",_.vdop?.toString()),this.addOptionalElement(t,"pdop",_.pdop?.toString()),this.addOptionalElement(t,"ageofdgpsdata",_.ageofdgpsdata?.toString()),this.addOptionalElement(t,"dgpsid",_.dgpsid?.toString())}buildRoute(t){let _=["<rte>"];return this.addRouteTrackCommonElements(_,t),t.extensions&&_.push(this.buildExtensions(t.extensions)),t.rtept&&t.rtept?.forEach(I=>{_.push(this.buildWaypoint(I,"rtept"))}),_.push("</rte>"),_.join(`
9
- `)}buildTrack(t){let _=["<trk>"];return this.addRouteTrackCommonElements(_,t),t.extensions&&_.push(this.buildExtensions(t.extensions)),t.trkseg&&t.trkseg.forEach(I=>{_.push(this.buildTrackSegment(I))}),_.push("</trk>"),_.join(`
10
- `)}buildTrackSegment(t){let _=["<trkseg>"];return t.trkpt&&t.trkpt.forEach(I=>{_.push(this.buildWaypoint(I,"trkpt"))}),t.extensions&&_.push(this.buildExtensions(t.extensions)),_.push("</trkseg>"),_.join(`
11
- `)}addRouteTrackCommonElements(t,_){this.addOptionalElement(t,"name",_.name),this.addOptionalElement(t,"cmt",_.cmt),this.addOptionalElement(t,"desc",_.desc),this.addOptionalElement(t,"src",_.src),_.link&&this.addLinks(t,_.link),this.addOptionalElement(t,"number",_.number?.toString()),this.addOptionalElement(t,"type",_.type)}processPointExtensions(t,_){let I={};return Object.entries({"gpxtpx:TrackPointExtension":{"gpxtpx:hr":"heartRate","gpxtpx:cad":"cadence","gpxtpx:speed":"speed","gpxtpx:atemp":"temperature","gpxtpx:wtemp":"wtemp","gpxtpx:temp":"temperature"},"gpxpx:PowerExtension":{"gpxpx:PowerInWatts":"power"},"gpxx:GpxExtensions":{"gpxx:Temperature":"temperature","gpxx:Depth":"depth"}}).forEach(([T,n])=>{let L={},E=!1;Object.entries(n).forEach(([f,G])=>{let U;if(t[G]!==void 0)U=t[G];else if(_)if(_[f]!==void 0)U=_[f];else{let K=f.split(":").pop();Object.entries(_).forEach(([s,B])=>{s.endsWith(`:${K}`)&&B!==void 0&&(U=B)})}U!==void 0&&(L[f]=U,E=!0)}),E&&(I[T]=L)}),I}buildTrackPointExtension(t,_){let I=this.deepClone(_["gpxtpx:TrackPointExtension"]||{}),A=Object.keys(Ut);return Object.keys(t).filter(T=>A.includes(T)).forEach(T=>{let n=Ut[T];n&&t[T]!==void 0&&(I[`gpxtpx:${n}`]=t[T])}),I}buildPowerExtension(t,_){return this.deepClone(_["gpxpx:PowerExtension"]||{})}buildGpxExtensions(t,_){let I=this.deepClone(_["gpxx:GpxExtensions"]||{}),A=Object.keys(Ft);return Object.keys(t).filter(T=>A.includes(T)).forEach(T=>{let n=Ft[T];n&&t[T]!==void 0&&(I[`gpxx:${n}`]=t[T])}),I}buildExtensions(t){let _=this.buildExtensionContent(t);return _?`<extensions>${_}</extensions>`:""}buildExtensionContent(t){return Object.entries(t).filter(([_])=>!_.startsWith("xmlns")).map(([_,I])=>{if(I&&typeof I=="object"){let A=this.buildExtensionContent(I);return`<${_}>${A}</${_}>`}else if(I!=null)return`<${_}>${this.escapeXML(String(I))}</${_}>`;return""}).filter(_=>_).join("")}buildLink(t){let _=[`<link href="${this.escapeXMLAttribute(t.href||"")}">`];return this.addOptionalElement(_,"text",t.text),this.addOptionalElement(_,"type",t.type),_.push("</link>"),_.join("")}addLinks(t,_){(Array.isArray(_)?_:[_]).forEach(A=>{t.push(this.buildLink(A))})}buildTimeElement(t){return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/.test(t)?`<time>${t}</time>`:`<time>${Qt(t).utc().format("YYYY-MM-DDTHH:mm:ss[Z]")}</time>`}addOptionalElement(t,_,I,A){if(I!=null&&I!==""){let T=A?A(I):this.escapeXML(I);t.push(`<${_}>${T}</${_}>`)}}isValidCoordinate(t,_){return t!=null&&_!==void 0&&_!==null&&!isNaN(t)&&!isNaN(_)}formatCoordinate(t){return this.roundTo(t,6).toString()}roundTo(t,_){let I=Math.pow(10,_);return Math.round(t*I)/I}escapeXML(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeXMLAttribute(t){return typeof t!="string"?String(t||""):t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;").replace(/\n/g,"&#10;").replace(/\t/g,"&#9;")}deepClone(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t))return t.map(I=>this.deepClone(I));let _={};for(let I in t)Object.prototype.hasOwnProperty.call(t,I)&&(_[I]=this.deepClone(t[I]));return _}encoder(t){return this.encode(t)}};var z=class extends q{parseHeartRate(t){let _=this.parseFloat(t);if(!(typeof _>"u"))return _>0&&_<300?_:void 0}parseTCXTime(t){if(!t)return;let _=new Date(t);return isNaN(_.getTime())?void 0:_}parseDistance(t){let _=this.parseFloat(t);if(!(typeof _>"u"))return _>0?_:void 0}parseSpeed(t){let _=this.parseFloat(t);if(!(typeof _>"u"))return _>=0?_:void 0}parseAltitude(t){return this.parseFloat(t)}parseCoordinate(t){let _=this.parseFloat(t);return _!==0?_:void 0}};var N_=class extends z{constructor(){super(...arguments);this.name="PositionConverter";this.supportedTags=["Position"]}convert(_,I){let A={};return this.processChildren(_,A,{LatitudeDegrees:(T,n)=>n.LatitudeDegrees=this.parseString(T.value),LongitudeDegrees:(T,n)=>n.LongitudeDegrees=this.parseString(T.value)}),A}},$_=class extends z{constructor(){super(...arguments);this.name="TrackpointConverter";this.supportedTags=["Trackpoint"]}convert(_,I){let A={};return this.processChildren(_,A,{Time:(T,n)=>n.Time=this.parseString(T.value),Position:(T,n)=>{let L=I.metadata.get("decoder");n.Position=L?.getConverter("Position")?.convert(T,I)},AltitudeMeters:(T,n)=>n.AltitudeMeters=this.parseFloat(T.value),DistanceMeters:(T,n)=>n.DistanceMeters=this.parseFloat(T.value),HeartRateBpm:(T,n)=>{if(T.value)n.HeartRateBpm=this.parseFloat(T.value);else{let L=this.getChildByTag(T,"Value");L?.value&&(n.HeartRateBpm=this.parseFloat(L.value))}},Cadence:(T,n)=>{let L={Low:0,High:0};this.processChildren(T,L,{Low:(E,f)=>f.Low=this.parseFloat(E.value)||0,High:(E,f)=>f.High=this.parseFloat(E.value)||0}),n.Cadence=L},SensorState:(T,n)=>n.SensorState=T.value,Extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Extensions");E&&(n.Extensions=E.convert(T,I))}}),A}},k_=class extends z{constructor(){super(...arguments);this.name="TrackConverter";this.supportedTags=["Track"]}convert(_,I){let A={Trackpoint:[]};return this.processChildren(_,A,{Trackpoint:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Trackpoint")?.convert(T,I);E&&n.Trackpoint&&n.Trackpoint.push(E)}}),A}},Q_=class extends z{constructor(){super(...arguments);this.name="ActivityLapConverter";this.supportedTags=["Lap"]}convert(_,I){let A={};return this.extractAttributes(_,A,{StartTime:"StartTime"}),this.processChildren(_,A,{TotalTimeSeconds:(T,n)=>n.TotalTimeSeconds=this.parseFloat(T.value),DistanceMeters:(T,n)=>n.DistanceMeters=this.parseFloat(T.value),MaximumSpeed:(T,n)=>n.MaximumSpeed=this.parseFloat(T.value),Calories:(T,n)=>n.Calories=this.parseFloat(T.value),AverageHeartRateBpm:(T,n)=>n.AverageHeartRateBpm=this.parseFloat(T.value),MaximumHeartRateBpm:(T,n)=>n.MaximumHeartRateBpm=this.parseFloat(T.value),Intensity:(T,n)=>n.Intensity=T.value,TriggerMethod:(T,n)=>n.TriggerMethod=T.value,Track:(T,n)=>{n.Track||(n.Track=[]);let E=I.metadata.get("decoder")?.getConverter("Track")?.convert(T,I);E&&n.Track.push(E)},Notes:(T,n)=>n.Notes=this.parseString(T.value),Extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Extensions");E&&(n.Extensions=E.convert(T,I))}}),A}},J_=class extends z{constructor(){super(...arguments);this.name="ActivityConverter";this.supportedTags=["Activity"]}convert(_,I){let A={Id:"",Lap:[]};return this.extractAttributes(_,A,{Sport:"Sport"}),this.processChildren(_,A,{Id:(T,n)=>n.Id=this.parseString(T.value),Lap:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Lap")?.convert(T,I);E&&n.Lap.push(E)},Notes:(T,n)=>n.Notes=this.parseString(T.value),Training:(T,n)=>n.Training=this.convertTraining(T),Creator:(T,n)=>n.Creator=this.convertCreator(T),Extensions:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Extensions");E&&(n.Extensions=E.convert(T,I))}}),A}convertTraining(_){let I={};return _.attributes&&Object.entries(_.attributes).forEach(([A,T])=>{I[A]=T}),_.children?.forEach(A=>{I[A.tag]=this.convertExtensionContent(A)}),I}convertCreator(_){let I={};return _.children?.forEach(A=>{I[A.tag]=this.convertExtensionContent(A)}),I}},z_=class extends z{constructor(){super(...arguments);this.name="ActivityListConverter";this.supportedTags=["Activities"]}convert(_,I){let A={Activity:[],MultiActivitySession:[]};return this.processChildren(_,A,{Activity:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("Activity")?.convert(T,I);E&&n.Activity&&n.Activity.push(E)},MultiActivitySession:(T,n)=>{let E=I.metadata.get("decoder")?.getConverter("MultiActivitySession")?.convert(T,I);E&&n.MultiActivitySession&&n.MultiActivitySession.push(E)}}),A}},j_=class extends z{constructor(){super(...arguments);this.name="MultiActivitySessionConverter";this.supportedTags=["MultiActivitySession"]}convert(_,I){let A={};return this.processChildren(_,A,{Id:(T,n)=>n.Id=this.parseString(T.value),FirstActivity:(T,n)=>{let L=I.metadata.get("decoder");n.FirstActivity=L?.getConverter("FirstActivity")?.convert(T,I)},NextActivity:(T,n)=>{n.NextActivity||(n.NextActivity=[]);let E=I.metadata.get("decoder")?.getConverter("NextActivity")?.convert(T,I);E&&n.NextActivity.push(E)},Notes:(T,n)=>n.Notes=this.parseString(T.value)}),A}},y_=class extends z{constructor(){super(...arguments);this.name="AbstractSourceConverter";this.supportedTags=["Author","Creator"]}convert(_,I){let A={};return this.processChildren(_,A,{Name:(T,n)=>n.Name=this.parseString(T.value)}),A}},Z_=class extends z{constructor(){super(...arguments);this.name="extensions-converter";this.supportedTags=["Extensions"]}convert(_,I){let A={};return this.flattenExtensionElement(_,A),A}flattenExtensionElement(_,I){if(!_.children?.length&&_.value!==void 0){I[_.tag]=this.parseExtensionValue(_.value);return}_.children?.length&&_.children.forEach(A=>{this.flattenExtensionElement(A,I)})}parseExtensionValue(_){if(_===void 0)return;let I=String(_),A=parseFloat(I);return!isNaN(A)&&isFinite(A)?A:I}};import{Parser as Jt}from"htmlparser2";var q_=class{static tokenizeXML(t){let _=[],I=new Jt({onopentag(A,T){_.push({type:"open",tag:A,attributes:T})},ontext(A){let T=A.replace(/\n/g,"").trim();T&&_.push({type:"text",tag:"text",value:T})},onclosetag(A){_.push({type:"close",tag:A})}},{xmlMode:!0});return I.write(t),I.end(),_}static compressXML(t){return t.replace(/>\s+</g,"><").replace(/\s+/g," ").trim()}static formatXML(t,_=2){let I=" ".repeat(_),A="",T=0,n=!1;for(let L=0;L<t.length;L++){let E=t[L],f=t[L+1];E==="<"?(f==="/"?(T--,n||(A+=`
12
- `+I.repeat(T))):f!=="?"&&f!=="!"&&(n||(A+=`
13
- `+I.repeat(T)),T++),n=!0):E===">"&&(n=!1,f==="<"&&t[L+2]==="/"&&T--),A+=E}return A.trim()}static validateXML(t){try{let _=new Jt({},{xmlMode:!0});return _.write(t),_.end(),{isValid:!0}}catch(_){return{isValid:!1,error:_.message}}}static extractXMLDeclaration(t){let _=t.match(/<\?xml\s+([^>]+)\?>/);if(!_)return{};let I=_[1],A={},T=I.match(/version=["']([^"']+)["']/);T&&(A.version=T[1]);let n=I.match(/encoding=["']([^"']+)["']/);n&&(A.encoding=n[1]);let L=I.match(/standalone=["']([^"']+)["']/);return L&&(A.standalone=L[1]),A}static escapeXML(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}static unescapeXML(t){return t.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}};var u_=class{constructor(){this.stage="tokenize";this.name="tokenize-processor"}async process(t){if(!t.xmlContent)throw new Error("TCX data cannot be empty");let _=q_.tokenizeXML(t.xmlContent);if(_.length===0)throw new Error("Not a valid TCX file");return t.tokens=_,t.stats.processedTokens=_.length,t}},i_=class{constructor(){this.stage="ast-generate";this.name="ast-generate-processor"}async process(t){let _=Date.now();if(!t.tokens)throw new Error("Tokens cannot be empty");let I=[],A,T=null;for(let n of t.tokens)if(n.type==="open"){let L={tag:n.tag,attributes:n.attributes||{},children:[]};A?T&&T.children?.push(L):A=L,I.push(L),T=L}else n.type==="text"&&T?T.value=n.value:n.type==="close"&&(I.pop(),T=I[I.length-1]||null);return t.ast=A,t.performance.astTime=Date.now()-_,t}},r_=class{constructor(t){this.getConverter=t;this.stage="convert";this.name="convert-processor"}async process(t){if(!t.ast)throw new Error("AST is empty, cannot convert");let _=this.findTCXRoot(t.ast);if(!_)throw new Error("Not a valid TCX file: TrainingCenterDatabase element not found");let I=this.convertAST(_,t);return t.result=I,t.stats.convertedElements=this.countElements(t.ast),t}findTCXRoot(t){if(t.tag==="TrainingCenterDatabase")return t;if(t.children)for(let _ of t.children){let I=this.findTCXRoot(_);if(I)return I}}convertAST(t,_){let I=this.getConverter(t.tag);return I?I.convert(t,_):this.genericConvert(t,_)}genericConvert(t,_){let I={};if(t.attributes&&Object.entries(t.attributes).forEach(([A,T])=>{I[A]=T}),t.value!==void 0)if(t.children&&t.children.length>0)I._value=t.value;else return t.value;return t.children&&t.children.forEach(A=>{let T=this.convertAST(A,_);I[A.tag]?(Array.isArray(I[A.tag])||(I[A.tag]=[I[A.tag]]),I[A.tag].push(T)):I[A.tag]=T}),I}countElements(t){let _=1;if(t.children)for(let I of t.children)_+=this.countElements(I);return _}},m_=class{constructor(){this.stage="complete";this.name="complete-processor"}async process(t){if(!t.result)throw new Error("No conversion result found");let _=Date.now(),I=_-t.performance.startTime;return t.performance.endTime=_,t.performance.processingTime=I,t.metadata.set("performance",{processingTime:I,processedTokens:t.stats.processedTokens,convertedElements:t.stats.convertedElements}),t}};var c_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultConvertersRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new u_,new i_,new r_(t=>this.getConverter(t)),new m_]}async registerDefaultConverters(){if(this.defaultConvertersRegistered)return;let t=[new N_,new $_,new k_,new Q_,new J_,new z_,new j_,new y_,new Z_];for(let _ of t)_.supportedTags?.forEach(I=>{this.addConverterForTag(I,_)}),this.registeredPlugins.add(_.name);this.defaultConvertersRegistered=!0}addConverterForTag(t,_){this.converterPlugins.has(t)||this.converterPlugins.set(t,[]);let I=this.converterPlugins.get(t);I.push(_),I.sort((A,T)=>(A.priority||100)-(T.priority||100))}async registerConverter(t){if(this.registeredPlugins.has(t.name))throw new Error(`Converter plugin ${t.name} already exists`);t.supportedTags?.forEach(_=>{this.addConverterForTag(_,t)}),this.registeredPlugins.add(t.name)}async registerMiddleware(t){let _=this.middlewarePlugins.findIndex(I=>I.name===t.name);_!==-1?this.middlewarePlugins[_]=t:this.middlewarePlugins.push(t)}getConverter(t){let _=this.converterPlugins.get(t);return _&&_.length>0?_[0]:void 0}getAllConverters(t){return this.converterPlugins.get(t)||[]}unregisterConverter(t){let _;for(let[I,A]of this.converterPlugins){let T=A.findIndex(n=>n.name===t);T!==-1&&(_=A[T],A.splice(T,1),A.length===0&&this.converterPlugins.delete(I))}_&&this.registeredPlugins.delete(t)}unregisterMiddleware(t){let _=this.middlewarePlugins.findIndex(I=>I.name===t);_!==-1&&this.middlewarePlugins.splice(_,1)}async initialize(){if(this.initialized)return;await this.registerDefaultConverters();let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.initialize?.(t);this.initialized=!0}async destroy(){if(!this.initialized)return;let t=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(I=>[I.name,I])).values()];for(let I of _)await I.destroy?.(t);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(t,_,I){let A=_;for(let T of this.middlewarePlugins){let n=T[t];if(n)try{A=await n.call(T,A,I)||A}catch(L){I.errors.push(L),await T.onError?.(L,I)}}return A}async parseByBuffer(t){await this.initialize();let _=this.createContext();_.rawData=t,_.xmlContent=t.toString("utf-8"),_.metadata.set("decoder",this);for(let I of this.processors)try{switch(_=await I.process(_),I.stage){case"tokenize":_.tokens&&(_.tokens=await this.executeMiddlewareHook("onTokenize",_.tokens,_));break;case"ast-generate":_.ast&&(_.ast=await this.executeMiddlewareHook("onAstGenerate",_.ast,_));break;case"convert":_.result&&(_.result=await this.executeMiddlewareHook("onConvert",_.result,_));break;case"complete":_.result&&(_.result=await this.executeMiddlewareHook("onComplete",_.result,_));break}}catch(A){_.errors.push(A);for(let T of this.middlewarePlugins)await T.onError?.(A,_);throw new Error(`TCX pipeline stage "${I.stage}" failed: ${A.message}`)}return _.result}convertExtensions(t){let _={},{attributes:I,tag:A,value:T}=t;if(I&&Object.entries(I).forEach(([n,L])=>{_[n]=L}),t?.children?.length)t.children?.forEach(n=>{_[n.tag]=this.convertExtensions(n)});else if(T!==void 0)return T;return _}async parserByBuffer(t){return this.parseByBuffer(t)}async parseByString(t){let _=Buffer.from(t,"utf-8");return this.parseByBuffer(_)}};import zt from"dayjs";import YI from"dayjs/plugin/utc.js";zt.extend(YI);var a_=class{constructor(t={}){this.compact=t.compact??!0}async encode(t){let _=this.buildTCXXML(t);return Buffer.from(_,"utf-8")}encodeToString(t){return this.buildTCXXML(t)}buildTCXXML(t){let _=this.buildXMLHeader(t),I=this.buildTCXContent(t),T=`${_}${I}
14
- </TrainingCenterDatabase>`;return this.compact?this.compressXML(T):T}compressXML(t){return t.replace(/>\s+</g,"><").replace(/^\s+|\s+$/gm,"").replace(/\s+/g," ").trim()}buildXMLHeader(t){let _=t.version||"1.0",I=t.creator||"trackswap",A=t.xmlns||"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2",T=t["xmlns:xsi"]||"http://www.w3.org/2001/XMLSchema-instance",n=t["xsi:schemaLocation"]||"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd";return['<?xml version="1.0" encoding="UTF-8"?>',`<TrainingCenterDatabase version="${this.escapeXMLAttribute(_)}"`,` creator="${this.escapeXMLAttribute(I)}"`,` xmlns="${this.escapeXMLAttribute(A)}"`,` xmlns:xsi="${this.escapeXMLAttribute(T)}"`,` xsi:schemaLocation="${this.escapeXMLAttribute(n)}">`].join(`
15
- `)}buildTCXContent(t){let _=[];return t.Folders&&_.push(this.buildFolders(t.Folders)),t.Activities&&_.push(this.buildActivities(t.Activities)),t.Workouts&&_.push(this.buildWorkouts(t.Workouts)),t.Courses&&_.push(this.buildCourses(t.Courses)),t.Author&&_.push(this.buildAuthor(t.Author)),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.join(`
16
- `)}buildFolders(t){let _=["<Folders>"];return t.History&&_.push(this.buildHistory(t.History)),t.Workouts&&_.push(this.buildWorkouts(t.Workouts)),t.Courses,_.push("</Folders>"),_.join(`
17
- `)}buildHistory(t){let _=["<History>"];return t.Running&&_.push(`<Running>${this.buildHistoryFolder(t.Running)}</Running>`),t.Biking&&_.push(`<Biking>${this.buildHistoryFolder(t.Biking)}</Biking>`),t.Other&&_.push(`<Other>${this.buildHistoryFolder(t.Other)}</Other>`),t.MultiActivity&&_.push(`<MultiActivity>${this.buildHistoryFolder(t.MultiActivity)}</MultiActivity>`),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.push("</History>"),_.join(`
18
- `)}buildHistoryFolder(t){return""}buildActivities(t){let _=["<Activities>"];return t.Activity&&t.Activity.forEach(I=>{_.push(this.buildActivity(I))}),t.MultiActivitySession&&t.MultiActivitySession.forEach(I=>{_.push(this.buildMultiActivitySession(I))}),_.push("</Activities>"),_.join(`
19
- `)}buildActivity(t){let I=[`<Activity Sport="${t.Sport||"Other"}">`];return I.push(`<Id>${this.formatTime(t.Id)}</Id>`),t.Lap&&t.Lap.length>0&&t.Lap.forEach(A=>{I.push(this.buildActivityLap(A))}),this.addOptionalElement(I,"Notes",t.Notes),t.Training,t.Creator,t.Extensions&&I.push(this.buildExtensions(t.Extensions)),I.push("</Activity>"),I.join(`
20
- `)}buildActivityLap(t){let I=[`<Lap${t.StartTime?` StartTime="${this.escapeXMLAttribute(this.formatTime(t.StartTime))}"`:""}>`];return this.addOptionalNumericElement(I,"TotalTimeSeconds",t.TotalTimeSeconds),this.addOptionalNumericElement(I,"DistanceMeters",t.DistanceMeters),this.addOptionalNumericElement(I,"MaximumSpeed",t.MaximumSpeed),this.addOptionalNumericElement(I,"Calories",t.Calories),t.AverageHeartRateBpm&&I.push(`<AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${t.AverageHeartRateBpm}</Value></AverageHeartRateBpm>`),t.MaximumHeartRateBpm&&I.push(`<MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${t.MaximumHeartRateBpm}</Value></MaximumHeartRateBpm>`),this.addOptionalElement(I,"Intensity",t.Intensity),t.Cadence&&I.push(this.buildCadence(t.Cadence)),this.addOptionalElement(I,"TriggerMethod",t.TriggerMethod),t.Track&&t.Track.forEach(A=>{I.push(this.buildTrack(A))}),this.addOptionalElement(I,"Notes",t.Notes),t.Extensions&&I.push(this.buildExtensions(t.Extensions)),I.push("</Lap>"),I.join(`
21
- `)}buildTrack(t){let _=["<Track>"];return t.Trackpoint&&t.Trackpoint.forEach(I=>{_.push(this.buildTrackpoint(I))}),_.push("</Track>"),_.join(`
22
- `)}buildTrackpoint(t){let _=["<Trackpoint>"];return t.Time?(_.push(`<Time>${this.formatTime(t.Time)}</Time>`),t.Position&&_.push(this.buildPosition(t.Position)),this.addOptionalNumericElement(_,"AltitudeMeters",t.AltitudeMeters),this.addOptionalNumericElement(_,"DistanceMeters",t.DistanceMeters),t.HeartRateBpm&&_.push(`<HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${t.HeartRateBpm}</Value></HeartRateBpm>`),t.Cadence&&_.push(this.buildCadence(t.Cadence)),this.addOptionalElement(_,"SensorState",t.SensorState),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.push("</Trackpoint>"),_.join(`
23
- `)):""}buildGeoCoords(t){let _=[];return t?.LatitudeDegrees&&_.push(`<LatitudeDegrees>${this.formatCoordinate(parseFloat(t.LatitudeDegrees))}</LatitudeDegrees>`),t?.LongitudeDegrees&&_.push(`<LongitudeDegrees>${this.formatCoordinate(parseFloat(t.LongitudeDegrees))}</LongitudeDegrees>`),_.join("")}wrapGeoTag(t,_){if(!_)return"";let I=this.buildGeoCoords(_);return I?`<${t}>${I}</${t}>`:""}buildPosition(t){let _=this.buildGeoCoords(t);return _?`<Position>${_}</Position>`:""}buildCadence(t){return`<Cadence><Low>${t.Low}</Low><High>${t.High}</High></Cadence>`}buildMultiActivitySession(t){let _=["<MultiActivitySession>"];return t.Id&&_.push(`<Id>${this.formatTime(t.Id)}</Id>`),t.FirstActivity&&_.push(this.buildFirstActivity(t.FirstActivity)),t.NextActivity&&t.NextActivity.forEach(I=>{_.push(this.buildNextActivity(I))}),this.addOptionalElement(_,"Notes",t.Notes),_.push("</MultiActivitySession>"),_.join(`
24
- `)}buildFirstActivity(t){let _=["<FirstActivity>"];return t.Activity&&_.push(this.buildActivity(t.Activity)),_.push("</FirstActivity>"),_.join(`
25
- `)}buildNextActivity(t){let _=["<NextActivity>"];return t.Transition&&_.push(`<Transition>${this.buildActivityLap(t.Transition)}</Transition>`),t.Activity&&_.push(this.buildActivity(t.Activity)),_.push("</NextActivity>"),_.join(`
26
- `)}buildWorkouts(t){return"<Workouts></Workouts>"}buildCourses(t){let _=["<Courses>"];return t.Course?.length&&t.Course.forEach(I=>{_.push(this.buildCourseElement(I))}),_.push("</Courses>"),_.join(`
27
- `)}buildCourseElement(t){let _=["<Course>"];return this.addOptionalElement(_,"Name",t.Name),this.addOptionalElement(_,"Notes",t.Notes),t.Lap?.length&&t.Lap.forEach(I=>{_.push(this.buildCourseLap(I))}),t.Track?.length&&t.Track.forEach(I=>{_.push(this.buildTrack(I))}),t.CoursePoint?.length&&t.CoursePoint.forEach(I=>{_.push(this.buildCoursePoint(I))}),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.push("</Course>"),_.join(`
28
- `)}buildCourseLap(t){let _=["<Lap>"];this.addOptionalNumericElement(_,"TotalTimeSeconds",t.TotalTimeSeconds),this.addOptionalNumericElement(_,"DistanceMeters",t.DistanceMeters),_.push(this.wrapGeoTag("BeginPosition",t.BeginPosition)),_.push(this.wrapGeoTag("EndPosition",t.EndPosition)),this.addOptionalNumericElement(_,"BeginAltitudeMeters",t.BeginAltitudeMeters),this.addOptionalNumericElement(_,"EndAltitudeMeters",t.EndAltitudeMeters);let I=t;return I.Track?.length&&I.Track.forEach(A=>{_.push(this.buildTrack(A))}),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.push("</Lap>"),_.join(`
29
- `)}buildCoursePoint(t){let _=["<CoursePoint>"];return this.addOptionalElement(_,"Name",t.Name),t.Time!==void 0&&t.Time!==null&&_.push(`<Time>${t.Time}</Time>`),t.Position&&_.push(this.buildPosition(t.Position)),this.addOptionalNumericElement(_,"AltitudeMeters",t.AltitudeMeters),this.addOptionalElement(_,"PointType",t.PointType),this.addOptionalElement(_,"Notes",t.Notes),t.Extensions&&_.push(this.buildExtensions(t.Extensions)),_.push("</CoursePoint>"),_.join("")}buildAuthor(t){let _=["<Author>"];return this.addOptionalElement(_,"Name",t.Name),_.push("</Author>"),_.join("")}buildExtensions(t){let _=this.buildExtensionContent(t);return _?`<Extensions>${_}</Extensions>`:""}buildExtensionContent(t){return Object.entries(t).filter(([_])=>!_.startsWith("xmlns")).map(([_,I])=>{if(I&&typeof I=="object"){let A=this.buildExtensionContent(I);return`<${_}>${A}</${_}>`}else if(I!=null)return`<${_}>${this.escapeXML(String(I))}</${_}>`;return""}).filter(_=>_).join("")}formatTime(t){let _=zt(t);if(!_.isValid())throw new Error(`Cannot encode invalid TCX timestamp: ${String(t)}`);return _.toISOString()}addOptionalElement(t,_,I,A){if(I!=null&&I!==""){let T=A?A(I):this.escapeXML(I);t.push(`<${_}>${T}</${_}>`)}}addOptionalNumericElement(t,_,I){I!=null&&!isNaN(I)&&t.push(`<${_}>${I}</${_}>`)}isValidCoordinate(t,_){return t!=null&&_!==void 0&&_!==null&&!isNaN(t)&&!isNaN(_)}formatCoordinate(t){return this.roundTo(t,6).toString()}roundTo(t,_){let I=Math.pow(10,_);return Math.round(t*I)/I}escapeXML(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeXMLAttribute(t){return typeof t!="string"?String(t||""):t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;").replace(/\n/g,"&#10;").replace(/\t/g,"&#9;")}deepClone(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t))return t.map(I=>this.deepClone(I));let _={};for(let I in t)Object.prototype.hasOwnProperty.call(t,I)&&(_[I]=this.deepClone(t[I]));return _}encoder(t){return this.encode(t)}};import bI from"dayjs";var a=class extends q{convertPoints(t){return t.map(_=>this.convertPoint(_)).filter(_=>_!==void 0)}convertTime(t){if(!t)return;if(typeof t=="number")return t;let _=bI(t);return _.isValid()?_.valueOf():void 0}},x=class{constructor(){this.version="1.0.0";this.priority=100}supports(t){return this.supportedTags.includes(t)}async initialize(t){t.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(t){t.metadata.delete(`plugin:${this.name}:initialized`)}async validate(t){return!0}convertTimeToDate(t){return t?new Date(t):new Date}convertTimeToString(t){return this.convertTimeToDate(t).toISOString()}ensureValidCoordinates(t,_){return t>=-90&&t<=90&&_>=-180&&_<=180}round(t,_=6){let I=Math.pow(10,_);return Math.round(t*I)/I}};var jt={heartrate:"heartRate","gpxtpx:hr":"heartRate","ns3:hr":"heartRate","gpxdata:hr":"heartRate","gpxdata:cadence":"cadence","gpxtpx:cad":"cadence","ns3:cad":"cadence",cadence:"cadence","gpxtpx:speed":"speed","ns3:speed":"speed",speed:"speed",power:"power","gpxdata:power":"power","gpxpx:PowerInWatts":"power",PowerInWatts:"power","gpxtpx:temp":"temperature","gpxtpx:wtemp":"wtemp","gpxtpx:atemp":"atemp","gpxx:Temperature":"temperature","gpxx:Depth":"depth"},yt=R=>R*(180/Math.pow(2,31)),Zt=2147483647;function j(R,t=6){if(R==null)return;let _=typeof R=="number"?R:Number(R);if(!Number.isFinite(_)||_===Zt)return;let I=yt(_),A=Math.pow(10,t);return Math.round(I*A)/A}import e_ from"dayjs";import x_ from"dayjs";import{getPreciseDistance as NI}from"geolib";var u=class{calculateRecordsAggMetrics(t){if(!t||t.length===0)return;let _={records:this.preprocessRecords(t)};for(let I=0;I<_.records.length;I++){let A=_.records[I];if(!(A.positionLat==null||A.positionLong==null||!Number.isFinite(A.positionLat)||!Number.isFinite(A.positionLong))){if(_.startPositionLat==null&&(_.startPositionLat=A.positionLat),_.startPositionLong==null&&(_.startPositionLong=A.positionLong),_.endPositionLat=A.positionLat,_.endPositionLong=A.positionLong,_.timestamp=A.timestamp,_?.startTime||(_.startTime=A.timestamp),_.endTime=A.timestamp,_.totalDistance=A.distance,_.totalElapsedTime=x_(A.timestamp).diff(x_(_.startTime),"second"),A?.speed&&(_.avgSpeed=_.avgSpeed?(_.avgSpeed+A.speed)/2:A.speed,_.maxSpeed=Math.max(_.maxSpeed||0,A.speed)),A?.heartRate&&(_.maxHeartRate=Math.max(_.maxHeartRate||0,A.heartRate),_.minHeartRate=Math.min(_.minHeartRate||A.heartRate,A.heartRate),_.avgHeartRate?_.avgHeartRate=(_.avgHeartRate+A.heartRate)/2:_.avgHeartRate=A.heartRate),A?.altitude&&(_.maxAltitude=Math.max(_.maxAltitude||0,A.altitude),_.minAltitude=Math.min(_.minAltitude||A.altitude,A.altitude),_.avgAltitude=_.avgAltitude?(_.avgAltitude+A.altitude)/2:A.altitude,I>0&&t[I-1].altitude)){let T=this.calculateElevationChanges(t[I-1],A);_.totalAscent=(_.totalAscent||0)+T.ascent,_.totalDescent=(_.totalDescent||0)+T.descent}if(A?.cadence&&(_.maxCadence=Math.max(_.maxCadence||0,A.cadence),_.avgCadence?_.avgCadence=(_.avgCadence+A.cadence)/2:_.avgCadence=A.cadence),A?.power){_.maxPower=Math.max(_.maxPower||0,A.power),_.avgPower?_.avgPower=(_.avgPower+A.power)/2:_.avgPower=A.power;let T=this.calculateAccumulatedPower(I>0?t[I-1]:A,A,_.totalWork||0);_.totalWork=T.newAccumulatedWork,_.normalizedPower=void 0}A?.temperature&&(_.avgTemperature?_.avgTemperature=(_.avgTemperature+A.temperature)/2:_.avgTemperature=A.temperature,_.maxTemperature=Math.max(_.maxTemperature||0,A.temperature),_.minTemperature=Math.min(_.minTemperature||A.temperature,A.temperature))}}return _}calculateLapAggMetrics(t){if(!t||t.length===0)return;let _={laps:t,timestamp:t[0]?.timestamp||new Date};for(let I=0;I<t.length;I++){let A=t[I];A.startPositionLat&&A.startPositionLong&&!_?.startPositionLat&&!_?.startPositionLong&&(_.startPositionLat=A.startPositionLat,_.startPositionLong=A.startPositionLong),A.endPositionLat&&A.endPositionLong&&(_.endPositionLat=A.endPositionLat,_.endPositionLong=A.endPositionLong),A.startTime&&!_?.startTime&&(_.startTime=A.startTime),A.endTime&&(_.endTime=A.endTime),_.timestamp=A.timestamp||A.endTime||_.timestamp,A.totalDistance&&(_.totalDistance=(_.totalDistance||0)+A.totalDistance),A.totalElapsedTime&&(_.totalElapsedTime=(_.totalElapsedTime||0)+A.totalElapsedTime),A.totalMovingTime&&(_.totalMovingTime=(_.totalMovingTime||0)+A.totalMovingTime),A.totalTimerTime&&(_.totalTimerTime=(_.totalTimerTime||0)+A.totalTimerTime),A.maxSpeed&&(_.maxSpeed=Math.max(_.maxSpeed||0,A.maxSpeed)),A.avgSpeed&&(_.avgSpeed?_.avgSpeed=(_.avgSpeed+A.avgSpeed)/2:_.avgSpeed=A.avgSpeed),A.maxHeartRate&&(_.maxHeartRate=Math.max(_.maxHeartRate||0,A.maxHeartRate)),A.minHeartRate&&(_.minHeartRate=_.minHeartRate?Math.min(_.minHeartRate,A.minHeartRate):A.minHeartRate),A.avgHeartRate&&(_.avgHeartRate?_.avgHeartRate=(_.avgHeartRate+A.avgHeartRate)/2:_.avgHeartRate=A.avgHeartRate),A.maxAltitude&&(_.maxAltitude=Math.max(_.maxAltitude||0,A.maxAltitude)),A.minAltitude&&(_.minAltitude=_.minAltitude?Math.min(_.minAltitude,A.minAltitude):A.minAltitude),A.avgAltitude&&(_.avgAltitude?_.avgAltitude=(_.avgAltitude+A.avgAltitude)/2:_.avgAltitude=A.avgAltitude),A.totalAscent&&(_.totalAscent=(_.totalAscent||0)+A.totalAscent),A.totalDescent&&(_.totalDescent=(_.totalDescent||0)+A.totalDescent),A.maxCadence&&(_.maxCadence=Math.max(_.maxCadence||0,A.maxCadence)),A.avgCadence&&(_.avgCadence?_.avgCadence=(_.avgCadence+A.avgCadence)/2:_.avgCadence=A.avgCadence),A.maxPower&&(_.maxPower=Math.max(_.maxPower||0,A.maxPower)),A.avgPower&&(_.avgPower?_.avgPower=(_.avgPower+A.avgPower)/2:_.avgPower=A.avgPower),A.totalWork&&(_.totalWork=(_.totalWork||0)+A.totalWork),A.maxTemperature&&(_.maxTemperature=Math.max(_.maxTemperature||0,A.maxTemperature)),A.minTemperature&&(_.minTemperature=_.minTemperature?Math.min(_.minTemperature,A.minTemperature):A.minTemperature),A.avgTemperature&&(_.avgTemperature?_.avgTemperature=(_.avgTemperature+A.avgTemperature)/2:_.avgTemperature=A.avgTemperature)}return _}preprocessRecords(t){if(!t||t.length===0)return t;let _=t.filter(n=>n.timestamp).sort((n,L)=>n.timestamp.valueOf()-L.timestamp.valueOf()),I=0,A=0,T=[];for(let n=0;n<_.length;n++){let L=_[n],E={...L};if(n>0){let f=this.calculatePointDistanceByPosition(_[n-1],E)||0;if(E.distance||(A+=f,E.distance=A),L.speed||(E.speed=this.calculateInstantSpeed(_[n-1],E,f)),L.power){let G=this.calculateAccumulatedPower(_[n-1],E,I);E.accumulatedPower=G.accumulatedPower,I=G.newAccumulatedWork}}T.push(E)}return T}calculatePointDistanceByPosition(t,_){if(!(t.positionLat==null||t.positionLong==null||_.positionLat==null||_.positionLong==null||!Number.isFinite(t.positionLat)||!Number.isFinite(t.positionLong)||!Number.isFinite(_.positionLat)||!Number.isFinite(_.positionLong)))try{return NI({latitude:t.positionLat,longitude:t.positionLong},{latitude:_.positionLat,longitude:_.positionLong})}catch{return}}calculateInstantSpeed(t,_,I){if(!t.timestamp||!_.timestamp||!I)return;let A=(x_(_.timestamp).valueOf()-x_(t.timestamp).valueOf())/1e3;if(!(A<=0))return I/A}calculateAccumulatedPower(t,_,I){if(t.power===void 0||_.power===void 0||!t.timestamp||!_.timestamp)return{accumulatedPower:I,newAccumulatedWork:I};let A=_.timestamp?.valueOf()-t.timestamp?.valueOf();if(A<=0)return{accumulatedPower:I,newAccumulatedWork:I};let n=(t.power+_.power)/2*A,L=I+n;return{accumulatedPower:L,newAccumulatedWork:L}}calculateElevationChanges(t,_){let I=0,A=0;return _.altitude!==void 0&&t.altitude!==void 0&&(_.altitude>t.altitude?I=_.altitude-t.altitude:_.altitude<=t.altitude&&(A=t.altitude-_.altitude)),{ascent:I,descent:A}}};var _t=class extends a{constructor(){super(...arguments);this.name="gpx-to-activity-converter";this.supportedTags=["gpx"];this.convertGPXExtensions=_=>{let I={};return Object.entries(_).forEach(([A,T])=>{if(typeof T<"u"&&T!=="undefined"){let n=jt[A]||A;I[n]=this.autoNumber(T)}}),I}}convert(_,I){if(I.sourceFormat!=="gpx")return;let A=I.sourceData;return this.convertGPX(A)}convertGPX(_){let I={metadata:{originType:"GPX",fileType:"gpx"},activities:[]};return _.wpt&&(I.points=this.convertWpts2Points(_.wpt)),_.trk&&(I.activities=_.trk.map((A,T)=>this.convertTrk2Activity(A,T))),_.rte&&(I.routes=_.rte.map((A,T)=>this.convertRoute2Lap(A,T))),I}convertPoint(_,I,A){let{extensions:T}=_,n=T?this.convertGPXExtensions(T):{};return{lapIndex:A||0,index:I||0,positionLat:_?.lat,positionLong:_?.lon,altitude:_?.ele,heartRate:_?.heartRate,speed:_?.speed,power:_?.power,cadence:_?.cadence,course:_?.course,magvar:_?.magvar,geoidheight:_?.geoidheight,pointName:_?.name,comment:_?.cmt,description:_?.desc,source:_?.src,links:_?.link,symbol:_?.sym,pointType:_?.type,fix:_?.fix,sat:_?.sat,hdop:_?.hdop,vdop:_?.vdop,pdop:_?.pdop,ageofdgpsdata:_?.ageofdgpsdata,dgpsid:_?.dgpsid,gpxExtensions:_?.extensions,timestamp:_.time?e_(_.time).toDate():void 0,...n}}convertTrk2Activity(_,I){let A=_.trkseg?.map((n,L)=>this.convertTrackSeg2Lap(n,L))||[],T=new u().calculateLapAggMetrics(A);return{index:I,messageIndex:I,activityName:_.name,comment:_.cmt,description:_.desc,source:_.src,links:_.link,activityNumber:_.number,sport:_.type,gpxExtensions:_.extensions,laps:A,...T}}convertTrackSeg2Lap(_,I){return{...this.convertPoints2Lap(_.trkpt??[],I),gpxExtensions:_.extensions}}convertRoute2Lap(_,I){return{...this.convertPoints2Lap(_.rtept??[],I,_.name),comment:_.cmt,description:_.desc,source:_.src,links:_.link,routeNumber:_.number,routeType:_.type,gpxExtensions:_.extensions}}convertPoints2Lap(_,I,A){let T=_.map((G,U)=>this.convertPoint(G,U,I)),L=new u().calculateRecordsAggMetrics(T),E=new Map((L?.records??[]).map(G=>[G.index,G])),f=T.map(G=>E.get(G.index)??G);return{index:I,messageIndex:I,routeName:A,...L,records:f,lengths:[]}}convertWpts2Points(_){let I=[];for(let A=0;A<_.length;A++){let T=this.convertPoint(_[A],A);T&&I.push(T)}return I}autoNumber(_){return typeof _=="string"&&_.trim()!==""&&!isNaN(_)?Number(_):_}},tt=class extends a{constructor(){super(...arguments);this.name="fit-to-activity-converter";this.supportedTags=["fit"]}convert(_,I){if(I.sourceFormat!=="fit")return;let A=I.sourceData;return this.convertFIT(A)}convertFIT(_){let I={metadata:{originType:"FIT",fileType:"fit"},activities:[]};return _.sessionMesgs?.length?I.activities=_.sessionMesgs.map((A,T)=>({index:T,...A,startPositionLat:j(A?.startPositionLat),startPositionLong:j(A?.startPositionLong),endPositionLat:j(A?.endPositionLat),endPositionLong:j(A?.endPositionLong),laps:this.convertFITLap2Trackseg(A?.lapMesgs)})):_.courseMesgs?.length&&(I.routes=_.courseMesgs.map((A,T)=>({index:T,...A,records:this.convertLap2Points(A?.lapMesgs)}))),I}convertPoint(_,I,A){let{positionLong:T,positionLat:n,altitude:L,enhancedAltitude:E,enhancedSpeed:f,speed:G,...U}=_,K=n??_.position_lat,s=T??_.position_long;return{lapIndex:A||0,index:I||0,positionLat:j(K),positionLong:j(s),altitude:L,enhancedAltitude:E,speed:G,enhancedSpeed:f,...U}}convertFITLap2Trackseg(_){let I=[];if(!_?.length)return[];for(let A=0;A<_.length;A++){let T=_[A],n=T?.recordMesgs?.map((E,f)=>this.convertPoint(E,f,A)).filter(E=>E!==void 0)||[],L=T?.lengthMesgs?.map((E,f)=>({...E,index:f}))||[];I.push({index:A,...T,startPositionLat:j(T?.startPositionLat),startPositionLong:j(T?.startPositionLong),endPositionLat:j(T?.endPositionLat),endPositionLong:j(T?.endPositionLong),records:n,lengths:L})}return I}convertLap2Points(_){let I=[];if(!_?.length)return[];for(let A=0;A<_.length;A++){let n=_[A].recordMesgs?.map((L,E)=>this.convertPoint(L,E,A)).filter(L=>L!==void 0)||[];n.length&&(I=[...I,...n])}return I}},It=class extends a{constructor(){super(...arguments);this.name="tcx-to-activity-converter";this.supportedTags=["tcx"]}convert(_,I){if(I.sourceFormat!=="tcx")return;let A=I.sourceData;return this.convertTCX(A)}convertTCX(_){let I={metadata:{originType:"TCX",fileType:"tcx"},activities:[]};_.Activities?.Activity?.length&&(I.activities=_.Activities.Activity.map((n,L)=>this.convertTCXActivityToActivity(n,L)));let A=_.Courses?.Course,T=A==null?[]:Array.isArray(A)?A:[A];return T.length&&(I.routes=T.map((n,L)=>this.convertTCXCourseToRoute(n,L))),I}convertTCXCourseToRoute(_,I){let A=[],T=0,n=B=>B==null?[]:Array.isArray(B)?B:[B],L=B=>{for(let k of B??[])for(let P of k.Trackpoint??[])P==null||P.Time===void 0||A.push(this.convertPoint(P,T++,I))};L(n(_.Track));let E=_.Lap==null?[]:Array.isArray(_.Lap)?_.Lap:[_.Lap];for(let B of E)L(n(B.Track));let f=A.length,G=A[0]?.timestamp!=null?e_(A[0].timestamp):e_("2000-01-01T00:00:00Z"),U=_.CoursePoint==null?[]:Array.isArray(_.CoursePoint)?_.CoursePoint:[_.CoursePoint];for(let B of U){let k=this.convertTCXCoursePointToRecord(B,f++,I,G);k&&A.push(k)}let K=new u,s=A.length>0?K.calculateRecordsAggMetrics(A):{records:A};return{index:I,messageIndex:I,routeName:_.Name,...s,records:s?.records??A,lengths:[]}}convertTCXCoursePointToRecord(_,I,A,T){let n=_.Position?.LatitudeDegrees?Number(_.Position.LatitudeDegrees):void 0,L=_.Position?.LongitudeDegrees?Number(_.Position.LongitudeDegrees):void 0;if(n==null&&L==null&&_.AltitudeMeters==null)return;let E=typeof _.Time=="number"&&Number.isFinite(_.Time)?T.add(_.Time,"second").toDate():T.add(I,"second").toDate();return{lapIndex:A,index:I,positionLat:n,positionLong:L,altitude:_.AltitudeMeters,timestamp:E}}convertTCXActivityToActivity(_,I){let A=_.Lap?.map((n,L)=>this.convertTCXLap2Lap(n,L))||[],T=new u().calculateLapAggMetrics(A);return{index:I,messageIndex:I,sport:_.Sport?.toLowerCase(),laps:A,...T}}convertTCXLap2Lap(_,I){let T=(_?.Track?.flatMap(E=>E.Trackpoint)||[])?.filter(E=>E!==void 0&&E.Time!==void 0).map((E,f)=>this.convertPoint(E,f))||[],L=new u().calculateRecordsAggMetrics(T);return{index:I,messageIndex:I,...L,records:L?.records||[],lengths:[]}}convertPoint(_,I,A){let{Position:T,Time:n,DistanceMeters:L,AltitudeMeters:E}=_;return{lapIndex:A||0,index:I||0,positionLat:T?.LatitudeDegrees?Number(T.LatitudeDegrees):void 0,positionLong:T?.LongitudeDegrees?Number(T.LongitudeDegrees):void 0,timestamp:e_(n).toDate(),distance:L,altitude:E}}};import $I from"dayjs";var At=class extends x{constructor(){super(...arguments);this.name="activity-to-gpx-encoder";this.supportedTags=["gpx"]}encode(_,I){if(I.targetFormat!=="gpx"||!_?.activities?.length&&!_?.routes?.length&&!_?.points?.length)return;let A=_.activities?.[0]?.timestamp??_.routes?.[0]?.records?.[0]?.timestamp??_.points?.[0]?.timestamp??new Date,T=this.countRecordsMissingGpxCoordinates(_),n={version:"1.1",creator:"TrackSwap",metadata:{time:A,...T>0?{desc:`TrackSwap: omitted ${T} trackpoint(s) without valid latitude/longitude.`}:{}}};return _.points?.length&&(n.wpt=this.convertRecords2Wpts(_.points)),_.routes?.length&&(n.rte=_.routes.map(L=>this.convertRoute2GPXRoute(L))),_.activities?.length&&(n.trk=_.activities.map(L=>this.convertActivity2GPXTrack(L))),n}hasValidGpxCoordinates(_){let I=_.positionLat,A=_.positionLong;return typeof I=="number"&&typeof A=="number"&&Number.isFinite(I)&&Number.isFinite(A)&&I>=-90&&I<=90&&A>=-180&&A<=180}countRecordsMissingGpxCoordinates(_){let I=0,A=T=>{for(let n of T??[])this.hasValidGpxCoordinates(n)||I++};A(_.points);for(let T of _.activities??[])for(let n of T.laps??[])A(n.records);for(let T of _.routes??[])A(T.records);return I}convertRecords2Wpts(_){return _?.filter(I=>this.hasValidGpxCoordinates(I)).map(I=>({lat:I?.positionLat,lon:I?.positionLong,ele:I?.altitude,time:I?.timestamp,speed:I?.speed,course:I?.course,magvar:I?.magvar,geoidheight:I?.geoidheight,name:I?.pointName,cmt:I?.comment,desc:I?.description,src:I?.source,link:I?.links,sym:I?.symbol,type:I?.pointType,fix:I?.fix,sat:I?.sat,hdop:I?.hdop,vdop:I?.vdop,pdop:I?.pdop,ageofdgpsdata:I?.ageofdgpsdata,dgpsid:I?.dgpsid,extensions:this.extractGPXExtensions(I)}))??[]}convertRoute2GPXRoute(_){return{name:_.routeName,cmt:_.comment,desc:_.description,src:_.source,link:_.links,number:_.routeNumber,type:_.routeType,extensions:_.gpxExtensions,rtept:_.records?this.convertRecords2Wpts(_.records):[]}}convertActivity2GPXTrack(_){return{name:_.activityName,cmt:_.comment,desc:_.description,src:_.source,link:_.links,number:_.activityNumber,type:_.sport,extensions:_.gpxExtensions,trkseg:_.laps?.map(I=>({trkpt:I.records?this.convertRecords2Wpts(I.records):[],extensions:I.gpxExtensions}))||[]}}extractGPXExtensions(_){let I={..._.gpxExtensions??{}},A={...I["gpxtpx:TrackPointExtension"]??{}};return typeof _?.heartRate<"u"&&(A["gpxtpx:hr"]=_.heartRate),typeof _?.cadence<"u"&&(A["gpxtpx:cad"]=_.cadence),typeof _?.speed<"u"&&(A["gpxtpx:speed"]=_.speed),typeof _?.temperature<"u"&&(A["gpxtpx:atemp"]=_.temperature),Object.keys(A).length>0&&(I["gpxtpx:TrackPointExtension"]=A),typeof _?.power<"u"&&(I["gpxpx:PowerExtension"]={"gpxpx:PowerInWatts":_.power}),Object.keys(I).length>0?I:void 0}},Tt=class extends x{constructor(){super(...arguments);this.name="activity-to-fit-encoder";this.supportedTags=["fit"]}encode(_,I){if(I.targetFormat==="fit"){if(_?.activities?.length){let A={};return A.sessionMesgs=_.activities.map(T=>this.convertActivity2FITSession(T)),A}if(_?.routes?.length){let A={};return A.sessionMesgs=[this.convertRoutesToSyntheticSession(_.routes)],A}}}convertRoutesToSyntheticSession(_){let I=_.map(f=>this.convertLap2FITLap(f)),T=_.flatMap(f=>f.records??[]).filter(f=>f.timestamp!=null).sort((f,G)=>new Date(f.timestamp).getTime()-new Date(G.timestamp).getTime()),n=T[0]?.timestamp??new Date,L=T[T.length-1]?.timestamp??n,E=T.find(f=>f.positionLat!=null&&f.positionLong!=null&&Number.isFinite(f.positionLat)&&Number.isFinite(f.positionLong));return{messageIndex:0,timestamp:L,event:"session",eventType:"stop",startTime:n,startPositionLat:E?.positionLat,startPositionLong:E?.positionLong,sport:"generic",subSport:"generic",lapMesgs:I}}convertActivity2FITSession(_){return{..._,event:_?.event||"session",sport:_?.sport||"generic",lapMesgs:_.laps?.map(A=>this.convertLap2FITLap(A))||[]}}convertLap2FITLap(_){return{startTime:_.startTime,..._,recordMesgs:_.records?.map(A=>this.convertPoint2FITRecord(A))||[]}}convertPoint2FITRecord(_){return _}},nt=class extends x{constructor(){super(...arguments);this.name="sport-to-tcx-encoder";this.supportedTags=["tcx"]}encode(_,I){if(I.targetFormat!=="tcx")return;let A=!!_?.activities?.length,T=!!_?.routes?.length;if(!A&&!T)return;let n={version:"1.0",Author:{Name:"TrackSwap"}};return A&&(n.Activities={Activity:_.activities.map(L=>this.convertActivity2TCXActivity(L))}),T&&(n.Courses={Course:_.routes.map((L,E)=>this.convertRouteToTCXCourse(L,E))}),n}convertActivity2TCXActivity(_){if(!_.laps?.length)throw new Error("Cannot encode a TCX activity without laps");let I="Other",A=_.sport?.toLowerCase();return A==="running"&&(I="Running"),(A==="biking"||A==="cycling")&&(I="Biking"),{Id:this.validTimestamp(_.startTime??_.laps[0]?.startTime??_.laps[0]?.records?.[0]?.timestamp),Sport:I,Lap:_.laps.map(n=>this.convertLap2TCXLap(n))}}convertLap2TCXLap(_){let A={StartTime:this.validTimestamp(_.startTime??_.records?.[0]?.timestamp),TotalTimeSeconds:_.totalElapsedTime,DistanceMeters:_.totalDistance,MaximumSpeed:_.maxSpeed,Calories:_.totalCalories,AverageHeartRateBpm:_.avgHeartRate,MaximumHeartRateBpm:_.maxHeartRate,Intensity:"Active",TriggerMethod:"Manual",Track:_.records?[this.convertRecords2TCXTrack(_.records)]:[]};return(_.avgCadence!==void 0||_.maxCadence!==void 0)&&(A.Cadence={Low:_.avgCadence||0,High:_.maxCadence||0}),A}convertRecords2TCXTrack(_){return{Trackpoint:_.map(I=>this.convertPoint2TCXTrackpoint(I))}}convertPoint2TCXTrackpoint(_){let I={Time:this.validTimestamp(_.timestamp),Position:{LatitudeDegrees:_?.positionLat?.toString(),LongitudeDegrees:_?.positionLong?.toString()},AltitudeMeters:_.altitude,DistanceMeters:_.distance};return _.heartRate&&(I.HeartRateBpm=_.heartRate),_.cadence&&(I.Cadence={Low:_.cadence,High:_.cadence256||_.cadence}),_.power&&(I.Extensions={"ns3:TPX":{"ns3:Watts":_.power}}),I}validTimestamp(_){let I=$I(_);if(!_||!I.isValid())throw new Error("Cannot encode TCX data without valid timestamps");return I.toISOString()}convertRouteToTCXCourse(_,I){return{Name:_.routeName??`Course_${I}`,Track:_.records?[this.convertRecords2TCXTrack(_.records)]:[]}}};var Rt=class{constructor(){this.converters=new Map;this.encoders=new Map;this.registerDefaultConverters(),this.registerDefaultEncoders()}registerDefaultConverters(){this.registerConverter(new _t),this.registerConverter(new tt),this.registerConverter(new It)}registerDefaultEncoders(){this.registerEncoder(new At),this.registerEncoder(new Tt),this.registerEncoder(new nt)}registerConverter(t){this.converters.set(t.name,t)}registerEncoder(t){this.encoders.set(t.name,t)}async convertToActivity(t,_){let I={metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},sourceFormat:_,sourceData:t,performance:{startTime:Date.now()}};try{let A=this.findConverter(_);if(!A)throw new Error(`No converter found for format "${_}"`);let T=Date.now(),n=A.convert(t,I);if(I.performance.convertTime=Date.now()-T,!n)throw new Error(`Converter "${A.name}" returned empty result`);let L=n;return I.result=L,I.performance.endTime=Date.now(),I.stats.endTime=Date.now(),L}catch(A){throw I.errors.push(A),A}}async encodeActivity(t,_){let I={metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},targetFormat:_,performance:{startTime:Date.now()}};try{let A=this.findEncoder(_);if(!A)throw new Error(`No encoder found for format "${_}"`);let T=Date.now(),n=A.encode(t,I);if(I.performance.encodeTime=Date.now()-T,!n)throw new Error(`Encoder "${A.name}" returned empty result`);return I.result=n,I.performance.endTime=Date.now(),I.stats.endTime=Date.now(),n}catch(A){throw I.errors.push(A),A}}findConverter(t){return Array.from(this.converters.values()).find(_=>_.supportedTags?.includes(t))}findEncoder(t){return Array.from(this.encoders.values()).find(_=>_.supportedTags?.includes(t))}async destroy(){this.converters.clear(),this.encoders.clear()}};var qt=8,kI=".FIT";function QI(R){return R.toString("utf8",0,Math.min(R.length,4096)).replace(/^\uFEFF/,"")}function JI(R){if(R.length>=12&&R.toString("ascii",qt,qt+4)===kI)return"fit";let t=QI(R);if(/<gpx\b/i.test(t))return"gpx";if(/<TrainingCenterDatabase\b/i.test(t))return"tcx"}var __=class{constructor(t){this.activities=t}matches(t){return JI(t)===this.format}},Gt=class extends __{constructor(){super(...arguments);this.format="fit"}getDecoder(){return this.decoder??=new f_}getEncoder(){return this.encoder??=new U_}async decode(_,I){let A=await this.getDecoder().parseByBuffer(_,{userData:{fitDocumentOptions:I.fit??{}}});if(!A)throw new Error("FIT decoder returned an empty result");let T=A.fitDocumentMetadata?.detectedKinds??["unknown"],n=T.includes("activity")?await this.activities.convertToActivity(A,"fit"):void 0,L=A.healthDocument?.diagnostics??{parserVersion:n_,messageCounts:A.fitDocumentMetadata?.messageCounts??{},recognizedMessageCounts:{},unknownMessageCounts:{},invalidValueCounts:{},warningCounts:{},warnings:[]},E=A.fileIdMesgs?.[0],f=E,G=A.fileCreatorMesgs?.[0];return{kinds:[...T],facets:{activity:n,health:A.healthDocument},native:A,metadata:{fileType:E?.type,manufacturer:E?.manufacturer,product:E?.garminProduct??E?.product,productName:typeof f?.productName=="string"?f.productName:void 0,serialNumber:E?.serialNumber===void 0?void 0:String(E.serialNumber),createdAt:E?.timeCreated?new Date(E.timeCreated):void 0,softwareVersion:G?.softwareVersion},fitDiagnostics:L,warnings:L.warnings.map(U=>U.message)}}async encodeActivity(_){let I=await this.activities.encodeActivity(_,"fit");return this.getEncoder().encode(I)}async encodeCourse(_){return Buffer.from($t(Xt(_)))}async dispose(){await this.decoder?.destroy()}},gt=class extends __{constructor(){super(...arguments);this.format="gpx"}getDecoder(){return this.decoder??=new Y_}getEncoder(){return this.encoder??=new b_}async decode(_){let I=await this.getDecoder().parserByBuffer(_);if(!I)throw new Error("GPX decoder returned an empty result");let A=await this.activities.convertToActivity(I,"gpx"),T=[];return A.activities?.length&&T.push("activity"),A.routes?.length&&T.push("route"),A.points?.length&&T.push("waypoint"),T.length===0&&T.push("unknown"),{kinds:T,facets:{activity:A},native:I,metadata:{title:I.metadata?.name,creator:I.creator,createdAt:I.metadata?.time}}}async encodeActivity(_){let I=await this.activities.encodeActivity(_,"gpx");return this.getEncoder().encode(I)}async dispose(){await this.decoder?.destroy()}},lt=class extends __{constructor(){super(...arguments);this.format="tcx"}getDecoder(){return this.decoder??=new c_}getEncoder(){return this.encoder??=new a_}async decode(_){let I=await this.getDecoder().parseByBuffer(_);if(!I)throw new Error("TCX decoder returned an empty result");let A=await this.activities.convertToActivity(I,"tcx");return{kinds:A.activities?.length?["activity"]:A.routes?.length?["course"]:["unknown"],facets:{activity:A},native:I,metadata:{creator:I.Author?.Name??I.creator}}}async encodeActivity(_){let I=await this.activities.encodeActivity(_,"tcx");return this.getEncoder().encode(I)}async dispose(){await this.decoder?.destroy()}};function ut(){let R=new Rt;return{adapters:[new Gt(R),new gt(R),new lt(R)],activities:R}}function it(R){return R.format==="fit"&&"encodeCourse"in R}var Lt=class{constructor(t){this.adapters=new Map;for(let _ of t){if(this.adapters.has(_.format))throw new Q("ADAPTER_CONFLICT",`Multiple adapters registered for format "${_.format}"`,{format:_.format});this.adapters.set(_.format,_)}}get(t){let _=this.adapters.get(t);if(!_)throw new Q("FORMAT_UNSUPPORTED",`No adapter registered for format "${t}"`,{format:t});return _}detect(t){for(let _ of this.adapters.values())if(_.matches(t))return _.format;throw new Q("FORMAT_UNKNOWN","Unable to detect input format")}async dispose(){await Promise.all([...this.adapters.values()].map(t=>t.dispose?.()))}};function Wt(R){return typeof R=="string"?Buffer.from(R,"utf8"):Buffer.isBuffer(R)?R:Buffer.from(R.buffer,R.byteOffset,R.byteLength)}function zI(R){return typeof R=="string"||Buffer.isBuffer(R)||R instanceof Uint8Array}var Et=class{constructor(t={}){this.disposed=!1;let I=[...t.includeBuiltInAdapters===!1?[]:ut().adapters,...t.adapters??[]];this.registry=new Lt(I)}detect(t){return this.assertActive(),this.registry.detect(Wt(t))}async decode(t,_={}){this.assertActive();let I=Wt(t),A=_.format??this.registry.detect(I),T=this.registry.get(A),n=Date.now();try{let L=await T.decode(I,_);return{schemaVersion:"2",format:A,kinds:[...new Set(L.kinds)],source:{byteLength:I.byteLength},metadata:L.metadata??{},facets:L.facets,..._.includeNative?{native:L.native}:{},diagnostics:{durationMs:Date.now()-n,warnings:L.warnings??[],fit:L.fitDiagnostics}}}catch(L){throw t_(L,"DECODE_FAILED",`Failed to decode ${A.toUpperCase()}`,A)}}async decodeActivity(t,_={}){let I=await this.decode(t,_);if(!I.facets.activity)throw new Q("ACTIVITY_NOT_FOUND",`The ${I.format.toUpperCase()} document has no activity facet`,{format:I.format});return I.facets.activity}async encodeActivity(t,_){this.assertActive();try{return await this.registry.get(_.format).encodeActivity(t)}catch(I){throw t_(I,"ENCODE_FAILED",`Failed to encode ${_.format.toUpperCase()}`,_.format)}}async transcode(t,_){this.assertActive();let I=Wt(t),A=_.sourceFormat??this.registry.detect(I);if(A===_.format)return Buffer.from(I);let T=await this.decodeActivity(I,{format:A});return this.encodeActivity(T,{format:_.format})}async encodeCourse(t,_={}){this.assertActive();let I=zI(t)?await this.decodeActivity(t,{format:_.sourceFormat}):t,A=this.registry.get("fit");if(!it(A))throw new Q("FORMAT_UNSUPPORTED","The registered FIT adapter does not support course encoding",{format:"fit"});try{return await A.encodeCourse(I)}catch(T){throw t_(T,"ENCODE_FAILED","Failed to encode FIT course","fit")}}async dispose(){this.disposed||(this.disposed=!0,await this.registry.dispose())}assertActive(){if(this.disposed)throw new Q("DISPOSED","TrackSwap instance is disposed")}};export{Zt as FIT_SEMICIRCLE_INVALID_SINT32,n_ as TRACKSWAP_HEALTH_PARSER_VERSION,Et as TrackSwap,Q as TrackSwapError,ht as buildHealthDocumentFromMessages,Et as default,pt as detectFITKinds,j as normalizeFitSemicircleToDegrees,yt as semicirclesToDegrees};
1
+ var s=class extends Error{constructor(I,_,t={}){super(_),this.name="TrackSwapError",this.code=I,this.format=t.format,this.cause=t.cause}};function x(n,I,_,t){if(n instanceof s)return n;let A=n instanceof Error?n.message:String(n);return new s(I,`${_}: ${A}`,{format:t,cause:n})}var k=class{constructor(){this.version="1.0.0";this.priority=100}async initialize(I){I.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(I){I.metadata.delete(`plugin:${this.name}:initialized`)}async validate(I){return!0}};var e="trackswap-0.2.0-health-ir-v1",LI=new Set(["timestampCorrelationMesgs","monitoringInfoMesgs","monitoringMesgs","monitoringHrDataMesgs","stressLevelMesgs","respirationRateMesgs","spo2DataMesgs","hrvStatusSummaryMesgs","hrvValueMesgs","sleepLevelMesgs","sleepAssessmentMesgs","napEventMesgs","hsaBodyBatteryDataMesgs","skinTempOvernightMesgs"]),jI=new Set([...LI].filter(n=>n!=="timestampCorrelationMesgs")),yI=new Set(["fileIdMesgs","fileCreatorMesgs","deviceInfoMesgs","deviceSettingsMesgs","softwareMesgs","ohrSettingsMesgs","eventMesgs","activityMesgs","sessionMesgs","lapMesgs","recordMesgs","lengthMesgs","courseMesgs","coursePointMesgs","workoutMesgs","workoutStepMesgs","trainingFileMesgs"]),ZI=[{field:"steps",metric:"steps",unit:"count",rolloverModulus:2**32,rolloverBits:32},{field:"distance",metric:"distance_m",unit:"m",rolloverModulus:2**32/100,rolloverBits:32},{field:"activeTime",metric:"active_time_s",unit:"s",rolloverModulus:2**32/1e3,rolloverBits:32},{field:"activeCalories",metric:"active_energy_kcal",unit:"kcal",rolloverModulus:2**16,rolloverBits:16},{field:"calories",metric:"total_energy_kcal",unit:"kcal",rolloverModulus:2**16,rolloverBits:16},{field:"ascent",metric:"ascent_m",unit:"m",rolloverModulus:2**32/1e3,rolloverBits:32},{field:"descent",metric:"descent_m",unit:"m",rolloverModulus:2**32/1e3,rolloverBits:32}];function X(n){return n&&typeof n=="object"?n:{}}function P(n){let I=typeof n=="number"?n:Number(n);return Number.isFinite(I)?I:void 0}function w(n){if(n instanceof Date&&Number.isFinite(n.valueOf()))return n;if(n==null||n==="")return;let I=new Date(n);return Number.isFinite(I.valueOf())?I:void 0}function RI(n){return w(n)?.toISOString().replace(/Z$/,"")}function K(n,I,_){return{messageName:n,messageIndex:I,fieldName:_}}function nI(n,I){return Object.fromEntries(I.map(_=>[_,n[_]]).filter(([,_])=>["number","string","boolean"].includes(typeof _)))}function gI(n){return Object.fromEntries(Object.entries(n).filter(([,I])=>Array.isArray(I)&&I.length>0).map(([I,_])=>[I,_?.length??0]))}function lI(n){let I=[];return((n.activityMesgs?.length??0)>0||(n.sessionMesgs?.length??0)>0)&&I.push("activity"),[...jI].some(_=>(n[_]?.length??0)>0)&&I.push("health"),((n.workoutMesgs?.length??0)>0||(n.workoutStepMesgs?.length??0)>0)&&I.push("workout"),(n.courseMesgs?.length??0)>0&&I.push("course"),I.length===0&&((n.deviceInfoMesgs?.length??0)>0||(n.fileIdMesgs?.length??0)>0)&&I.push("device"),I.length>0?I:["unknown"]}function qI(n){let I=String(n??"").trim().toLowerCase().replace(/[_\s-]+/g,"");return I.includes("awake")?"awake":I.includes("deep")?"deep":I.includes("light")?"light":I.includes("rem")?"rem":I.includes("unmeasurable")?"unmeasurable":I.includes("sleep")?"sleeping":`vendor:${I||"unknown"}`}function FI(n,I=0){return new Date(n.valueOf()+I*1e3).toISOString().slice(0,10)}function uI(n){return(n.timestampCorrelationMesgs??[]).map(I=>{let _=X(I),t=w(_.timestamp),A=w(_.localTimestamp);return!t||!A?null:{at:t,offsetSeconds:Math.round((A.valueOf()-t.valueOf())/1e3)}}).filter(I=>I!==null).sort((I,_)=>I.at.valueOf()-_.at.valueOf())}function m(n,I){let _;for(let t of n){if(t.at>I)break;_=t.offsetSeconds}return _}function GI(n,I){if(I!==void 0)return new Date(n.valueOf()+I*1e3).toISOString().replace(/Z$/,"")}function iI(n,I,_,t){return I>=n?{value:I-n}:n>=_*.75&&n<_&&I>=0&&I<=_*.25?{value:_-n+I,rolloverBits:t}:null}function rI(n){return n===-100?"off_wrist":n===-200?"motion":n===-300?"invalid":n>=0?"valid":"unknown"}function WI(n,I={},_={}){let t=gI(n),A=Object.fromEntries(Object.entries(t).filter(([H])=>LI.has(H))),T=Object.fromEntries(Object.entries(t).filter(([H])=>!LI.has(H)&&!yI.has(H))),R={sdkProfileVersion:_.sdkProfileVersion,parserVersion:e,messageCounts:t,recognizedMessageCounts:A,unknownMessageCounts:T,invalidValueCounts:{},warnings:[]};I.includeUnknownMessages&&(R.unknownMessages=Object.fromEntries(Object.keys(T).map(H=>[H,n[H]??[]])));let L=[],O=[],D=[],d=[],U=[],W=uI(n),l=H=>{let f=H.offsetSeconds??m(W,H.timestamp);if(H.offsetSeconds=f,H.localTimestamp??=GI(H.timestamp,f),L.push(H),U.push(H.timestamp),H.status!=="valid"){let o=`${H.metric}:${H.status}`;R.invalidValueCounts[o]=(R.invalidValueCounts[o]??0)+1}},M=new Map;(n.monitoringMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp);if(!C){R.warnings.push({code:"GARMIN_HEALTH_NO_TIMESTAMP",message:"Monitoring message has no valid timestamp",source:K("monitoringMesgs",f)});return}U.push(C);let F=P(o.heartRate);F!==void 0&&l({metric:"heart_rate_bpm",timestamp:C,localTimestamp:RI(o.localTimestamp),value:F,unit:"bpm",status:"valid",aggregation:"instant",source:K("monitoringMesgs",f,"heartRate")});let G=P(o.temperature);G!==void 0&&l({metric:"temperature_c",timestamp:C,localTimestamp:RI(o.localTimestamp),value:G,unit:"degC",status:"valid",aggregation:"mean",source:K("monitoringMesgs",f,"temperature")});for(let g of ZI){let B=P(o[g.field]);if(B===void 0)continue;let b=[o.deviceIndex??"device",o.activityType??"activity",g.field].join(":"),p=M.get(b);if(p&&C>p.timestamp){let Q=iI(p.value,B,g.rolloverModulus,g.rolloverBits);if(Q){Q.rolloverBits&&R.warnings.push({code:"GARMIN_HEALTH_ACCUMULATOR_ROLLOVER",message:`${g.field} accumulator rolled over at ${Q.rolloverBits} bits`,source:K("monitoringMesgs",f,g.field)});let J=m(W,p.timestamp);O.push({metric:g.metric,startTime:p.timestamp,endTime:C,localStartTime:GI(p.timestamp,J),offsetSeconds:J,value:Q.value,unit:g.unit,status:"valid",activityType:o.activityType===void 0?void 0:String(o.activityType),intensity:o.activityLevel===void 0?void 0:String(o.activityLevel),source:K("monitoringMesgs",f,g.field),attributes:I.health?.retainCumulativeValues===!1?void 0:{rawCumulativeValue:B}})}else R.warnings.push({code:"GARMIN_HEALTH_ACCUMULATOR_RESET",message:`${g.field} accumulator decreased; a new accumulation window was started`,source:K("monitoringMesgs",f,g.field)})}M.set(b,{timestamp:C,value:B})}}),(n.monitoringHrDataMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp);if(!C)return;[{field:"currentDayRestingHeartRate",metric:"resting_heart_rate_bpm"},{field:"restingHeartRate",metric:"resting_heart_rate_7_day_bpm"}].forEach(({field:G,metric:g})=>{let B=P(o[G]);B!==void 0&&l({metric:g,timestamp:C,value:B,unit:"bpm",status:"valid",aggregation:"latest",source:K("monitoringHrDataMesgs",f,G)})})}),(n.stressLevelMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.stressLevelTime),F=P(o.stressLevelValue);!C||F===void 0||l({metric:"stress_level",timestamp:C,value:F>=1&&F<=100?F:void 0,unit:"score",status:F>=1&&F<=100?"valid":"invalid",aggregation:"instant",source:K("stressLevelMesgs",f,"stressLevelValue"),attributes:{rawValue:F}})}),(n.respirationRateMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp),F=P(o.respirationRate);if(!C||F===void 0)return;let G=rI(F);l({metric:"respiration_rate_bpm",timestamp:C,value:G==="valid"?F:void 0,unit:"breaths/min",status:G,aggregation:"instant",source:K("respirationRateMesgs",f,"respirationRate"),attributes:G==="valid"?void 0:{rawValue:F}})}),(n.spo2DataMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp),F=P(o.readingSpo2);if(!C||F===void 0)return;let G=P(o.readingConfidence);l({metric:"spo2_percent",timestamp:C,value:F,unit:"percent",status:G!==void 0&&G<=0?"low_confidence":"valid",quality:G,aggregation:"instant",source:K("spo2DataMesgs",f,"readingSpo2"),attributes:{measurementMode:o.mode===void 0?null:String(o.mode)}})}),(n.hrvValueMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp),F=P(o.value);!C||F===void 0||l({metric:"hrv_rmssd_ms",timestamp:C,value:F,unit:"ms",status:"valid",aggregation:"mean",source:K("hrvValueMesgs",f,"value"),attributes:{windowSeconds:300}})}),(n.hrvStatusSummaryMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp);D.push({summaryType:"hrv_status",externalId:`fit:hrv-status:${C?.toISOString()??f}`,startTime:C,metrics:nI(o,["weeklyAverage","lastNightAverage","lastNight5MinHigh","baselineLowUpper","baselineBalancedLower","baselineBalancedUpper","status"]),source:K("hrvStatusSummaryMesgs",f)}),C&&U.push(C)}),(n.monitoringInfoMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp);D.push({summaryType:"device",externalId:`fit:monitoring-info:${C?.toISOString()??f}`,startTime:C,offsetSeconds:C?m(W,C):void 0,metrics:nI(o,["restingMetabolicRate","activityType","cyclesToDistance","cyclesToCalories"]),source:K("monitoringInfoMesgs",f)}),C&&U.push(C)}),(n.skinTempOvernightMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp);if(!C)return;[{field:"averageDeviation",metric:"skin_temperature_deviation_c"},{field:"average7DayDeviation",metric:"skin_temperature_7_day_deviation_c"},{field:"nightlyValue",metric:"skin_temperature_nightly_c"}].forEach(({field:G,metric:g})=>{let B=P(o[G]);B!==void 0&&l({metric:g,timestamp:C,localTimestamp:RI(o.localTimestamp),value:B,unit:"degC",status:"valid",aggregation:"mean",source:K("skinTempOvernightMesgs",f,G)})})});let V=(n.sleepLevelMesgs??[]).map((H,f)=>({message:X(H),messageIndex:f,timestamp:w(X(H).timestamp)})).filter(H=>H.timestamp!==void 0).sort((H,f)=>H.timestamp.valueOf()-f.timestamp.valueOf());if(V.length>=2){let H=X(n.sleepAssessmentMesgs?.[0]),f=[];for(let G=0;G<V.length-1;G+=1){let g=V[G],B=V[G+1];if(B.timestamp<=g.timestamp)continue;let b={segmentType:qI(g.message.sleepLevel),startTime:g.timestamp,endTime:B.timestamp,status:"valid",source:K("sleepLevelMesgs",g.messageIndex,"sleepLevel")},p=f.at(-1);p&&p.segmentType===b.segmentType&&p.endTime.valueOf()===b.startTime.valueOf()?p.endTime=b.endTime:f.push(b)}let o=V[0].timestamp,C=V.at(-1).timestamp;U.push(o,C);let F=m(W,C);d.push({sessionType:"sleep",externalId:`fit:sleep:${o.toISOString()}:${C.toISOString()}`,startTime:o,endTime:C,startOffsetSeconds:m(W,o),endOffsetSeconds:F,calendarDate:FI(C,F),segments:f,metrics:nI(H,["combinedAwakeScore","awakeTimeScore","awakeningsCountScore","deepSleepScore","sleepDurationScore","lightSleepScore","overallSleepScore","sleepQualityScore","sleepRecoveryScore","remSleepScore","sleepRestlessnessScore","awakeningsCount","interruptionsScore","averageStressDuringSleep"]),source:K("sleepLevelMesgs",V[0].messageIndex),attributes:{calendarDateStrategy:F===void 0?"sleep_end_utc_fallback_date":"sleep_end_local_date"}})}else V.length>0&&R.warnings.push({code:"GARMIN_HEALTH_SLEEP_BOUNDARY_INCOMPLETE",message:"Sleep level data does not contain enough boundaries",source:K("sleepLevelMesgs",V[0].messageIndex)});return(n.napEventMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.startTime),F=w(o.endTime),G=o.isDeleted===!0;if(!C||!F||F<C||!G&&F.valueOf()===C.valueOf())return;let g=P(o.startTimezoneOffset),B=P(o.endTimezoneOffset);U.push(C,F),d.push({sessionType:"nap",externalId:`fit:nap:${o.messageIndex??f}:${C.toISOString()}`,startTime:C,endTime:F,startOffsetSeconds:g,endOffsetSeconds:B,calendarDate:FI(F,B??g),deleted:G,segments:[],metrics:{},source:K("napEventMesgs",f),attributes:{source:o.source===void 0?null:String(o.source),feedback:o.feedback===void 0?null:String(o.feedback),updateTimestamp:w(o.updateTimestamp)?.toISOString()??null}})}),(n.hsaBodyBatteryDataMesgs??[]).forEach((H,f)=>{let o=X(H),C=w(o.timestamp),F=P(o.processingInterval)??0;if(!C||F<=0)return;[{field:"level",metric:"body_battery_level",unit:"score"},{field:"charged",metric:"body_battery_charged",unit:"score"},{field:"uncharged",metric:"body_battery_drained",unit:"score"}].forEach(({field:g,metric:B,unit:b})=>{(Array.isArray(o[g])?o[g]:[]).forEach((Q,J)=>{let y=P(Q);y!==void 0&&l({metric:B,timestamp:new Date(C.valueOf()+F*J*1e3),value:y===-16?void 0:y,unit:b,status:y===-16?"invalid":"valid",aggregation:"instant",source:K("hsaBodyBatteryDataMesgs",f,g),attributes:{sequenceIndex:J,intervalSeconds:F}})})})}),L.sort((H,f)=>H.timestamp.valueOf()-f.timestamp.valueOf()),O.sort((H,f)=>H.startTime.valueOf()-f.startTime.valueOf()),d.sort((H,f)=>H.startTime.valueOf()-f.startTime.valueOf()),U.sort((H,f)=>H.valueOf()-f.valueOf()),{schemaVersion:"1",observedStart:U[0],observedEnd:U.at(-1),timezone:{strategy:W.length>0?"timestamp_correlation":"unknown",offsets:W},points:L,intervals:I.health?.reconstructIntervals===!1?[]:O,summaries:D,sessions:d,diagnostics:R}}var a=class extends k{constructor(){super(...arguments);this.name="HealthStructurePlugin";this.priority=20}structureData(_,t){let A=t.userData?.fitDocumentOptions??{},T=lI(_);return{healthDocument:T.includes("health")?WI(_,A,{sdkProfileVersion:t.metadata.get("fit-sdk-profile-version")}):void 0,fitDocumentMetadata:{detectedKinds:T,messageCounts:gI(_)}}}};var __=(S=>(S[S.GENERIC=0]="GENERIC",S[S.RUNNING=1]="RUNNING",S[S.CYCLING=2]="CYCLING",S[S.TRANSITION=3]="TRANSITION",S[S.FITNESS_EQUIPMENT=4]="FITNESS_EQUIPMENT",S[S.SWIMMING=5]="SWIMMING",S[S.BASKETBALL=6]="BASKETBALL",S[S.SOCCER=7]="SOCCER",S[S.TENNIS=8]="TENNIS",S[S.AMERICAN_FOOTBALL=9]="AMERICAN_FOOTBALL",S[S.TRAINING=10]="TRAINING",S[S.WALKING=11]="WALKING",S[S.CROSS_COUNTRY_SKIING=12]="CROSS_COUNTRY_SKIING",S[S.ALPINE_SKIING=13]="ALPINE_SKIING",S[S.SNOWBOARDING=14]="SNOWBOARDING",S[S.ROWING=15]="ROWING",S[S.MOUNTAINEERING=16]="MOUNTAINEERING",S[S.HIKING=17]="HIKING",S[S.MULTISPORT=18]="MULTISPORT",S[S.PADDLING=19]="PADDLING",S[S.FLYING=20]="FLYING",S[S.E_BIKING=21]="E_BIKING",S[S.MOTORCYCLING=22]="MOTORCYCLING",S[S.BOATING=23]="BOATING",S[S.DRIVING=24]="DRIVING",S[S.GOLF=25]="GOLF",S[S.HANG_GLIDING=26]="HANG_GLIDING",S[S.HORSEBACK_RIDING=27]="HORSEBACK_RIDING",S[S.HUNTING=28]="HUNTING",S[S.FISHING=29]="FISHING",S[S.INLINE_SKATING=30]="INLINE_SKATING",S[S.ROCK_CLIMBING=31]="ROCK_CLIMBING",S[S.SAILING=32]="SAILING",S[S.ICE_SKATING=33]="ICE_SKATING",S[S.SKY_DIVING=34]="SKY_DIVING",S[S.SNOWSHOEING=35]="SNOWSHOEING",S[S.SNOWMOBILING=36]="SNOWMOBILING",S[S.STAND_UP_PADDLEBOARDING=37]="STAND_UP_PADDLEBOARDING",S[S.SURFING=38]="SURFING",S[S.WAKEBOARDING=39]="WAKEBOARDING",S[S.WATER_SKIING=40]="WATER_SKIING",S[S.KAYAKING=41]="KAYAKING",S[S.RAFTING=42]="RAFTING",S[S.WINDSURFING=43]="WINDSURFING",S[S.KITESURFING=44]="KITESURFING",S[S.TACTICAL=45]="TACTICAL",S[S.JUMPMASTER=46]="JUMPMASTER",S[S.BOXING=47]="BOXING",S[S.FLOOR_CLIMBING=48]="FLOOR_CLIMBING",S[S.BASEBALL=49]="BASEBALL",S[S.DIVING=53]="DIVING",S[S.HIIT=62]="HIIT",S[S.RACKET=64]="RACKET",S[S.WHEELCHAIR_PUSH_WALK=65]="WHEELCHAIR_PUSH_WALK",S[S.WHEELCHAIR_PUSH_RUN=66]="WHEELCHAIR_PUSH_RUN",S[S.MEDITATION=67]="MEDITATION",S[S.DISC_GOLF=69]="DISC_GOLF",S[S.CRICKET=71]="CRICKET",S[S.RUGBY=72]="RUGBY",S[S.HOCKEY=73]="HOCKEY",S[S.LACROSSE=74]="LACROSSE",S[S.VOLLEYBALL=75]="VOLLEYBALL",S[S.WATER_TUBING=76]="WATER_TUBING",S[S.WAKESURFING=77]="WAKESURFING",S[S.MIXED_MARTIAL_ARTS=80]="MIXED_MARTIAL_ARTS",S[S.SNORKELING=82]="SNORKELING",S[S.DANCE=83]="DANCE",S[S.JUMP_ROPE=84]="JUMP_ROPE",S[S.ALL=254]="ALL",S))(__||{});var I_=(E=>(E[E.GENERIC=0]="GENERIC",E[E.TREADMILL=1]="TREADMILL",E[E.STREET=2]="STREET",E[E.TRAIL=3]="TRAIL",E[E.TRACK=4]="TRACK",E[E.SPIN=5]="SPIN",E[E.INDOOR_CYCLING=6]="INDOOR_CYCLING",E[E.ROAD=7]="ROAD",E[E.MOUNTAIN=8]="MOUNTAIN",E[E.DOWNHILL=9]="DOWNHILL",E[E.RECUMBENT=10]="RECUMBENT",E[E.CYCLOCROSS=11]="CYCLOCROSS",E[E.HAND_CYCLING=12]="HAND_CYCLING",E[E.TRACK_CYCLING=13]="TRACK_CYCLING",E[E.INDOOR_ROWING=14]="INDOOR_ROWING",E[E.ELLIPTICAL=15]="ELLIPTICAL",E[E.STAIR_CLIMBING=16]="STAIR_CLIMBING",E[E.LAP_SWIMMING=17]="LAP_SWIMMING",E[E.OPEN_WATER=18]="OPEN_WATER",E[E.FLEXIBILITY_TRAINING=19]="FLEXIBILITY_TRAINING",E[E.STRENGTH_TRAINING=20]="STRENGTH_TRAINING",E[E.WARM_UP=21]="WARM_UP",E[E.MATCH=22]="MATCH",E[E.EXERCISE=23]="EXERCISE",E[E.CHALLENGE=24]="CHALLENGE",E[E.INDOOR_SKIING=25]="INDOOR_SKIING",E[E.CARDIO_TRAINING=26]="CARDIO_TRAINING",E[E.INDOOR_WALKING=27]="INDOOR_WALKING",E[E.E_BIKE_FITNESS=28]="E_BIKE_FITNESS",E[E.BMX=29]="BMX",E[E.CASUAL_WALKING=30]="CASUAL_WALKING",E[E.SPEED_WALKING=31]="SPEED_WALKING",E[E.BIKE_TO_RUN_TRANSITION=32]="BIKE_TO_RUN_TRANSITION",E[E.RUN_TO_BIKE_TRANSITION=33]="RUN_TO_BIKE_TRANSITION",E[E.SWIM_TO_BIKE_TRANSITION=34]="SWIM_TO_BIKE_TRANSITION",E[E.ATV=35]="ATV",E[E.MOTOCROSS=36]="MOTOCROSS",E[E.BACKCOUNTRY=37]="BACKCOUNTRY",E[E.RESORT=38]="RESORT",E[E.RC_DRONE=39]="RC_DRONE",E[E.WINGSUIT=40]="WINGSUIT",E[E.WHITEWATER=41]="WHITEWATER",E[E.SKATE_SKIING=42]="SKATE_SKIING",E[E.YOGA=43]="YOGA",E[E.PILATES=44]="PILATES",E[E.INDOOR_RUNNING=45]="INDOOR_RUNNING",E[E.GRAVEL_CYCLING=46]="GRAVEL_CYCLING",E[E.E_BIKE_MOUNTAIN=47]="E_BIKE_MOUNTAIN",E[E.COMMUTING=48]="COMMUTING",E[E.MIXED_SURFACE=49]="MIXED_SURFACE",E[E.NAVIGATE=50]="NAVIGATE",E[E.TRACK_ME=51]="TRACK_ME",E[E.MAP=52]="MAP",E[E.SINGLE_GAS_DIVING=53]="SINGLE_GAS_DIVING",E[E.MULTI_GAS_DIVING=54]="MULTI_GAS_DIVING",E[E.GAUGE_DIVING=55]="GAUGE_DIVING",E[E.APNEA_DIVING=56]="APNEA_DIVING",E[E.APNEA_HUNTING=57]="APNEA_HUNTING",E[E.VIRTUAL_ACTIVITY=58]="VIRTUAL_ACTIVITY",E[E.OBSTACLE=59]="OBSTACLE",E[E.BREATHING=62]="BREATHING",E[E.SAIL_RACE=65]="SAIL_RACE",E[E.ULTRA=67]="ULTRA",E[E.INDOOR_CLIMBING=68]="INDOOR_CLIMBING",E[E.BOULDERING=69]="BOULDERING",E[E.HIIT=70]="HIIT",E[E.AMRAP=73]="AMRAP",E[E.EMOM=74]="EMOM",E[E.TABATA=75]="TABATA",E[E.PICKLEBALL=84]="PICKLEBALL",E[E.PADEL=85]="PADEL",E[E.INDOOR_WHEELCHAIR_WALK=86]="INDOOR_WHEELCHAIR_WALK",E[E.INDOOR_WHEELCHAIR_RUN=87]="INDOOR_WHEELCHAIR_RUN",E[E.INDOOR_HAND_CYCLING=88]="INDOOR_HAND_CYCLING",E[E.SQUASH=94]="SQUASH",E[E.BADMINTON=95]="BADMINTON",E[E.RACQUETBALL=96]="RACQUETBALL",E[E.TABLE_TENNIS=97]="TABLE_TENNIS",E[E.FLY_CANOPY=110]="FLY_CANOPY",E[E.FLY_PARAGLIDE=111]="FLY_PARAGLIDE",E[E.FLY_PARAMOTOR=112]="FLY_PARAMOTOR",E[E.FLY_PRESSURIZED=113]="FLY_PRESSURIZED",E[E.FLY_NAVIGATE=114]="FLY_NAVIGATE",E[E.FLY_TIMER=115]="FLY_TIMER",E[E.FLY_ALTIMETER=116]="FLY_ALTIMETER",E[E.FLY_WX=117]="FLY_WX",E[E.FLY_VFR=118]="FLY_VFR",E[E.FLY_IFR=119]="FLY_IFR",E[E.ALL=254]="ALL",E))(I_||{});function BI(n,I){if(!I)return;let _=I.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase();for(let t of Object.keys(n)){if(!Number.isNaN(Number(t))||t.toUpperCase()!==_)continue;let A=n[t];return typeof A=="number"?A:void 0}}function mI(n){let I=n.metadata?.fileName?.trim();if(I)return I;let _=n.metadata?.originType;return _?`${_.toLowerCase()}-course`:"course"}function MI(n){let I=n.activities?.[0],t=[...(n.activities?.flatMap(A=>A.laps??[])??[]).flatMap(A=>A.records??[]),...n.routes?.flatMap(A=>A.records??[])??[],...n.points??[]].filter(A=>A.timestamp!=null&&A.positionLat!=null&&A.positionLong!=null).sort((A,T)=>new Date(A.timestamp).getTime()-new Date(T.timestamp).getTime()).map(A=>({timestamp:A.timestamp,latitude:A.positionLat,longitude:A.positionLong,distance:A.distance,altitude:A.enhancedAltitude??A.altitude,speed:A.enhancedSpeed??A.speed}));if(t.length===0)throw new Error("Cannot build a FIT course without timestamped coordinates");return{name:mI(n),sport:BI(__,I?.sport)??2,subSport:BI(I_,I?.subSport)??0,records:t,timeCreated:t[0].timestamp}}function VI(){return process.env.TRACKSWAP_FIT_DEBUG==="1"||process.env.TRACKSWAP_DEBUG==="1"}function h(...n){VI()}function u(...n){VI()}var t_=class{constructor(){this.stage="parse"}async process(I){let _=Date.now();if(!I.rawData)throw new Error("FIT data cannot be empty");try{let t=await this.parseWithFitSDK(I.rawData,I);return I.rawMessages=t,h("\u{1F389} FIT parsing raw messages:",t),I.performance.parseTime=Date.now()-_,h(`\u{1F527} FIT parsing completed, contains message types: ${Object.keys(t).join(", ")}`),I}catch(t){throw new Error(`FIT parsing failed: ${t.message}`)}}async parseWithFitSDK(I,_){let{Decoder:t,Profile:A,Stream:T}=await import("@garmin/fitsdk"),R=[A.version?.major,A.version?.minor,A.version?.patch].filter(U=>U!==void 0);R.length>0&&_.metadata.set("fit-sdk-profile-version",R.join("."));let L=T.fromBuffer(I);if(!t.isFIT(L))throw new Error("Not a valid FIT file");let O=new t(L),{messages:D,errors:d}=O.read();return d&&d.length>0&&u("FIT parsing warnings:",d),D}};function cI(n){let I={...n};return I.position_lat!=null&&I.positionLat==null&&(I.positionLat=I.position_lat),I.position_long!=null&&I.positionLong==null&&(I.positionLong=I.position_long),I}var A_=class{constructor(I){this.getConverters=I;this.stage="extract"}async process(I){let _=Date.now();if(!I.rawMessages)throw new Error("Raw messages cannot be empty");let t={};for(let[A,T]of Object.entries(I.rawMessages)){if(!Array.isArray(T)||T.length===0){t[A]=T;continue}let R=this.getConverters(A);if(R.length===0)t[A]=A==="recordMesgs"?T.map(L=>cI(L)):T,h(`\u{1F4CB} Message type "${A}" has no converter, using raw data`);else{let L=R[0];try{let O=L.convertMessages(T,I);t[A]=O,h(`\u2705 Message type "${A}" using converter ${L.name}`)}catch(O){I.errors.push(O),t[A]=T,u(`FIT converter "${L.name}" failed for ${A}; raw messages were retained`,O)}}}return I.rawMessages=t,I.performance.extractTime=Date.now()-_,I}},T_=class{constructor(I){this.getStructurePlugins=I;this.stage="structure"}async process(I){let _=Date.now();if(!I.rawMessages)throw new Error("Message data cannot be empty");let t={},A=this.getStructurePlugins();for(let T of A)try{let R=T.structureData(I.rawMessages,I);t={...t,...R},h(`\u{1F527} Structure plugin ${T.name} processing completed`)}catch(R){throw I.errors.push(R),new Error(`FIT structure plugin "${T.name}" failed: ${R.message}`)}return I.result=t,I.performance.structureTime=Date.now()-_,I}},R_=class{constructor(){this.stage="complete"}async process(I){I.performance.endTime=Date.now();let _=I.performance.endTime-I.performance.startTime;return I.metadata.set("performance",{totalTime:_,parseTime:I.performance.parseTime,extractTime:I.performance.extractTime,structureTime:I.performance.structureTime}),I.stats&&(I.stats.endTime=Date.now(),I.rawMessages&&(I.stats.processedTokens=this.countTotalMessages(I.rawMessages))),h(`\u2705 FIT processing completed, total time: ${_}ms`),I}countTotalMessages(I){let _=0;return Object.values(I).forEach(t=>{Array.isArray(t)&&(_+=t.length)}),_}};import Y from"dayjs";var n_=class extends k{constructor(){super(...arguments);this.name="SessionStructurePlugin";this.priority=10}structureData(_,t){let{sessionMesgs:A,lapMesgs:T,recordMesgs:R,lengthMesgs:L}=_;if(!A?.length)return u("No structured session found, data structure is incomplete"),{};let O=A.map(U=>{let W=Y(U.startTime).valueOf(),l=W+(U.totalElapsedTime??0)*1e3,M=Y(U.timestamp).valueOf(),V=Math.max(Number.isFinite(l)?l:Number.NEGATIVE_INFINITY,Number.isFinite(M)?M:Number.NEGATIVE_INFINITY),H=U.firstLapIndex,f=U.numLaps,o=typeof H=="number"&&typeof f=="number"?(T??[]).filter(G=>{let g=G.messageIndex;return typeof g=="number"&&g>=H&&g<H+f}):[],C=(o.length>0?o:(T??[]).filter(G=>{let g=Y(G.startTime).valueOf();return Number.isFinite(g)&&g>=W&&g<=V+2e3})).sort((G,g)=>Y(G.startTime).valueOf()-Y(g.startTime).valueOf()),F=C.map((G,g)=>{let B=Y(G.startTime).valueOf(),b=C[g+1]?.startTime,p=b==null?Number.NaN:Y(b).valueOf(),Q=B+(G.totalElapsedTime??0)*1e3,J=Number.isFinite(p)&&p>B,y=J?p:Math.max(Q,V),zI=R?.filter(TI=>{let q=Y(TI.timestamp).valueOf();return q>=B&&(J?q<y:q<=y)})||[],AI=G.firstLengthIndex??void 0,fI=G.numLengths??void 0,dI=[];if(AI!==void 0&&fI!==void 0){let TI=AI+fI;dI=L?.filter(q=>q.messageIndex>=AI&&q.messageIndex<TI)||[]}return{...G,recordMesgs:zI,lengthMesgs:dI,messageIndex:G.messageIndex!==void 0?G.messageIndex:0}});return{...U,lapMesgs:F,messageIndex:U.messageIndex!==void 0?U.messageIndex:0}}),D=new Set;for(let U of O)for(let W of U.lapMesgs??[])for(let l of W.recordMesgs??[])l?.timestamp!=null&&D.add(Y(l.timestamp).valueOf());let d=0;for(let U of R??[]){if(U?.timestamp==null)continue;let W=Y(U.timestamp).valueOf();D.has(W)||d++}return d>0&&(t.metadata.set("fit-unassigned-record-count",d),u(`SessionStructurePlugin: ${d} record(s) did not fall into any lap time window`)),{sessionMesgs:O}}},L_=class extends k{constructor(){super(...arguments);this.name="CourseStructurePlugin";this.priority=10}structureData(_,t){let{courseMesgs:A,lapMesgs:T,recordMesgs:R}=_;if(!A?.length)return{};let L=2e3;return{courseMesgs:A.map(D=>{let d=T?.map(U=>{let W=Y(U.startTime).valueOf(),l=Y(U.timestamp).valueOf(),M=R?.filter(V=>{let H=Y(V.timestamp).valueOf();return H>=W-L&&H<=l+L})||[];return{...U,recordMesgs:M}})||[];return{...D,lapMesgs:d}})}}},E_=class extends k{constructor(){super(...arguments);this.name="FileHeaderPlugin";this.priority=1}structureData(_,t){let{fileIdMesgs:A,fileCreatorMesgs:T,deviceInfoMesgs:R}=_;if(A?.length&&A[0]){let L=A[0];t.fileHeader={type:L.type,manufacturer:L.manufacturer,product:L.product}}return{fileIdMesgs:A,fileCreatorMesgs:T,deviceInfoMesgs:R}}};var O_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.structurePlugins=[];this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultPluginsRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new t_,new A_(I=>this.getConverters(I)),new T_(()=>this.structurePlugins),new R_],h("\u{1F527} FIT core pipeline processors initialized (fixed and not modifiable)")}async registerDefaultPlugins(){if(this.defaultPluginsRegistered)return;let I=[new E_,new n_,new L_,new a];for(let _ of I)this.addStructurePlugin(_),this.registeredPlugins.add(_.name);this.defaultPluginsRegistered=!0,h("\u2705 Default FIT structure plugins auto-registered (FileHeader, Session, Course, etc.)")}addConverterForMessageType(I,_){this.converterPlugins.has(I)||this.converterPlugins.set(I,[]);let t=this.converterPlugins.get(I);t.push(_),t.sort((A,T)=>(A.priority||100)-(T.priority||100))}addStructurePlugin(I){this.structurePlugins.push(I),this.structurePlugins.sort((_,t)=>(_.priority||100)-(t.priority||100))}async registerMessageConverter(I){if(this.registeredPlugins.has(I.name))throw new Error(`Message converter plugin ${I.name} already exists`);I.supportedMessageTypes.forEach(t=>{this.addConverterForMessageType(t,I)}),this.registeredPlugins.add(I.name);let _=I.priority!==void 0?` (priority: ${I.priority})`:"";h(`\u{1F4E6} Registered FIT message converter: ${I.name}${_}, supported message types: ${I.supportedMessageTypes.join(", ")}`),I.supportedMessageTypes.forEach(t=>{let T=(this.converterPlugins.get(t)||[]).map(R=>`${R.name}(${R.priority||100})`);h(` \u{1F4CB} Message type "${t}" converter priority: ${T.join(" > ")}`)})}async registerStructurePlugin(I){if(this.registeredPlugins.has(I.name))throw new Error(`Structure plugin ${I.name} already exists`);this.addStructurePlugin(I),this.registeredPlugins.add(I.name);let _=I.priority!==void 0?` (priority: ${I.priority})`:"";h(`\u{1F3D7}\uFE0F Registered FIT structure plugin: ${I.name}${_}`)}async registerMiddleware(I){let _=this.middlewarePlugins.findIndex(A=>A.name===I.name);_!==-1?(this.middlewarePlugins[_]=I,h(`\u{1F504} Updated FIT middleware: ${I.name}`)):(this.middlewarePlugins.push(I),this.middlewarePlugins.sort((A,T)=>(A.priority||100)-(T.priority||100)),h(`\u{1F50C} Registered FIT middleware: ${I.name}`));let t=[];I.onParse&&t.push("onParse"),I.onExtractMessages&&t.push("onExtractMessages"),I.onStructure&&t.push("onStructure"),I.onComplete&&t.push("onComplete"),I.onError&&t.push("onError"),t.length>0&&h(` \u{1F3A3} Supported hooks: ${t.join(", ")}`)}getConverter(I){let _=this.converterPlugins.get(I);return _&&_.length>0?_[0]:void 0}getConverters(I){return this.converterPlugins.get(I)||[]}unregisterPlugin(I){if(!this.registeredPlugins.has(I))return!1;for(let[A,T]of this.converterPlugins){let R=T.findIndex(L=>L.name===I);R!==-1&&(T.splice(R,1),T.length===0&&this.converterPlugins.delete(A))}let _=this.structurePlugins.findIndex(A=>A.name===I);_!==-1&&this.structurePlugins.splice(_,1);let t=this.middlewarePlugins.findIndex(A=>A.name===I);return t!==-1&&this.middlewarePlugins.splice(t,1),this.registeredPlugins.delete(I),h(`\u{1F5D1}\uFE0F Removed FIT plugin: ${I}`),!0}async initialize(){if(this.initialized)return;await this.registerDefaultPlugins();let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.structurePlugins,...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.initialize?.(I);this.initialized=!0}async destroy(){if(!this.initialized)return;let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.structurePlugins,...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.destroy?.(I);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(I,_,t){let A=_;for(let T of this.middlewarePlugins){let R=T[I];if(R)try{A=await R.call(T,A,t)||A}catch(L){t.errors.push(L),await T.onError?.(L,t)}}return A}async parseByBuffer(I,_={}){await this.initialize();let t=this.createContext();t.rawData=I,t.userData=_.userData,t.metadata.set("decoder",this);try{for(let A of this.processors)try{switch(A.stage==="parse"&&t.rawData&&(t.rawData=await this.executeMiddlewareHook("onParse",t.rawData,t)),t=await A.process(t),A.stage){case"parse":break;case"extract":t.rawMessages&&(t.rawMessages=await this.executeMiddlewareHook("onExtractMessages",t.rawMessages,t));break;case"structure":t.result&&(t.result=await this.executeMiddlewareHook("onStructure",t.result,t));break;case"complete":t.result&&(t.result=await this.executeMiddlewareHook("onComplete",t.result,t));break}}catch(T){t.errors.push(T);for(let R of this.middlewarePlugins)await R.onError?.(T,t);throw new Error(`FIT pipeline stage "${A.stage}" failed: ${T.message}`)}return h("\u{1F389} FIT parsing completed",t.result),t.result}catch(A){throw A}}};var xI={file:{course:6,device:1,settings:2,sport:3,activity:4,workout:5,schedules:7,weight:9,totals:10,goals:11,blood_pressure:14,monitoring_a:15,activity_summary:20,monitoring_daily:28,monitoring_b:32,segment_list:35,exd_configuration:40,invalid:0},sport:{generic:0,running:1,cycling:2,transition:3,fitness_equipment:4,swimming:5,basketball:6,soccer:7,tennis:8,american_football:9,training:10,walking:11,cross_country_skiing:12,alpine_skiing:13,snowboarding:14,rowing:15,mountaineering:16,hiking:17,multisport:18,paddling:19,invalid:254},event:{timer:0,workout:3,workout_step:4,power_down:5,power_up:6,off_course:7,session:8,lap:9,course_point:10,battery:11,virtual_partner_pace:12,hr_high_alert:13,hr_low_alert:14,speed_high_alert:15,speed_low_alert:16,cad_high_alert:17,cad_low_alert:18,power_high_alert:19,power_low_alert:20,recovery_hr:21,battery_low:22,time_duration_alert:23,distance_duration_alert:24,calorie_duration_alert:25,activity:26,fitness_equipment:27,length:28,user_marker:32,sport_point:33,calibration:36,front_gear_change:42,rear_gear_change:43,rider_position_change:44,elev_high_alert:45,elev_low_alert:46,comm_timeout:47,invalid:255},event_type:{start:0,stop:1,consecutive_depreciated:2,marker:3,stop_all:4,begin_depreciated:5,end_depreciated:6,end_all_depreciated:7,stop_disable:8,stop_disable_all:9,invalid:255},course_point:{generic:0,summit:1,valley:2,water:3,food:4,danger:5,left:6,right:7,straight:8,first_aid:9,fourth_category:10,third_category:11,second_category:12,first_category:13,hors_category:14,sprint:15,left_fork:16,right_fork:17,middle_fork:18,slight_left:19,sharp_left:20,slight_right:21,sharp_right:22,u_turn:23,segment_start:24,segment_end:25,invalid:255}},Z=n=>{let I=xI[n];return{size:1,baseType:0,mapValue:_=>typeof _=="string"?I[_]??255:_,setValue:function(_,t){this.setUint8(_,t)}}},EI={enum_file:Z("file"),enum_activity:Z("sport"),enum_sport:Z("sport"),enum_sub_sport:Z("sport"),enum_event:Z("event"),enum_event_type:Z("event_type"),enum_course_point:Z("course_point"),uint8:{size:1,baseType:2,setValue:DataView.prototype.setUint8},sint8:{size:1,baseType:1,setValue:DataView.prototype.setInt8},uint16:{size:2,baseType:132,setValue:DataView.prototype.setUint16},sint16:{size:2,baseType:131,setValue:DataView.prototype.setInt16},uint32:{size:4,baseType:134,setValue:DataView.prototype.setUint32},sint32:{size:4,baseType:133,setValue:DataView.prototype.setInt32},string:{size:0,baseType:7,mapValue:n=>Array.from(hI(n)),setValue:eI},distance:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:n=>Math.round(n*1e3)},speed:{size:2,baseType:132,setValue:DataView.prototype.setUint16,mapValue:n=>Math.round(n*100)},altitude:{size:2,baseType:132,setValue:DataView.prototype.setUint16,mapValue:n=>Math.round((n+500)*5)},seconds:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:n=>Math.round(n*1e3)},date_time:{size:4,baseType:134,setValue:DataView.prototype.setUint32,mapValue:n=>{let I;return n instanceof Date?(I=Math.floor(n.getTime()/1e3),I-631065600):typeof n=="string"?(I=Math.floor(new Date(n).getTime()/1e3),I-631065600):n<631065600?Math.floor(n):(n>9999999999?I=Math.floor(n/1e3):I=Math.floor(n),I-631065600)}},semicircles:{size:4,baseType:133,setValue:DataView.prototype.setInt32,mapValue:n=>Math.round(n/180*2147483648)}};function KI(n){return Array.from(hI(n)).length+1}function*hI(n){for(let I of aI(n))I<128?yield I:I<2048?(yield 192|I>>6,yield 128|I&63):I<65536?(yield 224|I>>12,yield 128|I>>6&63,yield 128|I&63):(yield 240|I>>18,yield 128|I>>12&63,yield 128|I>>6&63,yield 128|I&63);yield 0}function*aI(n){for(let I=0;I<n.length;){let _=n.codePointAt(I);if(_===void 0)break;yield _,I+=_>65535?2:1}}function eI(n,I){for(let _=0;_<I.length;_++)this.setUint8(n+_,I[_])}var It={file_id:{mesgNum:0,fieldDefns:[{name:"type",number:0,type:"enum_file"},{name:"time_created",number:4,type:"date_time"}]},session:{mesgNum:18,fieldDefns:[{name:"message_index",number:254,type:"uint16"},{name:"timestamp",number:253,type:"date_time"},{name:"start_time",number:2,type:"date_time"},{name:"total_elapsed_time",number:7,type:"seconds"},{name:"total_timer_time",number:8,type:"seconds"},{name:"start_position_lat",number:3,type:"semicircles"},{name:"start_position_long",number:4,type:"semicircles"},{name:"total_distance",number:9,type:"distance"},{name:"total_ascent",number:21,type:"uint16"},{name:"total_descent",number:22,type:"uint16"},{name:"sport",number:5,type:"enum_sport"},{name:"sub_sport",number:6,type:"enum_sub_sport"},{name:"first_lap_index",number:25,type:"uint16"},{name:"num_laps",number:26,type:"uint16"}]},lap:{mesgNum:19,fieldDefns:[{name:"message_index",number:254,type:"uint16"},{name:"timestamp",number:253,type:"date_time"},{name:"start_time",number:2,type:"date_time"},{name:"start_position_lat",number:3,type:"semicircles"},{name:"start_position_long",number:4,type:"semicircles"},{name:"end_position_lat",number:5,type:"semicircles"},{name:"end_position_long",number:6,type:"semicircles"},{name:"total_elapsed_time",number:7,type:"seconds"},{name:"total_timer_time",number:8,type:"seconds"},{name:"total_distance",number:9,type:"distance"},{name:"total_ascent",number:21,type:"uint16"},{name:"total_descent",number:22,type:"uint16"}]},record:{mesgNum:20,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"position_lat",number:0,type:"semicircles"},{name:"position_long",number:1,type:"semicircles"},{name:"altitude",number:2,type:"altitude"},{name:"distance",number:5,type:"distance"},{name:"heart_rate",number:3,type:"uint8"},{name:"cadence",number:4,type:"uint8"},{name:"speed",number:6,type:"speed"},{name:"power",number:7,type:"uint16"}]},event:{mesgNum:21,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"event",number:0,type:"enum_event"},{name:"event_type",number:1,type:"enum_event_type"},{name:"event_group",number:4,type:"uint8"}]},course:{mesgNum:31,fieldDefns:[{name:"name",number:5,type:"string"},{name:"sport",number:4,type:"enum_sport"},{name:"sub_sport",number:7,type:"enum_sub_sport"}]},activity:{mesgNum:34,fieldDefns:[{name:"timestamp",number:253,type:"date_time"},{name:"total_timer_time",number:0,type:"seconds"},{name:"num_sessions",number:1,type:"uint16"},{name:"type",number:2,type:"enum_activity"},{name:"event",number:3,type:"enum_event"},{name:"event_type",number:4,type:"enum_event_type"},{name:"local_timestamp",number:5,type:"date_time"},{name:"event_group",number:6,type:"uint8"}]},course_point:{mesgNum:32,fieldDefns:[{name:"timestamp",number:1,type:"date_time"},{name:"position_lat",number:2,type:"semicircles"},{name:"position_long",number:3,type:"semicircles"},{name:"distance",number:4,type:"distance"},{name:"type",number:5,type:"enum_course_point"}]}},tt=(n,I)=>n.map(_=>({..._,value:I[_.name]})).filter(({value:_})=>_!==void 0),S_=class n{static check(I,_,t,A){if(_===void 0)throw new Error(`Message '${I}' not known`);if(t===void 0)throw new Error(`Message '${I}' has no field definitions`);let T=t.map(L=>L.name),R=Object.keys(A).filter(L=>!T.includes(L));if(R.length)throw new Error(`Message '${I}' has no field definitions named '${R}'`)}constructor(I,_,t){let A=It[_];if(!A)throw new Error(`Unknown message type: ${_}`);let{mesgNum:T,fieldDefns:R}=A;n.check(_,T,R,t),this.localNum=I,this.mesgNum=T,this.fields=tt(R,t)}get mesgDefn(){let I=this.fields.map(({number:_,type:t,value:A})=>{let T=EI[t];if(!T)throw new Error(`Unknown type: ${t}`);let{size:R,baseType:L}=T;return t==="string"?{number:_,size:KI(A),baseType:L}:{number:_,size:R,baseType:L}});return{localNum:this.localNum,mesgNum:this.mesgNum,fieldDefns:I}}isSameDefn(I){let _=(L,O)=>L.number===O.number&&L.size===O.size&&L.baseType===O.baseType,t=(L,O)=>L.length===O.length&&L.every((D,d)=>_(D,O[d])),{localNum:A,mesgNum:T,fieldDefns:R}=this.mesgDefn;return T===I.mesgNum&&A===I.localNum&&t(R,I.fieldDefns)}get defnRecord(){let{localNum:I,mesgNum:_,fieldDefns:t}=this.mesgDefn,A=6+3*t.length,T=new DataView(new ArrayBuffer(A));T.setUint8(0,64|I),T.setUint8(2,1),T.setUint16(3,_),T.setUint8(5,t.length);let R=6;for(let L of t)T.setUint8(R++,L.number),T.setUint8(R++,L.size),T.setUint8(R++,L.baseType);return T.buffer}get dataRecord(){let{fieldDefns:I}=this.mesgDefn,_=1+I.reduce((T,{size:R})=>T+R,0),t=new DataView(new ArrayBuffer(_));t.setUint8(0,this.localNum);let A=1;for(let{number:T,type:R,value:L}of this.fields){let O=EI[R];if(!O)throw new Error(`Unknown type: ${R}`);let{size:D,setValue:d}=O,U;"mapValue"in O?U=O.mapValue(L):U=L,d&&d.call(t,A,U),A+=D}return t.buffer}};var At=[0,52225,55297,5120,61441,15360,10240,58369,40961,27648,30720,46081,20480,39937,34817,17408],wI=(n,I)=>(n>>>4^At[n&15^I])&65535,Tt=(n,I,_)=>wI(wI(n,I),_),Rt=(n,I)=>Tt(n,I&15,I>>>4);function OI(n,I=0){let _=I,t=n instanceof ArrayBuffer?new Uint8Array(n):n;for(let A=0;A<t.length;A++)_=Rt(_,t[A]);return _}import nt from"dayjs";var pI=14,Lt=16,Et=2078,Ot=776358228,D_=class{constructor(I={}){this.localNum={};this.mesgDefn=[];this.messages=[];this.options={compact:I.compact??!0,defaultActivity:I.defaultActivity??"cycling",defaultSubActivity:I.defaultSubActivity??"generic"}}async encode(I){return this.reset(),this.buildFITContent(I,"activity"),Buffer.from(await this.blob.arrayBuffer())}async encodeCourse(I){return this.reset(),this.buildFITContent(I,"course"),Buffer.from(await this.blob.arrayBuffer())}async encodeToBlob(I,_="activity"){return this.reset(),this.buildFITContent(I,_),this.blob}reset(){this.localNum={},this.mesgDefn=[],this.messages=[]}buildFITContent(I,_){this.buildFileId(I,_),_==="course"?this.buildCourseContent(I):this.buildActivityContent(I)}buildActivityContent(I){let _=I.sessionMesgs||[];if(_.length===0)throw new Error("Activity file must contain at least one Session");let t=[],A=[],T=0;for(let[R,L]of _.entries()){let O=(L.lapMesgs??[]).map((d,U)=>({...d,messageIndex:T+U})),D={...L,messageIndex:R,firstLapIndex:T,numLaps:O.length,lapMesgs:O};O.length>0&&this.buildEventsFromLaps(O,t);for(let d of O)d.recordMesgs&&this.buildRecords(d.recordMesgs);O.length>0&&this.buildLaps(O),this.buildSession(D),this.buildActivityFromSession(D,A),T+=O.length}t.forEach(R=>this.buildEvent(R)),A.forEach(R=>this.buildActivity(R))}buildCourseContent(I){let _=I.sessionMesgs||[];if(_.length===0)throw new Error("Course file must contain track data");let t=_[0];if(this.buildCourse({name:"course",sport:this.options.defaultActivity}),t.lapMesgs){let A=[];for(let L of t.lapMesgs)L.recordMesgs&&A.push(...L.recordMesgs);A.sort((L,O)=>L.timestamp&&O.timestamp?new Date(L.timestamp).getTime()-new Date(O.timestamp).getTime():(L.distance||0)-(O.distance||0));let T=A[0],R=A[A.length-1];if(t.startTime&&this.buildEvent({timestamp:t.startTime,event:"timer",eventType:"start",eventGroup:0}),A.forEach(L=>this.buildRecord(L)),R.timestamp&&this.buildEvent({timestamp:R.timestamp,event:"timer",eventType:"stop_all",eventGroup:0}),t.lapMesgs)for(let L=0;L<t.lapMesgs.length;L++)this.buildLap(t.lapMesgs[L])}}buildFileId(I,_){let t=I.fileIdMesgs?.[0]||{};this.writeMesg("file_id",{type:_,time_created:t.timeCreated?this.parseTimestamp(t.timeCreated):Date.now(),manufacturer:t.manufacturer,product:t.product,serial_number:t.serialNumber})}buildSession(I){this.writeMesg("session",{message_index:I.messageIndex,timestamp:I.timestamp?I.timestamp:void 0,start_time:I.startTime?I.startTime:void 0,total_elapsed_time:I.totalElapsedTime,total_timer_time:I.totalTimerTime,start_position_lat:I.startPositionLat!=null&&Number.isFinite(I.startPositionLat)?I.startPositionLat:void 0,start_position_long:I.startPositionLong!=null&&Number.isFinite(I.startPositionLong)?I.startPositionLong:void 0,total_distance:I.totalDistance,total_ascent:I.totalAscent,total_descent:I.totalDescent,sport:I.sport||this.options.defaultActivity,sub_sport:I.subSport||this.options.defaultSubActivity,first_lap_index:I.firstLapIndex??0,num_laps:I.numLaps??I.lapMesgs?.length??0})}buildLaps(I){I.forEach(_=>this.buildLap(_))}buildLap(I){this.writeMesg("lap",{message_index:I.messageIndex,timestamp:I?.timestamp?I.timestamp:void 0,start_time:I?.startTime?I.startTime:void 0,start_position_lat:I?.startPositionLat!=null&&Number.isFinite(I.startPositionLat)?I.startPositionLat:void 0,start_position_long:I?.startPositionLong!=null&&Number.isFinite(I.startPositionLong)?I.startPositionLong:void 0,end_position_lat:I?.endPositionLat!=null&&Number.isFinite(I.endPositionLat)?I.endPositionLat:void 0,end_position_long:I?.endPositionLong!=null&&Number.isFinite(I.endPositionLong)?I.endPositionLong:void 0,total_elapsed_time:I?.totalElapsedTime,total_timer_time:I?.totalTimerTime,total_distance:I?.totalDistance,total_ascent:I?.totalAscent,total_descent:I?.totalDescent})}buildRecords(I){I.forEach(_=>this.buildRecord(_))}buildRecord(I){this.writeMesg("record",{timestamp:I.timestamp,position_lat:I?.positionLat!=null&&Number.isFinite(I.positionLat)?I.positionLat:void 0,position_long:I?.positionLong!=null&&Number.isFinite(I.positionLong)?I.positionLong:void 0,altitude:I?.altitude,enhancedAltitude:I?.enhancedAltitude,distance:I?.distance,heart_rate:I?.heartRate,cadence:I?.cadence,speed:I?.speed,enhancedSpeed:I?.enhancedSpeed,power:I?.power})}buildEvent(I){this.writeMesg("event",{timestamp:I.timestamp?I.timestamp:void 0,event:I.event,event_type:I.eventType,event_group:I.eventGroup})}buildActivity(I){this.writeMesg("activity",{timestamp:I.timestamp?I.timestamp:void 0,total_timer_time:I.totalTimerTime,num_sessions:I.numSessions,type:I.type,event:I.event,event_type:I.eventType,local_timestamp:I.localTimestamp?this.parseTimestamp(I.localTimestamp):void 0,event_group:I.eventGroup})}buildCourse(I){this.writeMesg("course",{name:I.name,sport:I.sport})}buildEventsFromLaps(I,_){I.forEach((t,A)=>{t.startTime&&_.push({timestamp:t.startTime,event:"timer",eventType:"start",eventGroup:A}),t.timestamp&&_.push({timestamp:t.timestamp,event:"timer",eventType:A===I.length-1?"stop_all":"stop",eventGroup:A})})}buildActivityFromSession(I,_){_.push({timestamp:I.timestamp,totalTimerTime:I.totalTimerTime,numSessions:1,type:I.sport||this.options.defaultActivity,event:"activity",eventType:"stop",eventGroup:0})}parseTimestamp(I){return typeof I=="number"?I:nt(I).valueOf()}validateRequiredFields(I){if(!I.sessionMesgs||I.sessionMesgs.length===0)throw new Error("FIT file must contain at least one Session")}writeMesg(I,_){let t=Object.fromEntries(Object.entries(_).filter(([L,O])=>O!==void 0));if(Object.keys(t).length===0)return;let A=this.localNum[I];A===void 0&&(A=this.localNum[I]=Object.keys(this.localNum).length);let T=new S_(A,I,t),R=this.mesgDefn[A];(!R||!T.isSameDefn(R))&&(this.messages.push(T.defnRecord),this.mesgDefn[A]=T.mesgDefn),this.messages.push(T.dataRecord)}get blob(){let I=[this.header,...this.messages,this.trailer];return new Blob(I,{type:"application/octet-stream"})}get dataLen(){return this.messages.reduce((I,_)=>I+_.byteLength,0)}get dataCrc(){return this.messages.reduce((I,_)=>OI(_,I),0)}get header(){let I=new DataView(new ArrayBuffer(pI));return I.setUint8(0,pI),I.setUint8(1,Lt),I.setUint16(2,Et,!0),I.setUint32(4,this.dataLen,!0),I.setUint32(8,Ot),I.setUint16(12,OI(I.buffer.slice(0,12)),!0),I.buffer}get trailer(){let I=new DataView(new ArrayBuffer(2));return I.setUint16(0,this.dataCrc,!0),I.buffer}async encoder(I){return this.encode(I)}};import{Encoder as St}from"@garmin/fitsdk";var Dt="development",Ht=1,ot=1;function Ct(n,I){if(!Number.isFinite(n))throw new Error(`${I} must be a finite number.`)}function H_(n,I){return Ct(n,I),Math.abs(n)<=180?Math.round(n*2147483648/180):Math.round(n)}function Ut(n){if(!n.name||n.name.trim().length===0)throw new Error("Course name is required.");if(!Array.isArray(n.records)||n.records.length===0)throw new Error("Course must contain at least one record point.");let I=n.records.map((t,A)=>{if(t==null)throw new Error(`Course record #${A+1} is missing.`);if(t.timestamp==null)throw new Error(`Course record #${A+1} is missing timestamp.`);return{...t,positionLat:H_(t.latitude,`records[${A}].latitude`),positionLong:H_(t.longitude,`records[${A}].longitude`)}}),_=(n.coursePoints??[]).map((t,A)=>{if(t==null)throw new Error(`Course point #${A+1} is missing.`);if(t.timestamp==null)throw new Error(`Course point #${A+1} is missing timestamp.`);return{...t,type:t.type??0,positionLat:H_(t.latitude,`coursePoints[${A}].latitude`),positionLong:H_(t.longitude,`coursePoints[${A}].longitude`)}});return{...n,sport:n.sport??2,subSport:n.subSport??0,records:I,coursePoints:_,manufacturer:n.manufacturer??Dt,product:n.product??Ht,serialNumber:n.serialNumber??ot,timeCreated:n.timeCreated??I[0].timestamp}}function ft(n){let I=Ut(n),_=I.records[0],t=I.records[I.records.length-1],A=_.timestamp,T=t.timestamp,R=[{mesgNum:0,data:{type:6,manufacturer:I.manufacturer,product:I.product,serialNumber:I.serialNumber,timeCreated:I.timeCreated}},{mesgNum:31,data:{name:I.name,sport:I.sport,subSport:I.subSport}},{mesgNum:19,data:{startTime:A,timestamp:T,startPositionLat:_.positionLat,startPositionLong:_.positionLong,endPositionLat:t.positionLat,endPositionLong:t.positionLong,totalDistance:t.distance}},{mesgNum:21,data:{timestamp:A,event:0,eventType:0}}];return I.records.forEach(L=>{R.push({mesgNum:20,data:{timestamp:L.timestamp,positionLat:L.positionLat,positionLong:L.positionLong,distance:L.distance,altitude:L.altitude,speed:L.speed}})}),I.coursePoints.forEach((L,O)=>{R.push({mesgNum:32,data:{messageIndex:O,timestamp:L.timestamp,positionLat:L.positionLat,positionLong:L.positionLong,distance:L.distance,type:L.type,name:L.name,favorite:L.favorite}})}),R.push({mesgNum:21,data:{timestamp:T,event:0,eventType:4}}),R}function XI(n){let I=new St;return ft(n).forEach(t=>{I.onMesg(t.mesgNum,t.data)}),I.close()}var z=class{constructor(){this.version="1.0.0";this.priority=100}supports(I){return this.supportedTags.includes(I)}async initialize(I){I.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(I){I.metadata.delete(`plugin:${this.name}:initialized`)}async validate(I){return!0}parseFloat(I){if(!(typeof I>"u"))return typeof I=="number"?I:typeof I=="string"&&parseFloat(I)||0}parseInt(I){return typeof I=="number"?Math.floor(I):typeof I=="string"&&parseInt(I,10)||0}parseString(I){return String(I||"")}parseBoolean(I){return typeof I=="boolean"?I:typeof I=="string"?I.toLowerCase()==="true":!1}parseDate(I){if(!I)return;let _=new Date(I);return isNaN(_.getTime())?void 0:_}hasRequiredAttributes(I,_){return _.every(t=>I.attributes?.[t])}extractAttributes(I,_,t){I.attributes&&Object.entries(I.attributes).forEach(([A,T])=>{let R=t[A];R&&(_[R]=String(T??""))})}processChildren(I,_,t){I.children?.forEach(A=>{let T=t[A.tag];T&&T(A,_)})}getChildValue(I,_){let t=I.children?.find(A=>A.tag===_);return t?.value?String(t.value):void 0}getChildByTag(I,_){return I.children?.find(t=>t.tag===_)}getChildrenByTag(I,_){return I.children?.filter(t=>t.tag===_)||[]}convertExtensions(I){let _={};return I.children?.forEach(t=>{_[t.tag]=this.convertExtensionContent(t)}),_}convertExtensionContent(I){if(I.children?.length){let _={};return I.children.forEach(t=>{_[t.tag]=this.convertExtensionContent(t)}),_}else return I.value}};var v=class extends z{parseCoordinate(I){let _=this.parseFloat(I);return _===0?void 0:_}parseGPXTime(I){if(!I)return;let _=new Date(I);return isNaN(_.getTime())?void 0:_}extractNumericAttributes(I,_,t){I.attributes&&Object.entries(I.attributes).forEach(([A,T])=>{let R=t[A];R&&R in _&&typeof T<"u"&&(_[R]=this.parseFloat(T))})}};var o_=class extends v{constructor(){super(...arguments);this.name="wpt-converter";this.supportedTags=["wpt","trkpt","rtept"];this.version="1.0.0"}convert(_,t){if(!this.hasRequiredAttributes(_,["lat","lon"])){t.warnings.push(`${this.name}: point without latitude or longitude was ignored`);return}let A={lat:this.parseFloat(_.attributes?.lat),lon:this.parseFloat(_.attributes?.lon)};return this.processChildren(_,A,{ele:(T,R)=>R.ele=this.parseFloat(T.value),time:(T,R)=>R.time=new Date(this.parseString(T.value)),speed:(T,R)=>R.speed=this.parseFloat(T.value),power:(T,R)=>R.power=this.parseFloat(T.value),cadence:(T,R)=>R.cadence=this.parseFloat(T.value),heartRate:(T,R)=>R.heartRate=this.parseFloat(T.value),course:(T,R)=>R.course=this.parseFloat(T.value),name:(T,R)=>R.name=this.parseString(T.value),cmt:(T,R)=>R.cmt=this.parseString(T.value),desc:(T,R)=>R.desc=this.parseString(T.value),src:(T,R)=>R.src=this.parseString(T.value),sym:(T,R)=>R.sym=this.parseString(T.value),type:(T,R)=>R.type=this.parseString(T.value),fix:(T,R)=>R.fix=this.parseString(T.value),sat:(T,R)=>R.sat=this.parseFloat(T.value),hdop:(T,R)=>R.hdop=this.parseFloat(T.value),vdop:(T,R)=>R.vdop=this.parseFloat(T.value),pdop:(T,R)=>R.pdop=this.parseFloat(T.value),ageofdgpsdata:(T,R)=>R.ageofdgpsdata=this.parseFloat(T.value),geoidheight:(T,R)=>R.geoidheight=this.parseFloat(T.value),magvar:(T,R)=>R.magvar=this.parseFloat(T.value),dgpsid:(T,R)=>R.dgpsid=this.parseFloat(T.value),extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("extensions");if(O){let D=O.convert(T,t);D&&(this.mapExtensionsToPoint(D,R),R.extensions=D)}},link:(T,R)=>{R.link||(R.link=[]);let O=t.metadata.get("decoder")?.getConverter("link")?.convert(T,t);O&&R.link&&R.link.push(O)}}),A}mapExtensionsToPoint(_,t){Object.entries(_).forEach(([A,T])=>{if(T!==void 0&&(typeof T=="string"||typeof T=="number")){let R=L=>(Array.isArray(L)?L:[L]).some(D=>{let d=A.toLowerCase(),U=D.toLowerCase();return d===U||d.endsWith(`:${U}`)});R("speed")?t.speed=this.parseFloat(T):R("hr")?t.heartRate=this.parseFloat(T):R(["cad","cadence"])?t.cadence=this.parseFloat(T):R(["PowerInWatts","power"])&&(t.power=this.parseFloat(T))}})}},C_=class extends v{constructor(){super(...arguments);this.name="rte-converter";this.supportedTags=["rte"]}convert(_,t){let A={rtept:[]};return this.processChildren(_,A,{name:(T,R)=>R.name=this.parseString(T.value),cmt:(T,R)=>R.cmt=this.parseString(T.value),desc:(T,R)=>R.desc=this.parseString(T.value),src:(T,R)=>R.src=this.parseString(T.value),number:(T,R)=>R.number=this.parseFloat(T.value),type:(T,R)=>R.type=this.parseString(T.value),rtept:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("wpt")?.convert(T,t);O&&R.rtept&&R.rtept.push(O)},extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("extensions");O&&(R.extensions=O.convert(T,t))},link:(T,R)=>{R.link||(R.link=[]);let O=t.metadata.get("decoder")?.getConverter("link")?.convert(T,t);O&&R.link&&R.link.push(O)}}),A}},U_=class extends v{constructor(){super(...arguments);this.name="trk-converter";this.supportedTags=["trk"]}convert(_,t){let A={trkseg:[]};return this.processChildren(_,A,{name:(T,R)=>R.name=this.parseString(T.value),cmt:(T,R)=>R.cmt=this.parseString(T.value),desc:(T,R)=>R.desc=this.parseString(T.value),src:(T,R)=>R.src=this.parseString(T.value),number:(T,R)=>R.number=this.parseFloat(T.value),type:(T,R)=>R.type=this.parseString(T.value),trkseg:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("trkseg")?.convert(T,t);O&&R.trkseg&&R.trkseg.push(O)},extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("extensions");O&&(R.extensions=O.convert(T,t))},link:(T,R)=>{R.link||(R.link=[]);let O=t.metadata.get("decoder")?.getConverter("link")?.convert(T,t);O&&R.link&&R.link.push(O)}}),A}},f_=class extends v{constructor(){super(...arguments);this.name="trkseg-converter";this.supportedTags=["trkseg"]}convert(_,t){let A={trkpt:[]};return this.processChildren(_,A,{trkpt:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("wpt")?.convert(T,t);O&&R.trkpt&&R.trkpt.push(O)},extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("extensions");O&&(R.extensions=O.convert(T,t))}}),A}},d_=class extends v{constructor(){super(...arguments);this.name="link-converter";this.supportedTags=["link"]}convert(_,t){let A={};return _.attributes?.href&&(A.href=_.attributes.href),this.processChildren(_,A,{text:(T,R)=>R.text=this.parseString(T.value),type:(T,R)=>R.type=this.parseString(T.value)}),A}},F_=class extends v{constructor(){super(...arguments);this.name="metadata-converter";this.supportedTags=["metadata"]}convert(_,t){let A={};return this.processChildren(_,A,{name:(T,R)=>R.name=this.parseString(T.value),desc:(T,R)=>R.desc=this.parseString(T.value),keywords:(T,R)=>R.keywords=this.parseString(T.value),time:(T,R)=>R.time=new Date(this.parseString(T.value)),author:(T,R)=>{let L=t.metadata.get("decoder");R.author=L?.getConverter("author")?.convert(T,t)},copyright:(T,R)=>{let L=t.metadata.get("decoder");R.copyright=L?.getConverter("copyright")?.convert(T,t)},bounds:(T,R)=>{let L=t.metadata.get("decoder");R.bounds=L?.getConverter("bounds")?.convert(T,t)},extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("extensions");O&&(R.extensions=O.convert(T,t))},link:(T,R)=>{R.link||(R.link=[]);let O=t.metadata.get("decoder")?.getConverter("link")?.convert(T,t);O&&R.link&&R.link.push(O)}}),A}},G_=class extends v{constructor(){super(...arguments);this.name="person-converter";this.supportedTags=["author"]}convert(_,t){let A={};return _.value&&!_.children?.length?(A.name=this.parseString(_.value),A):(this.processChildren(_,A,{name:(T,R)=>R.name=this.parseString(T.value),email:(T,R)=>{let L=t.metadata.get("decoder");R.email=L?.getConverter("email")?.convert(T,t)},link:(T,R)=>{let L=t.metadata.get("decoder");R.link=L?.getConverter("link")?.convert(T,t)}}),A)}},g_=class extends v{constructor(){super(...arguments);this.name="email-converter";this.supportedTags=["email"]}convert(_,t){return{id:_.attributes?.id,domain:_.attributes?.domain}}},l_=class extends v{constructor(){super(...arguments);this.name="copyright-converter";this.supportedTags=["copyright"]}convert(_,t){let A={};return _.attributes?.author&&(A.author=_.attributes.author),this.processChildren(_,A,{year:(T,R)=>R.year=this.parseString(T.value),license:(T,R)=>R.license=this.parseString(T.value)}),A}},W_=class extends v{constructor(){super(...arguments);this.name="bounds-converter";this.supportedTags=["bounds"]}convert(_,t){let A={};return this.extractAttributes(_,A,{minlat:"minlat",minlon:"minlon",maxlat:"maxlat",maxlon:"maxlon"}),A}},B_=class extends v{constructor(){super(...arguments);this.name="extensions-converter";this.supportedTags=["extensions"]}convert(_,t){let A={};return _.children?.forEach(T=>{this.flattenExtensionElement(T,A)}),A}flattenExtensionElement(_,t){if(!_.children?.length&&_.value!==void 0){t[_.tag]=this.parseExtensionValue(_.value);return}_.children?.length&&_.children.forEach(A=>{this.flattenExtensionElement(A,t)})}parseExtensionValue(_){if(_===void 0)return;let t=String(_),A=parseFloat(t);return!isNaN(A)&&isFinite(A)?A:t}};import{Parser as dt}from"htmlparser2";var M_=class{constructor(){this.stage="tokenize"}async process(I){let _=Date.now();if(!I.xmlContent)throw new Error("XML content cannot be empty");let t=[],A=new dt({onopentag(T,R){t.push({type:"open",tag:T,attributes:R})},ontext(T){let R=T.replace(/\n/g,"").trim();R&&t.push({type:"text",tag:"text",value:R})},onclosetag(T){t.push({type:"close",tag:T})}},{xmlMode:!0});return A.write(I.xmlContent),A.end(),I.tokens=t,I.performance.tokenizeTime=Date.now()-_,I}},V_=class{constructor(){this.stage="ast_generate"}async process(I){let _=Date.now();if(!I.tokens)throw new Error("Tokens cannot be empty");let t=[],A,T=null;for(let R of I.tokens)if(R.type==="open"){let L={tag:R.tag,attributes:R.attributes||{},children:[]};A?T&&T.children?.push(L):A=L,t.push(L),T=L}else R.type==="text"&&T?T.value=R.value:R.type==="close"&&(t.pop(),T=t[t.length-1]||null);return I.ast=A,I.performance.astTime=Date.now()-_,I}},K_=class{constructor(I){this.getConverter=I;this.stage="convert"}async process(I){let _=Date.now();if(!I.ast)throw new Error("AST cannot be empty");if(I.ast.tag!=="gpx")throw new Error(`Not a valid GPX document: expected <gpx>, received <${I.ast.tag}>`);let t={};return I.ast.attributes&&Object.entries(I.ast.attributes).forEach(([A,T])=>{A.startsWith("xmlns:")?t[A]=T.replace(/&#39;/g,"'"):A==="xsi:schemaLocation"?t[A]=T.replace(/&#39;/g,"'"):t[A]=T}),I.ast.children?.forEach(A=>{let T=this.getConverter(A.tag);if(!T){I.warnings.push(`Unsupported GPX element "${A.tag}" was ignored`);return}try{let R=T.convert(A,I);R&&this.assignResult(t,A.tag,R)}catch(R){throw I.errors.push(R),new Error(`GPX converter "${T.name}" failed for ${A.tag}: ${R.message}`)}}),I.result=t,I.performance.convertTime=Date.now()-_,I}assignResult(I,_,t){switch(_){case"metadata":I.metadata=t;break;case"wpt":I.wpt||(I.wpt=[]),I.wpt.push(t);break;case"rte":I.rte||(I.rte=[]),I.rte.push(t);break;case"trk":I.trk||(I.trk=[]),I.trk.push(t);break;case"extensions":I.extensions=t;break}}},h_=class{constructor(){this.stage="complete"}async process(I){I.performance.endTime=Date.now();let _=I.performance.endTime-I.performance.startTime;return I.metadata.set("performance",{totalTime:_,tokenizeTime:I.performance.tokenizeTime,astTime:I.performance.astTime,convertTime:I.performance.convertTime}),I}};var w_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultConvertersRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new M_,new V_,new K_(I=>this.getConverter(I)),new h_]}async registerDefaultConverters(){if(this.defaultConvertersRegistered)return;let I=[new o_,new C_,new U_,new f_,new d_,new F_,new G_,new g_,new l_,new W_,new B_];for(let _ of I)_.supportedTags?.forEach(t=>{this.addConverterForTag(t,_)}),this.registeredPlugins.add(_.name);this.defaultConvertersRegistered=!0}addConverterForTag(I,_){this.converterPlugins.has(I)||this.converterPlugins.set(I,[]);let t=this.converterPlugins.get(I);t.push(_),t.sort((A,T)=>(A.priority||100)-(T.priority||100))}async registerConverter(I){if(this.registeredPlugins.has(I.name))throw new Error(`Converter plugin ${I.name} already exists`);I.supportedTags?.forEach(_=>{this.addConverterForTag(_,I)}),this.registeredPlugins.add(I.name)}async registerMiddleware(I){let _=this.middlewarePlugins.findIndex(t=>t.name===I.name);_!==-1?this.middlewarePlugins[_]=I:this.middlewarePlugins.push(I)}getConverter(I){let _=this.converterPlugins.get(I);return _&&_.length>0?_[0]:void 0}getAllConverters(I){return this.converterPlugins.get(I)||[]}unregisterConverter(I){let _;for(let[t,A]of this.converterPlugins){let T=A.findIndex(R=>R.name===I);T!==-1&&(_=A[T],A.splice(T,1),A.length===0&&this.converterPlugins.delete(t))}_&&this.registeredPlugins.delete(I)}unregisterMiddleware(I){let _=this.middlewarePlugins.findIndex(t=>t.name===I);_!==-1&&this.middlewarePlugins.splice(_,1)}listConverters(){return Array.from(this.converterPlugins.keys())}listConverterPlugins(){return Array.from(this.registeredPlugins)}listMiddlewares(){return this.middlewarePlugins.map(I=>I.name)}listProcessors(){return this.processors.map(I=>I.constructor.name)}getConverterDetails(I){let _={};if(I){let t=this.converterPlugins.get(I);t&&(_[I]=t.map(A=>({name:A.name,priority:A.priority||100})))}else for(let[t,A]of this.converterPlugins)_[t]=A.map(T=>({name:T.name,priority:T.priority||100}));return _}getMiddlewareDetails(){return this.middlewarePlugins.map(I=>{let _=[];return I.onTokenize&&_.push("onTokenize"),I.onAstGenerate&&_.push("onAstGenerate"),I.onConvert&&_.push("onConvert"),I.onComplete&&_.push("onComplete"),I.onError&&_.push("onError"),{name:I.name,hooks:_}})}async initialize(){if(this.initialized)return;await this.registerDefaultConverters();let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.initialize?.(I);this.initialized=!0}async destroy(){if(!this.initialized)return;let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.destroy?.(I);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(I,_,t){let A=_;for(let T of this.middlewarePlugins){let R=T[I];if(R)try{A=await R.call(T,A,t)||A}catch(L){t.errors.push(L),await T.onError?.(L,t)}}return A}async parserByBuffer(I){await this.initialize();let _=this.createContext();_.rawData=I,_.xmlContent=I.toString("utf-8"),_.metadata.set("decoder",this);for(let t of this.processors)try{switch(_=await t.process(_),t.stage){case"tokenize":_.tokens&&(_.tokens=await this.executeMiddlewareHook("onTokenize",_.tokens,_));break;case"ast_generate":_.ast&&(_.ast=await this.executeMiddlewareHook("onAstGenerate",_.ast,_));break;case"convert":_.result&&(_.result=await this.executeMiddlewareHook("onConvert",_.result,_));break;case"complete":_.result&&(_.result=await this.executeMiddlewareHook("onComplete",_.result,_));break}}catch(A){_.errors.push(A);for(let T of this.middlewarePlugins)await T.onError?.(A,_);throw new Error(`GPX pipeline stage "${t.stage}" failed: ${A.message}`)}return _.result}convertExtensions(I){let _={},{attributes:t,tag:A,value:T}=I;if(t&&Object.entries(t).forEach(([R,L])=>{_[R]=L}),I?.children?.length)I.children?.forEach(R=>{_[R.tag]=this.convertExtensions(R)});else if(T!==void 0)return T;return _}};import vI from"dayjs";import Ft from"dayjs/plugin/utc.js";var SI={temperature:"atemp",wtemp:"wtemp",heartRate:"hr",cadence:"cad"};var DI={temperature:"Temperature",Depth:"Depth"};vI.extend(Ft);var p_=class{constructor(I={}){this.formatElevation=I=>{let _=parseFloat(I);return isNaN(_)?I:this.roundTo(_,2).toString()};this.compact=I.compact??!0}async encode(I){let _=this.buildGPXXML(I);return Buffer.from(_,"utf-8")}encodeToString(I){return this.buildGPXXML(I)}buildGPXXML(I){let _=this.buildXMLHeader(I),t=this.buildGPXContent(I),T=`${_}${t}
2
+ </gpx>`;return this.compact?this.compressXML(T):T}compressXML(I){return I.replace(/>\s+</g,"><").replace(/^\s+|\s+$/gm,"").replace(/\s+/g," ").trim()}buildXMLHeader(I){let _=this.escapeXMLAttribute(I.creator||"TrackSwap"),t=this.escapeXMLAttribute(I.version||"1.1");return['<?xml version="1.0" encoding="UTF-8"?>',`<gpx creator="${_}" version="${t}"`,' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',' xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd'," http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd"," http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd"," http://www.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd",' http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd"',' xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"',' xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"',' xmlns:gpxpx="http://www.garmin.com/xmlschemas/PowerExtension/v1"',' xmlns:gpx_style="http://www.topografix.com/GPX/gpx_style/0/2"',' xmlns="http://www.topografix.com/GPX/1/1">'].join(`
3
+ `)}buildGPXContent(I){let{metadata:_,wpt:t=[],rte:A=[],trk:T=[],extensions:R}=I,L=[];return _&&L.push(this.buildMetadata(_)),t.forEach(O=>{L.push(this.buildWaypoint(O,"wpt"))}),A.forEach(O=>{L.push(this.buildRoute(O))}),T.forEach(O=>{L.push(this.buildTrack(O))}),R&&L.push(this.buildExtensions(R)),L.join(`
4
+ `)}buildMetadata(I){let _=["<metadata>"];return this.addOptionalElement(_,"name",I.name),this.addOptionalElement(_,"desc",I.desc),I.author&&_.push(this.buildAuthor(I.author)),I.copyright&&_.push(this.buildCopyright(I.copyright)),I.link&&this.addLinks(_,I.link),I.time&&_.push(this.buildTimeElement(I.time)),this.addOptionalElement(_,"keywords",I.keywords),I.bounds&&_.push(this.buildBounds(I.bounds)),I.extensions&&_.push(this.buildExtensions(I.extensions)),_.push("</metadata>"),_.join(`
5
+ `)}buildAuthor(I){let _=["<author>"];return this.addOptionalElement(_,"name",I.name),I.email&&_.push(`<email id="${this.escapeXML(I.email.id||"")}" domain="${this.escapeXML(I.email.domain||"")}"/>`),I.link&&_.push(this.buildLink(I.link)),_.push("</author>"),_.join(`
6
+ `)}buildCopyright(I){let _=[`<copyright author="${this.escapeXML(I.author||"")}">`];return this.addOptionalElement(_,"year",I.year),this.addOptionalElement(_,"license",I.license),_.push("</copyright>"),_.join(`
7
+ `)}buildBounds(I){let _=this.escapeXMLAttribute((I.minlat||0).toString()),t=this.escapeXMLAttribute((I.minlon||0).toString()),A=this.escapeXMLAttribute((I.maxlat||0).toString()),T=this.escapeXMLAttribute((I.maxlon||0).toString());return`<bounds minlat="${_}" minlon="${t}" maxlat="${A}" maxlon="${T}"/>`}buildWaypoint(I,_){let t=I.lat,A=I.lon,T=typeof t=="number"&&Number.isFinite(t)&&t>=-90&&t<=90,R=typeof A=="number"&&Number.isFinite(A)&&A>=-180&&A<=180;if(!T||!R)return"";let L=[`<${_} lat="${this.escapeXMLAttribute(this.formatCoordinate(t))}" lon="${this.escapeXMLAttribute(this.formatCoordinate(A))}">`];this.addOptionalElement(L,"ele",I.ele?.toString(),this.formatElevation),I?.time&&L.push(this.buildTimeElement(I.time)),this.addStandardWaypointElements(L,I);let O=this.processPointExtensions(I,I.extensions??{});return Object.keys(O).length>0&&L.push(this.buildExtensions(O)),L.push(`</${_}>`),L.join(`
8
+ `)}addStandardWaypointElements(I,_){this.addOptionalElement(I,"magvar",_.magvar?.toString()),this.addOptionalElement(I,"geoidheight",_.geoidheight?.toString()),this.addOptionalElement(I,"name",_.name),this.addOptionalElement(I,"cmt",_.cmt),this.addOptionalElement(I,"desc",_.desc),this.addOptionalElement(I,"src",_.src),_.link&&this.addLinks(I,_.link),this.addOptionalElement(I,"sym",_.sym),this.addOptionalElement(I,"type",_.type),this.addOptionalElement(I,"fix",_.fix),this.addOptionalElement(I,"sat",_.sat?.toString()),this.addOptionalElement(I,"hdop",_.hdop?.toString()),this.addOptionalElement(I,"vdop",_.vdop?.toString()),this.addOptionalElement(I,"pdop",_.pdop?.toString()),this.addOptionalElement(I,"ageofdgpsdata",_.ageofdgpsdata?.toString()),this.addOptionalElement(I,"dgpsid",_.dgpsid?.toString())}buildRoute(I){let _=["<rte>"];return this.addRouteTrackCommonElements(_,I),I.extensions&&_.push(this.buildExtensions(I.extensions)),I.rtept&&I.rtept?.forEach(t=>{_.push(this.buildWaypoint(t,"rtept"))}),_.push("</rte>"),_.join(`
9
+ `)}buildTrack(I){let _=["<trk>"];return this.addRouteTrackCommonElements(_,I),I.extensions&&_.push(this.buildExtensions(I.extensions)),I.trkseg&&I.trkseg.forEach(t=>{_.push(this.buildTrackSegment(t))}),_.push("</trk>"),_.join(`
10
+ `)}buildTrackSegment(I){let _=["<trkseg>"];return I.trkpt&&I.trkpt.forEach(t=>{_.push(this.buildWaypoint(t,"trkpt"))}),I.extensions&&_.push(this.buildExtensions(I.extensions)),_.push("</trkseg>"),_.join(`
11
+ `)}addRouteTrackCommonElements(I,_){this.addOptionalElement(I,"name",_.name),this.addOptionalElement(I,"cmt",_.cmt),this.addOptionalElement(I,"desc",_.desc),this.addOptionalElement(I,"src",_.src),_.link&&this.addLinks(I,_.link),this.addOptionalElement(I,"number",_.number?.toString()),this.addOptionalElement(I,"type",_.type)}processPointExtensions(I,_){let t={};return Object.entries({"gpxtpx:TrackPointExtension":{"gpxtpx:hr":"heartRate","gpxtpx:cad":"cadence","gpxtpx:speed":"speed","gpxtpx:atemp":"temperature","gpxtpx:wtemp":"wtemp","gpxtpx:temp":"temperature"},"gpxpx:PowerExtension":{"gpxpx:PowerInWatts":"power"},"gpxx:GpxExtensions":{"gpxx:Temperature":"temperature","gpxx:Depth":"depth"}}).forEach(([T,R])=>{let L={},O=!1;Object.entries(R).forEach(([D,d])=>{let U;if(I[d]!==void 0)U=I[d];else if(_)if(_[D]!==void 0)U=_[D];else{let W=D.split(":").pop();Object.entries(_).forEach(([l,M])=>{l.endsWith(`:${W}`)&&M!==void 0&&(U=M)})}U!==void 0&&(L[D]=U,O=!0)}),O&&(t[T]=L)}),t}buildTrackPointExtension(I,_){let t=this.deepClone(_["gpxtpx:TrackPointExtension"]||{}),A=Object.keys(SI);return Object.keys(I).filter(T=>A.includes(T)).forEach(T=>{let R=SI[T];R&&I[T]!==void 0&&(t[`gpxtpx:${R}`]=I[T])}),t}buildPowerExtension(I,_){return this.deepClone(_["gpxpx:PowerExtension"]||{})}buildGpxExtensions(I,_){let t=this.deepClone(_["gpxx:GpxExtensions"]||{}),A=Object.keys(DI);return Object.keys(I).filter(T=>A.includes(T)).forEach(T=>{let R=DI[T];R&&I[T]!==void 0&&(t[`gpxx:${R}`]=I[T])}),t}buildExtensions(I){let _=this.buildExtensionContent(I);return _?`<extensions>${_}</extensions>`:""}buildExtensionContent(I){return Object.entries(I).filter(([_])=>!_.startsWith("xmlns")).map(([_,t])=>{if(t&&typeof t=="object"){let A=this.buildExtensionContent(t);return`<${_}>${A}</${_}>`}else if(t!=null)return`<${_}>${this.escapeXML(String(t))}</${_}>`;return""}).filter(_=>_).join("")}buildLink(I){let _=[`<link href="${this.escapeXMLAttribute(I.href||"")}">`];return this.addOptionalElement(_,"text",I.text),this.addOptionalElement(_,"type",I.type),_.push("</link>"),_.join("")}addLinks(I,_){(Array.isArray(_)?_:[_]).forEach(A=>{I.push(this.buildLink(A))})}buildTimeElement(I){return typeof I=="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/.test(I)?`<time>${I}</time>`:`<time>${vI(I).utc().format("YYYY-MM-DDTHH:mm:ss[Z]")}</time>`}addOptionalElement(I,_,t,A){if(t!=null&&t!==""){let T=A?A(t):this.escapeXML(t);I.push(`<${_}>${T}</${_}>`)}}isValidCoordinate(I,_){return I!=null&&_!==void 0&&_!==null&&!isNaN(I)&&!isNaN(_)}formatCoordinate(I){return this.roundTo(I,6).toString()}roundTo(I,_){let t=Math.pow(10,_);return Math.round(I*t)/t}escapeXML(I){return I.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeXMLAttribute(I){return typeof I!="string"?String(I||""):I.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;").replace(/\n/g,"&#10;").replace(/\t/g,"&#9;")}deepClone(I){if(I===null||typeof I!="object")return I;if(I instanceof Date)return new Date(I.getTime());if(Array.isArray(I))return I.map(t=>this.deepClone(t));let _={};for(let t in I)Object.prototype.hasOwnProperty.call(I,t)&&(_[t]=this.deepClone(I[t]));return _}encoder(I){return this.encode(I)}};var N=class extends z{parseHeartRate(I){let _=this.parseFloat(I);if(!(typeof _>"u"))return _>0&&_<300?_:void 0}parseTCXTime(I){if(!I)return;let _=new Date(I);return isNaN(_.getTime())?void 0:_}parseDistance(I){let _=this.parseFloat(I);if(!(typeof _>"u"))return _>0?_:void 0}parseSpeed(I){let _=this.parseFloat(I);if(!(typeof _>"u"))return _>=0?_:void 0}parseAltitude(I){return this.parseFloat(I)}parseCoordinate(I){let _=this.parseFloat(I);return _!==0?_:void 0}};var X_=class extends N{constructor(){super(...arguments);this.name="PositionConverter";this.supportedTags=["Position"]}convert(_,t){let A={};return this.processChildren(_,A,{LatitudeDegrees:(T,R)=>R.LatitudeDegrees=this.parseString(T.value),LongitudeDegrees:(T,R)=>R.LongitudeDegrees=this.parseString(T.value)}),A}},P_=class extends N{constructor(){super(...arguments);this.name="TrackpointConverter";this.supportedTags=["Trackpoint"]}convert(_,t){let A={};return this.processChildren(_,A,{Time:(T,R)=>R.Time=this.parseString(T.value),Position:(T,R)=>{let L=t.metadata.get("decoder");R.Position=L?.getConverter("Position")?.convert(T,t)},AltitudeMeters:(T,R)=>R.AltitudeMeters=this.parseFloat(T.value),DistanceMeters:(T,R)=>R.DistanceMeters=this.parseFloat(T.value),HeartRateBpm:(T,R)=>{if(T.value)R.HeartRateBpm=this.parseFloat(T.value);else{let L=this.getChildByTag(T,"Value");L?.value&&(R.HeartRateBpm=this.parseFloat(L.value))}},Cadence:(T,R)=>{let L={Low:0,High:0};this.processChildren(T,L,{Low:(O,D)=>D.Low=this.parseFloat(O.value)||0,High:(O,D)=>D.High=this.parseFloat(O.value)||0}),R.Cadence=L},SensorState:(T,R)=>R.SensorState=T.value,Extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Extensions");O&&(R.Extensions=O.convert(T,t))}}),A}},v_=class extends N{constructor(){super(...arguments);this.name="TrackConverter";this.supportedTags=["Track"]}convert(_,t){let A={Trackpoint:[]};return this.processChildren(_,A,{Trackpoint:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Trackpoint")?.convert(T,t);O&&R.Trackpoint&&R.Trackpoint.push(O)}}),A}},s_=class extends N{constructor(){super(...arguments);this.name="ActivityLapConverter";this.supportedTags=["Lap"]}convert(_,t){let A={};return this.extractAttributes(_,A,{StartTime:"StartTime"}),this.processChildren(_,A,{TotalTimeSeconds:(T,R)=>R.TotalTimeSeconds=this.parseFloat(T.value),DistanceMeters:(T,R)=>R.DistanceMeters=this.parseFloat(T.value),MaximumSpeed:(T,R)=>R.MaximumSpeed=this.parseFloat(T.value),Calories:(T,R)=>R.Calories=this.parseFloat(T.value),AverageHeartRateBpm:(T,R)=>R.AverageHeartRateBpm=this.parseFloat(T.value),MaximumHeartRateBpm:(T,R)=>R.MaximumHeartRateBpm=this.parseFloat(T.value),Intensity:(T,R)=>R.Intensity=T.value,TriggerMethod:(T,R)=>R.TriggerMethod=T.value,Track:(T,R)=>{R.Track||(R.Track=[]);let O=t.metadata.get("decoder")?.getConverter("Track")?.convert(T,t);O&&R.Track.push(O)},Notes:(T,R)=>R.Notes=this.parseString(T.value),Extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Extensions");O&&(R.Extensions=O.convert(T,t))}}),A}},Y_=class extends N{constructor(){super(...arguments);this.name="ActivityConverter";this.supportedTags=["Activity"]}convert(_,t){let A={Id:"",Lap:[]};return this.extractAttributes(_,A,{Sport:"Sport"}),this.processChildren(_,A,{Id:(T,R)=>R.Id=this.parseString(T.value),Lap:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Lap")?.convert(T,t);O&&R.Lap.push(O)},Notes:(T,R)=>R.Notes=this.parseString(T.value),Training:(T,R)=>R.Training=this.convertTraining(T),Creator:(T,R)=>R.Creator=this.convertCreator(T),Extensions:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Extensions");O&&(R.Extensions=O.convert(T,t))}}),A}convertTraining(_){let t={};return _.attributes&&Object.entries(_.attributes).forEach(([A,T])=>{t[A]=T}),_.children?.forEach(A=>{t[A.tag]=this.convertExtensionContent(A)}),t}convertCreator(_){let t={};return _.children?.forEach(A=>{t[A.tag]=this.convertExtensionContent(A)}),t}},b_=class extends N{constructor(){super(...arguments);this.name="ActivityListConverter";this.supportedTags=["Activities"]}convert(_,t){let A={Activity:[],MultiActivitySession:[]};return this.processChildren(_,A,{Activity:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("Activity")?.convert(T,t);O&&R.Activity&&R.Activity.push(O)},MultiActivitySession:(T,R)=>{let O=t.metadata.get("decoder")?.getConverter("MultiActivitySession")?.convert(T,t);O&&R.MultiActivitySession&&R.MultiActivitySession.push(O)}}),A}},N_=class extends N{constructor(){super(...arguments);this.name="MultiActivitySessionConverter";this.supportedTags=["MultiActivitySession"]}convert(_,t){let A={};return this.processChildren(_,A,{Id:(T,R)=>R.Id=this.parseString(T.value),FirstActivity:(T,R)=>{let L=t.metadata.get("decoder");R.FirstActivity=L?.getConverter("FirstActivity")?.convert(T,t)},NextActivity:(T,R)=>{R.NextActivity||(R.NextActivity=[]);let O=t.metadata.get("decoder")?.getConverter("NextActivity")?.convert(T,t);O&&R.NextActivity.push(O)},Notes:(T,R)=>R.Notes=this.parseString(T.value)}),A}},$_=class extends N{constructor(){super(...arguments);this.name="AbstractSourceConverter";this.supportedTags=["Author","Creator"]}convert(_,t){let A={};return this.processChildren(_,A,{Name:(T,R)=>R.Name=this.parseString(T.value)}),A}},Q_=class extends N{constructor(){super(...arguments);this.name="extensions-converter";this.supportedTags=["Extensions"]}convert(_,t){let A={};return this.flattenExtensionElement(_,A),A}flattenExtensionElement(_,t){if(!_.children?.length&&_.value!==void 0){t[_.tag]=this.parseExtensionValue(_.value);return}_.children?.length&&_.children.forEach(A=>{this.flattenExtensionElement(A,t)})}parseExtensionValue(_){if(_===void 0)return;let t=String(_),A=parseFloat(t);return!isNaN(A)&&isFinite(A)?A:t}};import{Parser as sI}from"htmlparser2";var J_=class{static tokenizeXML(I){let _=[],t=new sI({onopentag(A,T){_.push({type:"open",tag:A,attributes:T})},ontext(A){let T=A.replace(/\n/g,"").trim();T&&_.push({type:"text",tag:"text",value:T})},onclosetag(A){_.push({type:"close",tag:A})}},{xmlMode:!0});return t.write(I),t.end(),_}static compressXML(I){return I.replace(/>\s+</g,"><").replace(/\s+/g," ").trim()}static formatXML(I,_=2){let t=" ".repeat(_),A="",T=0,R=!1;for(let L=0;L<I.length;L++){let O=I[L],D=I[L+1];O==="<"?(D==="/"?(T--,R||(A+=`
12
+ `+t.repeat(T))):D!=="?"&&D!=="!"&&(R||(A+=`
13
+ `+t.repeat(T)),T++),R=!0):O===">"&&(R=!1,D==="<"&&I[L+2]==="/"&&T--),A+=O}return A.trim()}static validateXML(I){try{let _=new sI({},{xmlMode:!0});return _.write(I),_.end(),{isValid:!0}}catch(_){return{isValid:!1,error:_.message}}}static extractXMLDeclaration(I){let _=I.match(/<\?xml\s+([^>]+)\?>/);if(!_)return{};let t=_[1],A={},T=t.match(/version=["']([^"']+)["']/);T&&(A.version=T[1]);let R=t.match(/encoding=["']([^"']+)["']/);R&&(A.encoding=R[1]);let L=t.match(/standalone=["']([^"']+)["']/);return L&&(A.standalone=L[1]),A}static escapeXML(I){return I.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}static unescapeXML(I){return I.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}};var k_=class{constructor(){this.stage="tokenize";this.name="tokenize-processor"}async process(I){if(!I.xmlContent)throw new Error("TCX data cannot be empty");let _=J_.tokenizeXML(I.xmlContent);if(_.length===0)throw new Error("Not a valid TCX file");return I.tokens=_,I.stats.processedTokens=_.length,I}},z_=class{constructor(){this.stage="ast-generate";this.name="ast-generate-processor"}async process(I){let _=Date.now();if(!I.tokens)throw new Error("Tokens cannot be empty");let t=[],A,T=null;for(let R of I.tokens)if(R.type==="open"){let L={tag:R.tag,attributes:R.attributes||{},children:[]};A?T&&T.children?.push(L):A=L,t.push(L),T=L}else R.type==="text"&&T?T.value=R.value:R.type==="close"&&(t.pop(),T=t[t.length-1]||null);return I.ast=A,I.performance.astTime=Date.now()-_,I}},j_=class{constructor(I){this.getConverter=I;this.stage="convert";this.name="convert-processor"}async process(I){if(!I.ast)throw new Error("AST is empty, cannot convert");let _=this.findTCXRoot(I.ast);if(!_)throw new Error("Not a valid TCX file: TrainingCenterDatabase element not found");let t=this.convertAST(_,I);return I.result=t,I.stats.convertedElements=this.countElements(I.ast),I}findTCXRoot(I){if(I.tag==="TrainingCenterDatabase")return I;if(I.children)for(let _ of I.children){let t=this.findTCXRoot(_);if(t)return t}}convertAST(I,_){let t=this.getConverter(I.tag);return t?t.convert(I,_):this.genericConvert(I,_)}genericConvert(I,_){let t={};if(I.attributes&&Object.entries(I.attributes).forEach(([A,T])=>{t[A]=T}),I.value!==void 0)if(I.children&&I.children.length>0)t._value=I.value;else return I.value;return I.children&&I.children.forEach(A=>{let T=this.convertAST(A,_);t[A.tag]?(Array.isArray(t[A.tag])||(t[A.tag]=[t[A.tag]]),t[A.tag].push(T)):t[A.tag]=T}),t}countElements(I){let _=1;if(I.children)for(let t of I.children)_+=this.countElements(t);return _}},y_=class{constructor(){this.stage="complete";this.name="complete-processor"}async process(I){if(!I.result)throw new Error("No conversion result found");let _=Date.now(),t=_-I.performance.startTime;return I.performance.endTime=_,I.performance.processingTime=t,I.metadata.set("performance",{processingTime:t,processedTokens:I.stats.processedTokens,convertedElements:I.stats.convertedElements}),I}};var Z_=class{constructor(){this.converterPlugins=new Map;this.registeredPlugins=new Set;this.middlewarePlugins=[];this.processors=[];this.initialized=!1;this.defaultConvertersRegistered=!1;this.initializePipeline()}initializePipeline(){this.processors=[new k_,new z_,new j_(I=>this.getConverter(I)),new y_]}async registerDefaultConverters(){if(this.defaultConvertersRegistered)return;let I=[new X_,new P_,new v_,new s_,new Y_,new b_,new N_,new $_,new Q_];for(let _ of I)_.supportedTags?.forEach(t=>{this.addConverterForTag(t,_)}),this.registeredPlugins.add(_.name);this.defaultConvertersRegistered=!0}addConverterForTag(I,_){this.converterPlugins.has(I)||this.converterPlugins.set(I,[]);let t=this.converterPlugins.get(I);t.push(_),t.sort((A,T)=>(A.priority||100)-(T.priority||100))}async registerConverter(I){if(this.registeredPlugins.has(I.name))throw new Error(`Converter plugin ${I.name} already exists`);I.supportedTags?.forEach(_=>{this.addConverterForTag(_,I)}),this.registeredPlugins.add(I.name)}async registerMiddleware(I){let _=this.middlewarePlugins.findIndex(t=>t.name===I.name);_!==-1?this.middlewarePlugins[_]=I:this.middlewarePlugins.push(I)}getConverter(I){let _=this.converterPlugins.get(I);return _&&_.length>0?_[0]:void 0}getAllConverters(I){return this.converterPlugins.get(I)||[]}unregisterConverter(I){let _;for(let[t,A]of this.converterPlugins){let T=A.findIndex(R=>R.name===I);T!==-1&&(_=A[T],A.splice(T,1),A.length===0&&this.converterPlugins.delete(t))}_&&this.registeredPlugins.delete(I)}unregisterMiddleware(I){let _=this.middlewarePlugins.findIndex(t=>t.name===I);_!==-1&&this.middlewarePlugins.splice(_,1)}async initialize(){if(this.initialized)return;await this.registerDefaultConverters();let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.initialize?.(I);this.initialized=!0}async destroy(){if(!this.initialized)return;let I=this.createContext(),_=[...new Map([...Array.from(this.converterPlugins.values()).flat(),...this.middlewarePlugins].map(t=>[t.name,t])).values()];for(let t of _)await t.destroy?.(I);this.initialized=!1}createContext(){return{metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},performance:{startTime:Date.now()}}}async executeMiddlewareHook(I,_,t){let A=_;for(let T of this.middlewarePlugins){let R=T[I];if(R)try{A=await R.call(T,A,t)||A}catch(L){t.errors.push(L),await T.onError?.(L,t)}}return A}async parseByBuffer(I){await this.initialize();let _=this.createContext();_.rawData=I,_.xmlContent=I.toString("utf-8"),_.metadata.set("decoder",this);for(let t of this.processors)try{switch(_=await t.process(_),t.stage){case"tokenize":_.tokens&&(_.tokens=await this.executeMiddlewareHook("onTokenize",_.tokens,_));break;case"ast-generate":_.ast&&(_.ast=await this.executeMiddlewareHook("onAstGenerate",_.ast,_));break;case"convert":_.result&&(_.result=await this.executeMiddlewareHook("onConvert",_.result,_));break;case"complete":_.result&&(_.result=await this.executeMiddlewareHook("onComplete",_.result,_));break}}catch(A){_.errors.push(A);for(let T of this.middlewarePlugins)await T.onError?.(A,_);throw new Error(`TCX pipeline stage "${t.stage}" failed: ${A.message}`)}return _.result}convertExtensions(I){let _={},{attributes:t,tag:A,value:T}=I;if(t&&Object.entries(t).forEach(([R,L])=>{_[R]=L}),I?.children?.length)I.children?.forEach(R=>{_[R.tag]=this.convertExtensions(R)});else if(T!==void 0)return T;return _}async parserByBuffer(I){return this.parseByBuffer(I)}async parseByString(I){let _=Buffer.from(I,"utf-8");return this.parseByBuffer(_)}};import YI from"dayjs";import Gt from"dayjs/plugin/utc.js";YI.extend(Gt);var q_=class{constructor(I={}){this.compact=I.compact??!0}async encode(I){let _=this.buildTCXXML(I);return Buffer.from(_,"utf-8")}encodeToString(I){return this.buildTCXXML(I)}buildTCXXML(I){let _=this.buildXMLHeader(I),t=this.buildTCXContent(I),T=`${_}${t}
14
+ </TrainingCenterDatabase>`;return this.compact?this.compressXML(T):T}compressXML(I){return I.replace(/>\s+</g,"><").replace(/^\s+|\s+$/gm,"").replace(/\s+/g," ").trim()}buildXMLHeader(I){let _=I.version||"1.0",t=I.creator||"trackswap",A=I.xmlns||"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2",T=I["xmlns:xsi"]||"http://www.w3.org/2001/XMLSchema-instance",R=I["xsi:schemaLocation"]||"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd";return['<?xml version="1.0" encoding="UTF-8"?>',`<TrainingCenterDatabase version="${this.escapeXMLAttribute(_)}"`,` creator="${this.escapeXMLAttribute(t)}"`,` xmlns="${this.escapeXMLAttribute(A)}"`,` xmlns:xsi="${this.escapeXMLAttribute(T)}"`,` xsi:schemaLocation="${this.escapeXMLAttribute(R)}">`].join(`
15
+ `)}buildTCXContent(I){let _=[];return I.Folders&&_.push(this.buildFolders(I.Folders)),I.Activities&&_.push(this.buildActivities(I.Activities)),I.Workouts&&_.push(this.buildWorkouts(I.Workouts)),I.Courses&&_.push(this.buildCourses(I.Courses)),I.Author&&_.push(this.buildAuthor(I.Author)),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.join(`
16
+ `)}buildFolders(I){let _=["<Folders>"];return I.History&&_.push(this.buildHistory(I.History)),I.Workouts&&_.push(this.buildWorkouts(I.Workouts)),I.Courses,_.push("</Folders>"),_.join(`
17
+ `)}buildHistory(I){let _=["<History>"];return I.Running&&_.push(`<Running>${this.buildHistoryFolder(I.Running)}</Running>`),I.Biking&&_.push(`<Biking>${this.buildHistoryFolder(I.Biking)}</Biking>`),I.Other&&_.push(`<Other>${this.buildHistoryFolder(I.Other)}</Other>`),I.MultiActivity&&_.push(`<MultiActivity>${this.buildHistoryFolder(I.MultiActivity)}</MultiActivity>`),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.push("</History>"),_.join(`
18
+ `)}buildHistoryFolder(I){return""}buildActivities(I){let _=["<Activities>"];return I.Activity&&I.Activity.forEach(t=>{_.push(this.buildActivity(t))}),I.MultiActivitySession&&I.MultiActivitySession.forEach(t=>{_.push(this.buildMultiActivitySession(t))}),_.push("</Activities>"),_.join(`
19
+ `)}buildActivity(I){let t=[`<Activity Sport="${I.Sport||"Other"}">`];return t.push(`<Id>${this.formatTime(I.Id)}</Id>`),I.Lap&&I.Lap.length>0&&I.Lap.forEach(A=>{t.push(this.buildActivityLap(A))}),this.addOptionalElement(t,"Notes",I.Notes),I.Training,I.Creator,I.Extensions&&t.push(this.buildExtensions(I.Extensions)),t.push("</Activity>"),t.join(`
20
+ `)}buildActivityLap(I){let t=[`<Lap${I.StartTime?` StartTime="${this.escapeXMLAttribute(this.formatTime(I.StartTime))}"`:""}>`];return this.addOptionalNumericElement(t,"TotalTimeSeconds",I.TotalTimeSeconds),this.addOptionalNumericElement(t,"DistanceMeters",I.DistanceMeters),this.addOptionalNumericElement(t,"MaximumSpeed",I.MaximumSpeed),this.addOptionalNumericElement(t,"Calories",I.Calories),I.AverageHeartRateBpm&&t.push(`<AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${I.AverageHeartRateBpm}</Value></AverageHeartRateBpm>`),I.MaximumHeartRateBpm&&t.push(`<MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${I.MaximumHeartRateBpm}</Value></MaximumHeartRateBpm>`),this.addOptionalElement(t,"Intensity",I.Intensity),I.Cadence&&t.push(this.buildCadence(I.Cadence)),this.addOptionalElement(t,"TriggerMethod",I.TriggerMethod),I.Track&&I.Track.forEach(A=>{t.push(this.buildTrack(A))}),this.addOptionalElement(t,"Notes",I.Notes),I.Extensions&&t.push(this.buildExtensions(I.Extensions)),t.push("</Lap>"),t.join(`
21
+ `)}buildTrack(I){let _=["<Track>"];return I.Trackpoint&&I.Trackpoint.forEach(t=>{_.push(this.buildTrackpoint(t))}),_.push("</Track>"),_.join(`
22
+ `)}buildTrackpoint(I){let _=["<Trackpoint>"];return I.Time?(_.push(`<Time>${this.formatTime(I.Time)}</Time>`),I.Position&&_.push(this.buildPosition(I.Position)),this.addOptionalNumericElement(_,"AltitudeMeters",I.AltitudeMeters),this.addOptionalNumericElement(_,"DistanceMeters",I.DistanceMeters),I.HeartRateBpm&&_.push(`<HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"><Value>${I.HeartRateBpm}</Value></HeartRateBpm>`),I.Cadence&&_.push(this.buildCadence(I.Cadence)),this.addOptionalElement(_,"SensorState",I.SensorState),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.push("</Trackpoint>"),_.join(`
23
+ `)):""}buildGeoCoords(I){let _=[];return I?.LatitudeDegrees&&_.push(`<LatitudeDegrees>${this.formatCoordinate(parseFloat(I.LatitudeDegrees))}</LatitudeDegrees>`),I?.LongitudeDegrees&&_.push(`<LongitudeDegrees>${this.formatCoordinate(parseFloat(I.LongitudeDegrees))}</LongitudeDegrees>`),_.join("")}wrapGeoTag(I,_){if(!_)return"";let t=this.buildGeoCoords(_);return t?`<${I}>${t}</${I}>`:""}buildPosition(I){let _=this.buildGeoCoords(I);return _?`<Position>${_}</Position>`:""}buildCadence(I){return`<Cadence><Low>${I.Low}</Low><High>${I.High}</High></Cadence>`}buildMultiActivitySession(I){let _=["<MultiActivitySession>"];return I.Id&&_.push(`<Id>${this.formatTime(I.Id)}</Id>`),I.FirstActivity&&_.push(this.buildFirstActivity(I.FirstActivity)),I.NextActivity&&I.NextActivity.forEach(t=>{_.push(this.buildNextActivity(t))}),this.addOptionalElement(_,"Notes",I.Notes),_.push("</MultiActivitySession>"),_.join(`
24
+ `)}buildFirstActivity(I){let _=["<FirstActivity>"];return I.Activity&&_.push(this.buildActivity(I.Activity)),_.push("</FirstActivity>"),_.join(`
25
+ `)}buildNextActivity(I){let _=["<NextActivity>"];return I.Transition&&_.push(`<Transition>${this.buildActivityLap(I.Transition)}</Transition>`),I.Activity&&_.push(this.buildActivity(I.Activity)),_.push("</NextActivity>"),_.join(`
26
+ `)}buildWorkouts(I){return"<Workouts></Workouts>"}buildCourses(I){let _=["<Courses>"];return I.Course?.length&&I.Course.forEach(t=>{_.push(this.buildCourseElement(t))}),_.push("</Courses>"),_.join(`
27
+ `)}buildCourseElement(I){let _=["<Course>"];return this.addOptionalElement(_,"Name",I.Name),this.addOptionalElement(_,"Notes",I.Notes),I.Lap?.length&&I.Lap.forEach(t=>{_.push(this.buildCourseLap(t))}),I.Track?.length&&I.Track.forEach(t=>{_.push(this.buildTrack(t))}),I.CoursePoint?.length&&I.CoursePoint.forEach(t=>{_.push(this.buildCoursePoint(t))}),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.push("</Course>"),_.join(`
28
+ `)}buildCourseLap(I){let _=["<Lap>"];this.addOptionalNumericElement(_,"TotalTimeSeconds",I.TotalTimeSeconds),this.addOptionalNumericElement(_,"DistanceMeters",I.DistanceMeters),_.push(this.wrapGeoTag("BeginPosition",I.BeginPosition)),_.push(this.wrapGeoTag("EndPosition",I.EndPosition)),this.addOptionalNumericElement(_,"BeginAltitudeMeters",I.BeginAltitudeMeters),this.addOptionalNumericElement(_,"EndAltitudeMeters",I.EndAltitudeMeters);let t=I;return t.Track?.length&&t.Track.forEach(A=>{_.push(this.buildTrack(A))}),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.push("</Lap>"),_.join(`
29
+ `)}buildCoursePoint(I){let _=["<CoursePoint>"];return this.addOptionalElement(_,"Name",I.Name),I.Time!==void 0&&I.Time!==null&&_.push(`<Time>${I.Time}</Time>`),I.Position&&_.push(this.buildPosition(I.Position)),this.addOptionalNumericElement(_,"AltitudeMeters",I.AltitudeMeters),this.addOptionalElement(_,"PointType",I.PointType),this.addOptionalElement(_,"Notes",I.Notes),I.Extensions&&_.push(this.buildExtensions(I.Extensions)),_.push("</CoursePoint>"),_.join("")}buildAuthor(I){let _=["<Author>"];return this.addOptionalElement(_,"Name",I.Name),_.push("</Author>"),_.join("")}buildExtensions(I){let _=this.buildExtensionContent(I);return _?`<Extensions>${_}</Extensions>`:""}buildExtensionContent(I){return Object.entries(I).filter(([_])=>!_.startsWith("xmlns")).map(([_,t])=>{if(t&&typeof t=="object"){let A=this.buildExtensionContent(t);return`<${_}>${A}</${_}>`}else if(t!=null)return`<${_}>${this.escapeXML(String(t))}</${_}>`;return""}).filter(_=>_).join("")}formatTime(I){let _=YI(I);if(!_.isValid())throw new Error(`Cannot encode invalid TCX timestamp: ${String(I)}`);return _.toISOString()}addOptionalElement(I,_,t,A){if(t!=null&&t!==""){let T=A?A(t):this.escapeXML(t);I.push(`<${_}>${T}</${_}>`)}}addOptionalNumericElement(I,_,t){t!=null&&!isNaN(t)&&I.push(`<${_}>${t}</${_}>`)}isValidCoordinate(I,_){return I!=null&&_!==void 0&&_!==null&&!isNaN(I)&&!isNaN(_)}formatCoordinate(I){return this.roundTo(I,6).toString()}roundTo(I,_){let t=Math.pow(10,_);return Math.round(I*t)/t}escapeXML(I){return I.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeXMLAttribute(I){return typeof I!="string"?String(I||""):I.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;").replace(/\n/g,"&#10;").replace(/\t/g,"&#9;")}deepClone(I){if(I===null||typeof I!="object")return I;if(I instanceof Date)return new Date(I.getTime());if(Array.isArray(I))return I.map(t=>this.deepClone(t));let _={};for(let t in I)Object.prototype.hasOwnProperty.call(I,t)&&(_[t]=this.deepClone(I[t]));return _}encoder(I){return this.encode(I)}};import gt from"dayjs";var i=class extends z{convertPoints(I){return I.map(_=>this.convertPoint(_)).filter(_=>_!==void 0)}convertTime(I){if(!I)return;if(typeof I=="number")return I;let _=gt(I);return _.isValid()?_.valueOf():void 0}},r=class{constructor(){this.version="1.0.0";this.priority=100}supports(I){return this.supportedTags.includes(I)}async initialize(I){I.metadata.set(`plugin:${this.name}:initialized`,!0)}async destroy(I){I.metadata.delete(`plugin:${this.name}:initialized`)}async validate(I){return!0}convertTimeToDate(I){return I?new Date(I):new Date}convertTimeToString(I){return this.convertTimeToDate(I).toISOString()}ensureValidCoordinates(I,_){return I>=-90&&I<=90&&_>=-180&&_<=180}round(I,_=6){let t=Math.pow(10,_);return Math.round(I*t)/t}};var bI={heartrate:"heartRate","gpxtpx:hr":"heartRate","ns3:hr":"heartRate","gpxdata:hr":"heartRate","gpxdata:cadence":"cadence","gpxtpx:cad":"cadence","ns3:cad":"cadence",cadence:"cadence","gpxtpx:speed":"speed","ns3:speed":"speed",speed:"speed",power:"power","gpxdata:power":"power","gpxpx:PowerInWatts":"power",PowerInWatts:"power","gpxtpx:temp":"temperature","gpxtpx:wtemp":"wtemp","gpxtpx:atemp":"atemp","gpxx:Temperature":"temperature","gpxx:Depth":"depth"},NI=n=>n*(180/Math.pow(2,31)),$I=2147483647;function $(n,I=6){if(n==null)return;let _=typeof n=="number"?n:Number(n);if(!Number.isFinite(_)||_===$I)return;let t=NI(_),A=Math.pow(10,I);return Math.round(t*A)/A}import i_ from"dayjs";import u_ from"dayjs";import{getPreciseDistance as lt}from"geolib";var j=class{calculateRecordsAggMetrics(I){if(!I||I.length===0)return;let _={records:this.preprocessRecords(I)};for(let t=0;t<_.records.length;t++){let A=_.records[t];if(!(A.positionLat==null||A.positionLong==null||!Number.isFinite(A.positionLat)||!Number.isFinite(A.positionLong))){if(_.startPositionLat==null&&(_.startPositionLat=A.positionLat),_.startPositionLong==null&&(_.startPositionLong=A.positionLong),_.endPositionLat=A.positionLat,_.endPositionLong=A.positionLong,_.timestamp=A.timestamp,_?.startTime||(_.startTime=A.timestamp),_.endTime=A.timestamp,_.totalDistance=A.distance,_.totalElapsedTime=u_(A.timestamp).diff(u_(_.startTime),"second"),A?.speed&&(_.avgSpeed=_.avgSpeed?(_.avgSpeed+A.speed)/2:A.speed,_.maxSpeed=Math.max(_.maxSpeed||0,A.speed)),A?.heartRate&&(_.maxHeartRate=Math.max(_.maxHeartRate||0,A.heartRate),_.minHeartRate=Math.min(_.minHeartRate||A.heartRate,A.heartRate),_.avgHeartRate?_.avgHeartRate=(_.avgHeartRate+A.heartRate)/2:_.avgHeartRate=A.heartRate),A?.altitude&&(_.maxAltitude=Math.max(_.maxAltitude||0,A.altitude),_.minAltitude=Math.min(_.minAltitude||A.altitude,A.altitude),_.avgAltitude=_.avgAltitude?(_.avgAltitude+A.altitude)/2:A.altitude,t>0&&I[t-1].altitude)){let T=this.calculateElevationChanges(I[t-1],A);_.totalAscent=(_.totalAscent||0)+T.ascent,_.totalDescent=(_.totalDescent||0)+T.descent}if(A?.cadence&&(_.maxCadence=Math.max(_.maxCadence||0,A.cadence),_.avgCadence?_.avgCadence=(_.avgCadence+A.cadence)/2:_.avgCadence=A.cadence),A?.power){_.maxPower=Math.max(_.maxPower||0,A.power),_.avgPower?_.avgPower=(_.avgPower+A.power)/2:_.avgPower=A.power;let T=this.calculateAccumulatedPower(t>0?I[t-1]:A,A,_.totalWork||0);_.totalWork=T.newAccumulatedWork,_.normalizedPower=void 0}A?.temperature&&(_.avgTemperature?_.avgTemperature=(_.avgTemperature+A.temperature)/2:_.avgTemperature=A.temperature,_.maxTemperature=Math.max(_.maxTemperature||0,A.temperature),_.minTemperature=Math.min(_.minTemperature||A.temperature,A.temperature))}}return _}calculateLapAggMetrics(I){if(!I||I.length===0)return;let _={laps:I,timestamp:I[0]?.timestamp||new Date};for(let t=0;t<I.length;t++){let A=I[t];A.startPositionLat&&A.startPositionLong&&!_?.startPositionLat&&!_?.startPositionLong&&(_.startPositionLat=A.startPositionLat,_.startPositionLong=A.startPositionLong),A.endPositionLat&&A.endPositionLong&&(_.endPositionLat=A.endPositionLat,_.endPositionLong=A.endPositionLong),A.startTime&&!_?.startTime&&(_.startTime=A.startTime),A.endTime&&(_.endTime=A.endTime),_.timestamp=A.timestamp||A.endTime||_.timestamp,A.totalDistance&&(_.totalDistance=(_.totalDistance||0)+A.totalDistance),A.totalElapsedTime&&(_.totalElapsedTime=(_.totalElapsedTime||0)+A.totalElapsedTime),A.totalMovingTime&&(_.totalMovingTime=(_.totalMovingTime||0)+A.totalMovingTime),A.totalTimerTime&&(_.totalTimerTime=(_.totalTimerTime||0)+A.totalTimerTime),A.maxSpeed&&(_.maxSpeed=Math.max(_.maxSpeed||0,A.maxSpeed)),A.avgSpeed&&(_.avgSpeed?_.avgSpeed=(_.avgSpeed+A.avgSpeed)/2:_.avgSpeed=A.avgSpeed),A.maxHeartRate&&(_.maxHeartRate=Math.max(_.maxHeartRate||0,A.maxHeartRate)),A.minHeartRate&&(_.minHeartRate=_.minHeartRate?Math.min(_.minHeartRate,A.minHeartRate):A.minHeartRate),A.avgHeartRate&&(_.avgHeartRate?_.avgHeartRate=(_.avgHeartRate+A.avgHeartRate)/2:_.avgHeartRate=A.avgHeartRate),A.maxAltitude&&(_.maxAltitude=Math.max(_.maxAltitude||0,A.maxAltitude)),A.minAltitude&&(_.minAltitude=_.minAltitude?Math.min(_.minAltitude,A.minAltitude):A.minAltitude),A.avgAltitude&&(_.avgAltitude?_.avgAltitude=(_.avgAltitude+A.avgAltitude)/2:_.avgAltitude=A.avgAltitude),A.totalAscent&&(_.totalAscent=(_.totalAscent||0)+A.totalAscent),A.totalDescent&&(_.totalDescent=(_.totalDescent||0)+A.totalDescent),A.maxCadence&&(_.maxCadence=Math.max(_.maxCadence||0,A.maxCadence)),A.avgCadence&&(_.avgCadence?_.avgCadence=(_.avgCadence+A.avgCadence)/2:_.avgCadence=A.avgCadence),A.maxPower&&(_.maxPower=Math.max(_.maxPower||0,A.maxPower)),A.avgPower&&(_.avgPower?_.avgPower=(_.avgPower+A.avgPower)/2:_.avgPower=A.avgPower),A.totalWork&&(_.totalWork=(_.totalWork||0)+A.totalWork),A.maxTemperature&&(_.maxTemperature=Math.max(_.maxTemperature||0,A.maxTemperature)),A.minTemperature&&(_.minTemperature=_.minTemperature?Math.min(_.minTemperature,A.minTemperature):A.minTemperature),A.avgTemperature&&(_.avgTemperature?_.avgTemperature=(_.avgTemperature+A.avgTemperature)/2:_.avgTemperature=A.avgTemperature)}return _}preprocessRecords(I){if(!I||I.length===0)return I;let _=I.filter(R=>R.timestamp).sort((R,L)=>R.timestamp.valueOf()-L.timestamp.valueOf()),t=0,A=0,T=[];for(let R=0;R<_.length;R++){let L=_[R],O={...L};if(R>0){let D=this.calculatePointDistanceByPosition(_[R-1],O)||0;if(O.distance||(A+=D,O.distance=A),L.speed||(O.speed=this.calculateInstantSpeed(_[R-1],O,D)),L.power){let d=this.calculateAccumulatedPower(_[R-1],O,t);O.accumulatedPower=d.accumulatedPower,t=d.newAccumulatedWork}}T.push(O)}return T}calculatePointDistanceByPosition(I,_){if(!(I.positionLat==null||I.positionLong==null||_.positionLat==null||_.positionLong==null||!Number.isFinite(I.positionLat)||!Number.isFinite(I.positionLong)||!Number.isFinite(_.positionLat)||!Number.isFinite(_.positionLong)))try{return lt({latitude:I.positionLat,longitude:I.positionLong},{latitude:_.positionLat,longitude:_.positionLong})}catch{return}}calculateInstantSpeed(I,_,t){if(!I.timestamp||!_.timestamp||!t)return;let A=(u_(_.timestamp).valueOf()-u_(I.timestamp).valueOf())/1e3;if(!(A<=0))return t/A}calculateAccumulatedPower(I,_,t){if(I.power===void 0||_.power===void 0||!I.timestamp||!_.timestamp)return{accumulatedPower:t,newAccumulatedWork:t};let A=_.timestamp?.valueOf()-I.timestamp?.valueOf();if(A<=0)return{accumulatedPower:t,newAccumulatedWork:t};let R=(I.power+_.power)/2*A,L=t+R;return{accumulatedPower:L,newAccumulatedWork:L}}calculateElevationChanges(I,_){let t=0,A=0;return _.altitude!==void 0&&I.altitude!==void 0&&(_.altitude>I.altitude?t=_.altitude-I.altitude:_.altitude<=I.altitude&&(A=I.altitude-_.altitude)),{ascent:t,descent:A}}};var r_=class extends i{constructor(){super(...arguments);this.name="gpx-to-activity-converter";this.supportedTags=["gpx"];this.convertGPXExtensions=_=>{let t={};return Object.entries(_).forEach(([A,T])=>{if(typeof T<"u"&&T!=="undefined"){let R=bI[A]||A;t[R]=this.autoNumber(T)}}),t}}convert(_,t){if(t.sourceFormat!=="gpx")return;let A=t.sourceData;return this.convertGPX(A)}convertGPX(_){let t={metadata:{originType:"GPX",fileType:"gpx"},activities:[]};return _.wpt&&(t.points=this.convertWpts2Points(_.wpt)),_.trk&&(t.activities=_.trk.map((A,T)=>this.convertTrk2Activity(A,T))),_.rte&&(t.routes=_.rte.map((A,T)=>this.convertRoute2Lap(A,T))),t}convertPoint(_,t,A){let{extensions:T}=_,R=T?this.convertGPXExtensions(T):{};return{lapIndex:A||0,index:t||0,positionLat:_?.lat,positionLong:_?.lon,altitude:_?.ele,heartRate:_?.heartRate,speed:_?.speed,power:_?.power,cadence:_?.cadence,course:_?.course,magvar:_?.magvar,geoidheight:_?.geoidheight,pointName:_?.name,comment:_?.cmt,description:_?.desc,source:_?.src,links:_?.link,symbol:_?.sym,pointType:_?.type,fix:_?.fix,sat:_?.sat,hdop:_?.hdop,vdop:_?.vdop,pdop:_?.pdop,ageofdgpsdata:_?.ageofdgpsdata,dgpsid:_?.dgpsid,gpxExtensions:_?.extensions,timestamp:_.time?i_(_.time).toDate():void 0,...R}}convertTrk2Activity(_,t){let A=_.trkseg?.map((R,L)=>this.convertTrackSeg2Lap(R,L))||[],T=new j().calculateLapAggMetrics(A);return{index:t,messageIndex:t,activityName:_.name,comment:_.cmt,description:_.desc,source:_.src,links:_.link,activityNumber:_.number,sport:_.type,gpxExtensions:_.extensions,laps:A,...T}}convertTrackSeg2Lap(_,t){return{...this.convertPoints2Lap(_.trkpt??[],t),gpxExtensions:_.extensions}}convertRoute2Lap(_,t){return{...this.convertPoints2Lap(_.rtept??[],t,_.name),comment:_.cmt,description:_.desc,source:_.src,links:_.link,routeNumber:_.number,routeType:_.type,gpxExtensions:_.extensions}}convertPoints2Lap(_,t,A){let T=_.map((d,U)=>this.convertPoint(d,U,t)),L=new j().calculateRecordsAggMetrics(T),O=new Map((L?.records??[]).map(d=>[d.index,d])),D=T.map(d=>O.get(d.index)??d);return{index:t,messageIndex:t,routeName:A,...L,records:D,lengths:[]}}convertWpts2Points(_){let t=[];for(let A=0;A<_.length;A++){let T=this.convertPoint(_[A],A);T&&t.push(T)}return t}autoNumber(_){return typeof _=="string"&&_.trim()!==""&&!isNaN(_)?Number(_):_}},m_=class extends i{constructor(){super(...arguments);this.name="fit-to-activity-converter";this.supportedTags=["fit"]}convert(_,t){if(t.sourceFormat!=="fit")return;let A=t.sourceData;return this.convertFIT(A)}convertFIT(_){let t={metadata:{originType:"FIT",fileType:"fit"},activities:[]};return _.sessionMesgs?.length?t.activities=_.sessionMesgs.map((A,T)=>({index:T,...A,startPositionLat:$(A?.startPositionLat),startPositionLong:$(A?.startPositionLong),endPositionLat:$(A?.endPositionLat),endPositionLong:$(A?.endPositionLong),laps:this.convertFITLap2Trackseg(A?.lapMesgs)})):_.courseMesgs?.length&&(t.routes=_.courseMesgs.map((A,T)=>({index:T,...A,records:this.convertLap2Points(A?.lapMesgs)}))),t}convertPoint(_,t,A){let{positionLong:T,positionLat:R,altitude:L,enhancedAltitude:O,enhancedSpeed:D,speed:d,...U}=_,W=R??_.position_lat,l=T??_.position_long;return{lapIndex:A||0,index:t||0,positionLat:$(W),positionLong:$(l),altitude:L,enhancedAltitude:O,speed:d,enhancedSpeed:D,...U}}convertFITLap2Trackseg(_){let t=[];if(!_?.length)return[];for(let A=0;A<_.length;A++){let T=_[A],R=T?.recordMesgs?.map((O,D)=>this.convertPoint(O,D,A)).filter(O=>O!==void 0)||[],L=T?.lengthMesgs?.map((O,D)=>({...O,index:D}))||[];t.push({index:A,...T,startPositionLat:$(T?.startPositionLat),startPositionLong:$(T?.startPositionLong),endPositionLat:$(T?.endPositionLat),endPositionLong:$(T?.endPositionLong),records:R,lengths:L})}return t}convertLap2Points(_){let t=[];if(!_?.length)return[];for(let A=0;A<_.length;A++){let R=_[A].recordMesgs?.map((L,O)=>this.convertPoint(L,O,A)).filter(L=>L!==void 0)||[];R.length&&(t=[...t,...R])}return t}},c_=class extends i{constructor(){super(...arguments);this.name="tcx-to-activity-converter";this.supportedTags=["tcx"]}convert(_,t){if(t.sourceFormat!=="tcx")return;let A=t.sourceData;return this.convertTCX(A)}convertTCX(_){let t={metadata:{originType:"TCX",fileType:"tcx"},activities:[]};_.Activities?.Activity?.length&&(t.activities=_.Activities.Activity.map((R,L)=>this.convertTCXActivityToActivity(R,L)));let A=_.Courses?.Course,T=A==null?[]:Array.isArray(A)?A:[A];return T.length&&(t.routes=T.map((R,L)=>this.convertTCXCourseToRoute(R,L))),t}convertTCXCourseToRoute(_,t){let A=[],T=0,R=M=>M==null?[]:Array.isArray(M)?M:[M],L=M=>{for(let V of M??[])for(let H of V.Trackpoint??[])H==null||H.Time===void 0||A.push(this.convertPoint(H,T++,t))};L(R(_.Track));let O=_.Lap==null?[]:Array.isArray(_.Lap)?_.Lap:[_.Lap];for(let M of O)L(R(M.Track));let D=A.length,d=A[0]?.timestamp!=null?i_(A[0].timestamp):i_("2000-01-01T00:00:00Z"),U=_.CoursePoint==null?[]:Array.isArray(_.CoursePoint)?_.CoursePoint:[_.CoursePoint];for(let M of U){let V=this.convertTCXCoursePointToRecord(M,D++,t,d);V&&A.push(V)}let W=new j,l=A.length>0?W.calculateRecordsAggMetrics(A):{records:A};return{index:t,messageIndex:t,routeName:_.Name,...l,records:l?.records??A,lengths:[]}}convertTCXCoursePointToRecord(_,t,A,T){let R=_.Position?.LatitudeDegrees?Number(_.Position.LatitudeDegrees):void 0,L=_.Position?.LongitudeDegrees?Number(_.Position.LongitudeDegrees):void 0;if(R==null&&L==null&&_.AltitudeMeters==null)return;let O=typeof _.Time=="number"&&Number.isFinite(_.Time)?T.add(_.Time,"second").toDate():T.add(t,"second").toDate();return{lapIndex:A,index:t,positionLat:R,positionLong:L,altitude:_.AltitudeMeters,timestamp:O}}convertTCXActivityToActivity(_,t){let A=_.Lap?.map((R,L)=>this.convertTCXLap2Lap(R,L))||[],T=new j().calculateLapAggMetrics(A);return{index:t,messageIndex:t,sport:_.Sport?.toLowerCase(),laps:A,...T}}convertTCXLap2Lap(_,t){let T=(_?.Track?.flatMap(O=>O.Trackpoint)||[])?.filter(O=>O!==void 0&&O.Time!==void 0).map((O,D)=>this.convertPoint(O,D))||[],L=new j().calculateRecordsAggMetrics(T);return{index:t,messageIndex:t,...L,records:L?.records||[],lengths:[]}}convertPoint(_,t,A){let{Position:T,Time:R,DistanceMeters:L,AltitudeMeters:O}=_;return{lapIndex:A||0,index:t||0,positionLat:T?.LatitudeDegrees?Number(T.LatitudeDegrees):void 0,positionLong:T?.LongitudeDegrees?Number(T.LongitudeDegrees):void 0,timestamp:i_(R).toDate(),distance:L,altitude:O}}};import Wt from"dayjs";var x_=class extends r{constructor(){super(...arguments);this.name="activity-to-gpx-encoder";this.supportedTags=["gpx"]}encode(_,t){if(t.targetFormat!=="gpx"||!_?.activities?.length&&!_?.routes?.length&&!_?.points?.length)return;let A=_.activities?.[0]?.timestamp??_.routes?.[0]?.records?.[0]?.timestamp??_.points?.[0]?.timestamp??new Date,T=this.countRecordsMissingGpxCoordinates(_),R={version:"1.1",creator:"TrackSwap",metadata:{time:A,...T>0?{desc:`TrackSwap: omitted ${T} trackpoint(s) without valid latitude/longitude.`}:{}}};return _.points?.length&&(R.wpt=this.convertRecords2Wpts(_.points)),_.routes?.length&&(R.rte=_.routes.map(L=>this.convertRoute2GPXRoute(L))),_.activities?.length&&(R.trk=_.activities.map(L=>this.convertActivity2GPXTrack(L))),R}hasValidGpxCoordinates(_){let t=_.positionLat,A=_.positionLong;return typeof t=="number"&&typeof A=="number"&&Number.isFinite(t)&&Number.isFinite(A)&&t>=-90&&t<=90&&A>=-180&&A<=180}countRecordsMissingGpxCoordinates(_){let t=0,A=T=>{for(let R of T??[])this.hasValidGpxCoordinates(R)||t++};A(_.points);for(let T of _.activities??[])for(let R of T.laps??[])A(R.records);for(let T of _.routes??[])A(T.records);return t}convertRecords2Wpts(_){return _?.filter(t=>this.hasValidGpxCoordinates(t)).map(t=>({lat:t?.positionLat,lon:t?.positionLong,ele:t?.altitude,time:t?.timestamp,speed:t?.speed,course:t?.course,magvar:t?.magvar,geoidheight:t?.geoidheight,name:t?.pointName,cmt:t?.comment,desc:t?.description,src:t?.source,link:t?.links,sym:t?.symbol,type:t?.pointType,fix:t?.fix,sat:t?.sat,hdop:t?.hdop,vdop:t?.vdop,pdop:t?.pdop,ageofdgpsdata:t?.ageofdgpsdata,dgpsid:t?.dgpsid,extensions:this.extractGPXExtensions(t)}))??[]}convertRoute2GPXRoute(_){return{name:_.routeName,cmt:_.comment,desc:_.description,src:_.source,link:_.links,number:_.routeNumber,type:_.routeType,extensions:_.gpxExtensions,rtept:_.records?this.convertRecords2Wpts(_.records):[]}}convertActivity2GPXTrack(_){return{name:_.activityName,cmt:_.comment,desc:_.description,src:_.source,link:_.links,number:_.activityNumber,type:_.sport,extensions:_.gpxExtensions,trkseg:_.laps?.map(t=>({trkpt:t.records?this.convertRecords2Wpts(t.records):[],extensions:t.gpxExtensions}))||[]}}extractGPXExtensions(_){let t={..._.gpxExtensions??{}},A={...t["gpxtpx:TrackPointExtension"]??{}};return typeof _?.heartRate<"u"&&(A["gpxtpx:hr"]=_.heartRate),typeof _?.cadence<"u"&&(A["gpxtpx:cad"]=_.cadence),typeof _?.speed<"u"&&(A["gpxtpx:speed"]=_.speed),typeof _?.temperature<"u"&&(A["gpxtpx:atemp"]=_.temperature),Object.keys(A).length>0&&(t["gpxtpx:TrackPointExtension"]=A),typeof _?.power<"u"&&(t["gpxpx:PowerExtension"]={"gpxpx:PowerInWatts":_.power}),Object.keys(t).length>0?t:void 0}},a_=class extends r{constructor(){super(...arguments);this.name="activity-to-fit-encoder";this.supportedTags=["fit"]}encode(_,t){if(t.targetFormat==="fit"){if(_?.activities?.length){let A={};return A.sessionMesgs=_.activities.map(T=>this.convertActivity2FITSession(T)),A}if(_?.routes?.length){let A={};return A.sessionMesgs=[this.convertRoutesToSyntheticSession(_.routes)],A}}}convertRoutesToSyntheticSession(_){let t=_.map(D=>this.convertLap2FITLap(D)),T=_.flatMap(D=>D.records??[]).filter(D=>D.timestamp!=null).sort((D,d)=>new Date(D.timestamp).getTime()-new Date(d.timestamp).getTime()),R=T[0]?.timestamp??new Date,L=T[T.length-1]?.timestamp??R,O=T.find(D=>D.positionLat!=null&&D.positionLong!=null&&Number.isFinite(D.positionLat)&&Number.isFinite(D.positionLong));return{messageIndex:0,timestamp:L,event:"session",eventType:"stop",startTime:R,startPositionLat:O?.positionLat,startPositionLong:O?.positionLong,sport:"generic",subSport:"generic",lapMesgs:t}}convertActivity2FITSession(_){return{..._,event:_?.event||"session",sport:_?.sport||"generic",lapMesgs:_.laps?.map(A=>this.convertLap2FITLap(A))||[]}}convertLap2FITLap(_){return{startTime:_.startTime,..._,recordMesgs:_.records?.map(A=>this.convertPoint2FITRecord(A))||[]}}convertPoint2FITRecord(_){return _}},e_=class extends r{constructor(){super(...arguments);this.name="sport-to-tcx-encoder";this.supportedTags=["tcx"]}encode(_,t){if(t.targetFormat!=="tcx")return;let A=!!_?.activities?.length,T=!!_?.routes?.length;if(!A&&!T)return;let R={version:"1.0",Author:{Name:"TrackSwap"}};return A&&(R.Activities={Activity:_.activities.map(L=>this.convertActivity2TCXActivity(L))}),T&&(R.Courses={Course:_.routes.map((L,O)=>this.convertRouteToTCXCourse(L,O))}),R}convertActivity2TCXActivity(_){if(!_.laps?.length)throw new Error("Cannot encode a TCX activity without laps");let t="Other",A=_.sport?.toLowerCase();return A==="running"&&(t="Running"),(A==="biking"||A==="cycling")&&(t="Biking"),{Id:this.validTimestamp(_.startTime??_.laps[0]?.startTime??_.laps[0]?.records?.[0]?.timestamp),Sport:t,Lap:_.laps.map(R=>this.convertLap2TCXLap(R))}}convertLap2TCXLap(_){let A={StartTime:this.validTimestamp(_.startTime??_.records?.[0]?.timestamp),TotalTimeSeconds:_.totalElapsedTime,DistanceMeters:_.totalDistance,MaximumSpeed:_.maxSpeed,Calories:_.totalCalories,AverageHeartRateBpm:_.avgHeartRate,MaximumHeartRateBpm:_.maxHeartRate,Intensity:"Active",TriggerMethod:"Manual",Track:_.records?[this.convertRecords2TCXTrack(_.records)]:[]};return(_.avgCadence!==void 0||_.maxCadence!==void 0)&&(A.Cadence={Low:_.avgCadence||0,High:_.maxCadence||0}),A}convertRecords2TCXTrack(_){return{Trackpoint:_.map(t=>this.convertPoint2TCXTrackpoint(t))}}convertPoint2TCXTrackpoint(_){let t={Time:this.validTimestamp(_.timestamp),Position:{LatitudeDegrees:_?.positionLat?.toString(),LongitudeDegrees:_?.positionLong?.toString()},AltitudeMeters:_.altitude,DistanceMeters:_.distance};return _.heartRate&&(t.HeartRateBpm=_.heartRate),_.cadence&&(t.Cadence={Low:_.cadence,High:_.cadence256||_.cadence}),_.power&&(t.Extensions={"ns3:TPX":{"ns3:Watts":_.power}}),t}validTimestamp(_){let t=Wt(_);if(!_||!t.isValid())throw new Error("Cannot encode TCX data without valid timestamps");return t.toISOString()}convertRouteToTCXCourse(_,t){return{Name:_.routeName??`Course_${t}`,Track:_.records?[this.convertRecords2TCXTrack(_.records)]:[]}}};var _I=class{constructor(){this.converters=new Map;this.encoders=new Map;this.registerDefaultConverters(),this.registerDefaultEncoders()}registerDefaultConverters(){this.registerConverter(new r_),this.registerConverter(new m_),this.registerConverter(new c_)}registerDefaultEncoders(){this.registerEncoder(new x_),this.registerEncoder(new a_),this.registerEncoder(new e_)}registerConverter(I){this.converters.set(I.name,I)}registerEncoder(I){this.encoders.set(I.name,I)}async convertToActivity(I,_){let t={metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},sourceFormat:_,sourceData:I,performance:{startTime:Date.now()}};try{let A=this.findConverter(_);if(!A)throw new Error(`No converter found for format "${_}"`);let T=Date.now(),R=A.convert(I,t);if(t.performance.convertTime=Date.now()-T,!R)throw new Error(`Converter "${A.name}" returned empty result`);let L=R;return t.result=L,t.performance.endTime=Date.now(),t.stats.endTime=Date.now(),L}catch(A){throw t.errors.push(A),A}}async encodeActivity(I,_){let t={metadata:new Map,errors:[],warnings:[],stats:{startTime:Date.now(),processedTokens:0,convertedElements:0},targetFormat:_,performance:{startTime:Date.now()}};try{let A=this.findEncoder(_);if(!A)throw new Error(`No encoder found for format "${_}"`);let T=Date.now(),R=A.encode(I,t);if(t.performance.encodeTime=Date.now()-T,!R)throw new Error(`Encoder "${A.name}" returned empty result`);return t.result=R,t.performance.endTime=Date.now(),t.stats.endTime=Date.now(),R}catch(A){throw t.errors.push(A),A}}findConverter(I){return Array.from(this.converters.values()).find(_=>_.supportedTags?.includes(I))}findEncoder(I){return Array.from(this.encoders.values()).find(_=>_.supportedTags?.includes(I))}async destroy(){this.converters.clear(),this.encoders.clear()}};var QI=8,Bt=".FIT";function Mt(n){return n.toString("utf8",0,Math.min(n.length,4096)).replace(/^\uFEFF/,"")}function Vt(n){if(n.length>=12&&n.toString("ascii",QI,QI+4)===Bt)return"fit";let I=Mt(n);if(/<gpx\b/i.test(I))return"gpx";if(/<TrainingCenterDatabase\b/i.test(I))return"tcx"}var c=class{constructor(I){this.activities=I}matches(I){return Vt(I)===this.format}},HI=class extends c{constructor(){super(...arguments);this.format="fit"}getDecoder(){return this.decoder??=new O_}getEncoder(){return this.encoder??=new D_}async decode(_,t){let A=await this.getDecoder().parseByBuffer(_,{userData:{fitDocumentOptions:t.fit??{}}});if(!A)throw new Error("FIT decoder returned an empty result");let T=A.fitDocumentMetadata?.detectedKinds??["unknown"],R=T.includes("activity")?await this.activities.convertToActivity(A,"fit"):void 0,L=A.healthDocument?.diagnostics??{parserVersion:e,messageCounts:A.fitDocumentMetadata?.messageCounts??{},recognizedMessageCounts:{},unknownMessageCounts:{},invalidValueCounts:{},warnings:[]},O=A.fileIdMesgs?.[0],D=O,d=A.fileCreatorMesgs?.[0];return{kinds:[...T],facets:{activity:R,health:A.healthDocument},native:A,metadata:{fileType:O?.type,manufacturer:O?.manufacturer,product:O?.garminProduct??O?.product,productName:typeof D?.productName=="string"?D.productName:void 0,serialNumber:O?.serialNumber===void 0?void 0:String(O.serialNumber),createdAt:O?.timeCreated?new Date(O.timeCreated):void 0,softwareVersion:d?.softwareVersion},fitDiagnostics:L,warnings:L.warnings.map(U=>U.message)}}async encodeActivity(_){let t=await this.activities.encodeActivity(_,"fit");return this.getEncoder().encode(t)}async encodeCourse(_){return Buffer.from(XI(MI(_)))}async dispose(){await this.decoder?.destroy()}},oI=class extends c{constructor(){super(...arguments);this.format="gpx"}getDecoder(){return this.decoder??=new w_}getEncoder(){return this.encoder??=new p_}async decode(_){let t=await this.getDecoder().parserByBuffer(_);if(!t)throw new Error("GPX decoder returned an empty result");let A=await this.activities.convertToActivity(t,"gpx"),T=[];return A.activities?.length&&T.push("activity"),A.routes?.length&&T.push("route"),A.points?.length&&T.push("waypoint"),T.length===0&&T.push("unknown"),{kinds:T,facets:{activity:A},native:t,metadata:{title:t.metadata?.name,creator:t.creator,createdAt:t.metadata?.time}}}async encodeActivity(_){let t=await this.activities.encodeActivity(_,"gpx");return this.getEncoder().encode(t)}async dispose(){await this.decoder?.destroy()}},CI=class extends c{constructor(){super(...arguments);this.format="tcx"}getDecoder(){return this.decoder??=new Z_}getEncoder(){return this.encoder??=new q_}async decode(_){let t=await this.getDecoder().parseByBuffer(_);if(!t)throw new Error("TCX decoder returned an empty result");let A=await this.activities.convertToActivity(t,"tcx");return{kinds:A.activities?.length?["activity"]:A.routes?.length?["course"]:["unknown"],facets:{activity:A},native:t,metadata:{creator:t.Author?.Name??t.creator}}}async encodeActivity(_){let t=await this.activities.encodeActivity(_,"tcx");return this.getEncoder().encode(t)}async dispose(){await this.decoder?.destroy()}};function JI(){let n=new _I;return{adapters:[new HI(n),new oI(n),new CI(n)],activities:n}}function kI(n){return n.format==="fit"&&"encodeCourse"in n}var II=class{constructor(I){this.adapters=new Map;for(let _ of I){if(this.adapters.has(_.format))throw new s("ADAPTER_CONFLICT",`Multiple adapters registered for format "${_.format}"`,{format:_.format});this.adapters.set(_.format,_)}}get(I){let _=this.adapters.get(I);if(!_)throw new s("FORMAT_UNSUPPORTED",`No adapter registered for format "${I}"`,{format:I});return _}detect(I){for(let _ of this.adapters.values())if(_.matches(I))return _.format;throw new s("FORMAT_UNKNOWN","Unable to detect input format")}async dispose(){await Promise.all([...this.adapters.values()].map(I=>I.dispose?.()))}};function UI(n){return typeof n=="string"?Buffer.from(n,"utf8"):Buffer.isBuffer(n)?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength)}function Kt(n){return typeof n=="string"||Buffer.isBuffer(n)||n instanceof Uint8Array}var tI=class{constructor(I={}){this.disposed=!1;let t=[...I.includeBuiltInAdapters===!1?[]:JI().adapters,...I.adapters??[]];this.registry=new II(t)}detect(I){return this.assertActive(),this.registry.detect(UI(I))}async decode(I,_={}){this.assertActive();let t=UI(I),A=_.format??this.registry.detect(t),T=this.registry.get(A),R=Date.now();try{let L=await T.decode(t,_);return{schemaVersion:"2",format:A,kinds:[...new Set(L.kinds)],source:{byteLength:t.byteLength},metadata:L.metadata??{},facets:L.facets,..._.includeNative?{native:L.native}:{},diagnostics:{durationMs:Date.now()-R,warnings:L.warnings??[],fit:L.fitDiagnostics}}}catch(L){throw x(L,"DECODE_FAILED",`Failed to decode ${A.toUpperCase()}`,A)}}async decodeActivity(I,_={}){let t=await this.decode(I,_);if(!t.facets.activity)throw new s("ACTIVITY_NOT_FOUND",`The ${t.format.toUpperCase()} document has no activity facet`,{format:t.format});return t.facets.activity}async encodeActivity(I,_){this.assertActive();try{return await this.registry.get(_.format).encodeActivity(I)}catch(t){throw x(t,"ENCODE_FAILED",`Failed to encode ${_.format.toUpperCase()}`,_.format)}}async transcode(I,_){this.assertActive();let t=UI(I),A=_.sourceFormat??this.registry.detect(t);if(A===_.format)return Buffer.from(t);let T=await this.decodeActivity(t,{format:A});return this.encodeActivity(T,{format:_.format})}async encodeCourse(I,_={}){this.assertActive();let t=Kt(I)?await this.decodeActivity(I,{format:_.sourceFormat}):I,A=this.registry.get("fit");if(!kI(A))throw new s("FORMAT_UNSUPPORTED","The registered FIT adapter does not support course encoding",{format:"fit"});try{return await A.encodeCourse(t)}catch(T){throw x(T,"ENCODE_FAILED","Failed to encode FIT course","fit")}}async dispose(){this.disposed||(this.disposed=!0,await this.registry.dispose())}assertActive(){if(this.disposed)throw new s("DISPOSED","TrackSwap instance is disposed")}};export{$I as FIT_SEMICIRCLE_INVALID_SINT32,e as TRACKSWAP_HEALTH_PARSER_VERSION,tI as TrackSwap,s as TrackSwapError,WI as buildHealthDocumentFromMessages,tI as default,lI as detectFITKinds,$ as normalizeFitSemicircleToDegrees,NI as semicirclesToDegrees};