@kymoscope/sdk 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/assets/{importer.worker-Cgz__4KO.js → importer.worker-C63-1oBd.js} +1 -1
  2. package/dist/assets/liveIngestWorker-DQYK0Xxv.js +1 -0
  3. package/dist/importers-IlQKVrkS.js +5 -0
  4. package/dist/{keys-CkI2qrI-.js → keys-BPymBse7.js} +3 -3
  5. package/dist/kymoscope-embed.js +85 -85
  6. package/dist/kymoscope-sdk.js +84 -86
  7. package/dist/types/engine/columns.d.ts +1 -10
  8. package/dist/types/engine/createEngine.d.ts +3 -13
  9. package/dist/types/engine/types.d.ts +2 -8
  10. package/dist/types/index.d.ts +6 -12
  11. package/dist/types/lib/cycles/evaluator.d.ts +1 -2
  12. package/dist/types/lib/duckdb/duckdbInstance.d.ts +0 -5
  13. package/dist/types/lib/live/blockWire.d.ts +1 -1
  14. package/dist/types/lib/live/chainWire.d.ts +67 -0
  15. package/dist/types/lib/live/crypto.d.ts +0 -3
  16. package/dist/types/lib/live/liveIngest.d.ts +9 -1
  17. package/dist/types/lib/live/publisher.d.ts +11 -1
  18. package/dist/types/lib/live/stream.d.ts +6 -0
  19. package/dist/types/lib/live/types.d.ts +5 -0
  20. package/dist/types/lib/live/wire.d.ts +2 -0
  21. package/dist/types/lib/recordings/export.d.ts +0 -1
  22. package/dist/types/lib/segments/liveAxis.d.ts +8 -40
  23. package/dist/types/lib/segments/rules.d.ts +3 -42
  24. package/dist/types/lib/workspaces/io.d.ts +0 -6
  25. package/dist/types/lib/yAxisTicks.d.ts +1 -1
  26. package/package.json +1 -1
  27. package/dist/assets/liveIngestWorker-BLPTEEc7.js +0 -1
  28. package/dist/importers-D_M42sqZ.js +0 -5
  29. package/dist/types/lib/data/historyDataSource.d.ts +0 -51
  30. package/dist/types/lib/historian/blockCache.d.ts +0 -32
  31. package/dist/types/lib/historian/export.d.ts +0 -31
  32. package/dist/types/lib/historian/khd1.d.ts +0 -41
  33. package/dist/types/lib/historian/parquet.d.ts +0 -21
  34. package/dist/types/lib/historian/reader.d.ts +0 -73
@@ -1 +0,0 @@
1
- const e=e=>e.startsWith(`eyJ`);function t(e){try{let t=e.split(`.`)[1]??``,n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((t.length+3)%4)),r=JSON.parse(n).exp;return typeof r==`number`?r:null}catch{return null}}function n(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function r(r,i,a,o){let s=null,c=null,l=null,u=!1,d=0,f=()=>{l&&=(clearTimeout(l),null)},p=(n,a)=>{f();let o=t(a);if(o===null)return;let c=e(a),d=c?Math.min(o,Date.now()/1e3+300):o,m=Math.min(Math.max((d-(c?90:30))*1e3-Date.now(),1e4),2**31-1);l=setTimeout(async()=>{l=null;let e=null;try{e=await r.getToken(i)}catch{e=null}if(!(u||s!==n||!e)){try{n.send(JSON.stringify({type:`auth`,token:e}))}catch{return}p(n,e)}},m)},m=()=>{if(u||c)return;let e=Math.min(3e4,2e3*2**d++)*(.75+Math.random()/2);c=setTimeout(()=>{c=null,h()},e)},h=async()=>{if(u)return;let e=null;try{e=await r.getToken(i)}catch{e=null}if(u)return;if(!e){o?.(`error`),m();return}let t=new WebSocket(n(r.url,i),[`kymoscope-live.v1`,`kymoscope-live.ack1`,`bearer.${e}`]);t.binaryType=`arraybuffer`,s=t;let c=e,l=0,h=setInterval(()=>{if(!(l===0||t.readyState!==1)){try{t.send(JSON.stringify({type:`ack`,b:l}))}catch{return}l=0}},1e3);t.onopen=()=>{o?.(`subscribed`),p(t,c)},t.onmessage=e=>{d=0,typeof e.data!=`string`&&(l+=e.data.byteLength,a(e.data))},t.onclose=()=>{clearInterval(h),s===t&&(s=null,f(),!u&&(o?.(`error`),m()))}};return h(),()=>{if(u=!0,c&&=(clearTimeout(c),null),f(),s){let e=s;s=null,e.close(1e3)}}}new TextEncoder;function i(e,t,n){let r=t,i=r+n,a=[],o=``;for(;r<i;){let t=e[r++];if(!(t&128))a.push(t);else if((t&224)==192){let n=e[r++]&63;a.push((t&31)<<6|n)}else if((t&240)==224){let n=e[r++]&63,i=e[r++]&63;a.push((t&31)<<12|n<<6|i)}else if((t&248)==240){let n=e[r++]&63,i=e[r++]&63,o=e[r++]&63,s=(t&7)<<18|n<<12|i<<6|o;s>65535&&(s-=65536,a.push(s>>>10&1023|55296),s=56320|s&1023),a.push(s)}else a.push(t);a.length>=4096&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const a=new TextDecoder;function o(e,t,n){let r=e.subarray(t,t+n);return a.decode(r)}function s(e,t,n){return n>200?o(e,t,n):i(e,t,n)}var c=class{type;data;constructor(e,t){this.type=e,this.data=t}},l=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,`name`,{configurable:!0,enumerable:!1,value:e.name})}};function u(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function d(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function f(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}function p({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183)if(t===0&&e<=4294967295){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),a=new DataView(i.buffer);return a.setUint32(0,t<<2|n&3),a.setUint32(4,r),i}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),u(r,4,e),n}}function m(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function h(e){return e instanceof Date?p(m(e)):null}function g(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let e=t.getUint32(0),n=t.getUint32(4);return{sec:(e&3)*4294967296+n,nsec:e>>>2}}case 12:return{sec:d(t,4),nsec:t.getUint32(0)};default:throw new l(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function _(e){let t=g(e);return new Date(t.sec*1e3+t.nsec/1e6)}const v={type:-1,encode:h,decode:_};var ee=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(v)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new c(-1-n,i)}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new c(n,i)}}return e instanceof c?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new c(t,e)}};function y(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function b(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):y(e)?new Uint8Array(e):Uint8Array.from(e)}function x(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var S=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];FIND_CHUNK:for(let i of r){let r=i.bytes;for(let i=0;i<n;i++)if(r[i]!==e[t+i])continue FIND_CHUNK;return i.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let a=i(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}};const C=`array`,w=`map_key`,T=`map_value`,E=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new l(`The type of key must be string or number but `+typeof e)};var D=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=C,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=w,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){return this.stackHeadPosition++,this.stackHeadPosition===this.stack.length&&this.stack.push({type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null}),this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw Error(`Invalid stack state. Released state is not on top of the stack.`);if(e.type===C){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===w||e.type===T){let t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}};const O=new DataView(new ArrayBuffer(0)),k=new Uint8Array(O.buffer);try{O.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw Error(`This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access`)}const A=RangeError(`Insufficient data`),j=new S;var M=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=O;bytes=k;headByte=-1;stack=new D;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??ee.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder===void 0?j:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??E}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){let t=b(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===-1&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=b(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(let r of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(r);try{n=this.doDecodeSync(),t=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:i,totalPos:a}=this;throw RangeError(`Insufficient data in parsing ${x(r)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,r=-1;for await(let i of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){DECODE:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue DECODE}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue DECODE}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(e===217){let e=this.lookU8();t=this.decodeString(e,1)}else if(e===218){let e=this.lookU16();t=this.decodeString(e,2)}else if(e===219){let e=this.lookU32();t=this.decodeString(e,4)}else if(e===220){let e=this.readU16();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===221){let e=this.readU32();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===222){let e=this.readU16();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===223){let e=this.readU32();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===196){let e=this.lookU8();t=this.decodeBinary(e,1)}else if(e===197){let e=this.lookU16();t=this.decodeBinary(e,2)}else if(e===198){let e=this.lookU32();t=this.decodeBinary(e,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let e=this.lookU8();t=this.decodeExtension(e,1)}else if(e===200){let e=this.lookU16();t=this.decodeExtension(e,2)}else if(e===201){let e=this.lookU32();t=this.decodeExtension(e,4)}else throw new l(`Unrecognized type byte: ${x(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===C)if(e.array[e.position]=t,e.position++,e.position===e.size)t=e.array,n.release(e);else continue DECODE;else if(e.type===w){if(t===`__proto__`)throw new l(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=T;continue DECODE}else if(e.map[e.key]=t,e.readCount++,e.readCount===e.size)t=e.map,n.release(e);else{e.key=null,e.type=w;continue DECODE}}return t}}readHeadByte(){return this.headByte===-1&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new l(`Unrecognized array type byte: ${x(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new l(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new l(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new l(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw A;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):s(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===w:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new l(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw A;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new l(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=f(this.view,this.pos);return this.pos+=8,e}readI64(){let e=d(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function N(e,t){return new M(t).decode(e)}function P(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}async function F(e,t,n,r){let i=await P().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}new TextEncoder().encode(`kymoscope-device-wrap-v1`),new TextEncoder().encode(`kymoscope-sender-bind-v1`);function I(e){let t=new Uint8Array(e),n=t.length>0&&t[0]&128?2:1;return t.length<n+12+16?null:{kind:t[0]&-129,keyId:n===2?t[1]:null,iv:t.subarray(n,n+12),ciphertext:t.subarray(n+12),aad:t.subarray(0,n)}}async function L(e,t){let n=I(t);if(!n)return null;let r=typeof e==`function`?await e(n.keyId):e;if(!r)return null;let i=await F(r,n.iv,n.ciphertext,n.aad);return{kind:n.kind,plaintext:i}}const R=e=>e+7&-8;function z(e){let t=e=>RangeError(`columns message: ${e}`);e.byteOffset%8!=0&&(e=e.slice());let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw t(`short`);if(n.getUint8(0)!==1)throw t(`version ${n.getUint8(0)}`);let r=n.getUint16(2,!0),i=n.getUint32(4,!0),a=new TextDecoder,o=[],s=8;for(let i=0;i<r;i++){if(s+3>e.byteLength)throw t(`short channel table`);let r=n.getUint8(s),i=n.getUint8(s+1),c=n.getUint8(s+2);if(s+=3,r!==4&&r!==8)throw t(`value size ${r}`);if(s+i+c>e.byteLength)throw t(`short channel table`);o.push({name:a.decode(e.subarray(s,s+i)),unit:a.decode(e.subarray(s+i,s+i+c)),size:r}),s+=i+c}if(s=R(s),s+R(i*8)+o.reduce((e,t)=>e+R(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=R(i*8);let u={},d={};for(let t of o)u[t.name]=t.size===4?new Float32Array(e.buffer,c+s,i):new Float64Array(e.buffer,c+s,i),t.unit&&(d[t.name]=t.unit),s+=R(i*t.size);return{t:l,columns:u,units:d}}function B(e){if(e.length<24||e[0]!==1||e[2]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=(e[1]&1)!=0,r=t.getUint16(16,!0),i=t.getUint16(18,!0);if(i===0||r>=i)return null;let a=24,o=``;if(n&&r===0){if(e.length<a+1||e.length<a+1+e[a])return null;o=new TextDecoder().decode(e.subarray(a+1,a+1+e[a])),a+=1+e[a]}return{key:n,last:(e[1]&2)!=0,t:t.getFloat64(4,!0),seq:t.getUint32(12,!0),fragIndex:r,fragCount:i,width:t.getUint16(20,!0),height:t.getUint16(22,!0),codec:o,payload:e.subarray(a)}}const V=(e,t)=>RangeError(`${e}: ${t}`);function H(e){if(e.byteLength<8)throw V(`block schema`,`short`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint8(0)!==2)throw V(`block schema`,`version ${t.getUint8(0)}`);let n=t.getUint16(2,!0),r=t.getUint32(4,!0),i=new TextDecoder(`utf-8`,{fatal:!0}),a=[],o=8;try{for(let r=0;r<n;r++){if(o+3>e.byteLength)throw V(`block schema`,`short channel table`);let n=t.getUint8(o),r=t.getUint8(o+1),s=t.getUint8(o+2);if(o+=3,n!==4&&n!==8)throw V(`block schema`,`value size ${n}`);if(o+r+s>e.byteLength)throw V(`block schema`,`short channel table`);a.push({name:i.decode(e.subarray(o,o+r)),unit:i.decode(e.subarray(o+r,o+r+s)),size:n}),o+=r+s}}catch(e){throw e instanceof RangeError?e:V(`block schema`,`invalid text`)}return{id:r,channels:a}}function U(e,t){if(e.byteLength<12)throw V(`last values`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==1)throw V(`last values`,`version ${n.getUint8(0)}`);let r=t.get(n.getUint32(4,!0));if(!r)return null;let i=n.getUint32(8,!0);if(i!==r.channels.length)throw V(`last values`,`channel count differs from its schema`);if(e.byteLength<12+16*i)throw V(`last values`,`short`);let a=[];for(let e=0;e<i;e++){let t=n.getFloat64(12+8*e,!0),o=n.getFloat64(12+8*(i+e),!0);Number.isFinite(t)&&Number.isFinite(o)&&a.push({name:r.channels[e].name,unit:r.channels[e].unit,t,v:o})}return a}async function W(e,t){let n=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`)).getReader(),r=new Uint8Array(t),i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+a.length>t)throw V(`block`,`body larger than its header says`);r.set(a,i),i+=a.length}}catch(e){throw await n.cancel().catch(()=>{}),e instanceof RangeError?e:V(`block`,`body is not valid deflate`)}if(i!==t)throw V(`block`,`body size mismatch`);return r}async function G(e,t){if(e.byteLength<20)throw V(`block`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==2)throw V(`block`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint16(2,!0),a=n.getUint32(4,!0),o=t.get(n.getUint32(8,!0));if(!o)return null;if(o.channels.length!==i)throw V(`block`,`channel count differs from its schema`);let s=n.getFloat64(12,!0),c=Math.max(0,a-1),l=4*c+o.channels.reduce((e,t)=>e+t.size*a,0);if(l>67108864)throw V(`block`,`too large`);let u;if(r&1)u=await W(e.subarray(20),l);else if(u=e.subarray(20),u.byteLength<l)throw V(`block`,`body size mismatch`);let d=new DataView(u.buffer,u.byteOffset,u.byteLength),f=new Float64Array(a),p=0;a&&(f[0]=s);for(let e=1;e<a;e++)p+=d.getInt32(4*(e-1),!0),f[e]=s+p/1e6;let m=4*c,h={},g={};for(let e of o.channels){let t=new Uint8Array(a*e.size);for(let n=0;n<e.size;n++)for(let r=0;r<a;r++)t[r*e.size+n]=u[m+n*a+r];h[e.name]=e.size===4?new Float32Array(t.buffer):new Float64Array(t.buffer),e.unit&&(g[e.name]=e.unit),m+=a*e.size}return{block:{t:f,columns:h,units:g},historical:(r&2)!=0}}function K(e,t){let n=new Map,r=Promise.resolve();return i=>{let a=L(e,i).catch(()=>null);r=r.then(async()=>{try{let e=await a;if(!e)return;if(e.kind===6){let n=B(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=H(e.plaintext);n.set(t.id,t)}else if(e.kind===7){let r=U(e.plaintext,n);r&&t({type:`last`,values:r})}else if(e.kind===4){let r=await G(e.plaintext,n);r&&!r.historical&&t({type:`columns`,block:r.block})}else if(e.kind===3)t({type:`columns`,block:z(e.plaintext)});else if(e.kind===2){let n=N(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})}}function q(e){if(e.type!==`columns`)return[];let t=new Set,n=e=>{ArrayBuffer.isView(e)&&Object.prototype.toString.call(e.buffer)===`[object ArrayBuffer]`&&t.add(e.buffer)};n(e.block.t);for(let t of Object.values(e.block.columns))n(t);return[...t]}function J(e,t=67108864){let n=0,r=0,i=0;return{emit(a){let o=q(a).reduce((e,t)=>e+t.byteLength,0);if(a.type===`columns`&&n>0&&n+o>t){r+=a.block.t.length,i+=a.block.t.length;return}a.type===`columns`&&i>0&&(e({type:`gap`,samples:i},0),i=0),n+=o,e(a,o)},ack(e){n=Math.max(0,n-e)},get dropped(){return r}}}let Y=1;const X=new Map,Z=(e,t)=>new Promise(n=>{let r=Y++;X.set(r,n),self.postMessage({type:`ask`,id:r,what:e,arg:t})});let Q=null;const $=J((e,t)=>self.postMessage({type:`decoded`,d:e,bytes:t},q(e)));self.onmessage=e=>{let t=e.data;if(t.type===`reply`){X.get(t.id)?.(t.value),X.delete(t.id);return}if(t.type===`ack`){$.ack(t.bytes);return}if(t.type===`stop`){Q?.(),Q=null,self.close();return}let n=new Map,i=K(t.key??(async e=>{let t=n.get(e);if(t)return t;let r=await Z(`key`,e);return r&&n.set(e,r),r}),$.emit);Q=r({url:t.url,getToken:()=>Z(`token`)},t.streamId,i,e=>self.postMessage({type:`status`,status:e}))};
@@ -1,5 +0,0 @@
1
- /*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
2
- import{At as e,Dt as t,Et as n,Ft as r,It as i,Lt as a,Mt as o,Nt as s,Ot as c,Pt as l,Rt as u,Tt as d,bt as f,c as p,d as m,f as h,jt as g,kt as _,m as v,o as y,p as b,s as x,t as S,v as ee,vt as C,y as w,yt as te,zt as T}from"./keys-CkI2qrI-.js";function E(e,t){return e.selection.find(e=>e.group===t)?.channels??[]}var ne=4096,re={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,exp:Math.exp,ln:Math.log,log:Math.log,log10:Math.log10,sqrt:Math.sqrt,abs:Math.abs,pow:Math.pow,min:Math.min,max:Math.max};function ie(e){if(e.length>ne)return null;let t=e.match(/\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|\*\*|[-+*/^(),]|\S/g)??[],n=0,r=()=>t[n],i=()=>{throw Error(`formula`)},a=e=>{t[n++]!==e&&i()},o=()=>{let e=s();for(;r()===`+`||r()===`-`;){let r=t[n++],i=e,a=s();e=r===`+`?e=>i(e)+a(e):e=>i(e)-a(e)}return e},s=()=>{let e=c();for(;r()===`*`||r()===`/`;){let r=t[n++],i=e,a=c();e=r===`*`?e=>i(e)*a(e):e=>i(e)/a(e)}return e},c=()=>{if(r()===`-`){n++;let e=c();return t=>-e(t)}return r()===`+`?(n++,c()):l()},l=()=>{let e=u();if(r()===`^`||r()===`**`){n++;let t=c();return n=>e(n)**t(n)}return e},u=()=>{let e=t[n++];if(e===void 0&&i(),e===`(`){let e=o();return a(`)`),e}if(/^[\d.]/.test(e)){let t=Number(e);return Number.isFinite(t)||i(),()=>t}if(e===`X`||e===`x`||e===`X1`)return e=>e;if(Object.hasOwn(re,e)){let t=re[e];a(`(`);let i=[o()];for(;r()===`,`;)n++,i.push(o());return a(`)`),i.length===1?e=>t(i[0](e)):e=>t(...i.map(t=>t(e)))}return i()};try{let e=o();return n===t.length?e:null}catch{return null}}var D={k:`id`};function ae(e,t){let{keys:n,vals:r}=e,i=n.length;if(i===0)return t;if(t<=n[0])return r[0];if(t>=n[i-1])return r[i-1];let a=0,o=i-1;for(;o-a>1;){let e=a+o>>1;n[e]<=t?a=e:o=e}return e.interp?r[a]+(r[o]-r[a])*(t-n[a])/(n[o]-n[a]):t-n[a]<=n[o]-t?r[a]:r[o]}function O(e,t){let n=t.length;switch(e.k){case`lin`:{let{a:r,b:i}=e;if(r===1&&i===0)return;for(let e=0;e<n;e++)t[e]=r*t[e]+i;return}case`rat`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e];t[e]=(r*n*n+i*n+a)/(o*n*n+s*n+c)}return}case`poly`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e]-s-c;t[e]=(i-o*n)/(a*n-r)}return}case`alg`:{let r=e.f;for(let e=0;e<n;e++)t[e]=r(t[e]);return}case`tab`:for(let r=0;r<n;r++)t[r]=ae(e,t[r]);return;case`rtv`:for(let r=0;r<n;r++){let n=t[r],i=e.def;for(let t=0;t<e.lo.length;t++)if(n>=e.lo[t]&&n<=e.hi[t]){i=e.vals[t];break}t[r]=i}return;default:return}}function oe(e,t){let n=Float64Array.of(t);return O(e,n),n[0]}var se=(e,t)=>e===null||typeof e==`string`?e:String(oe(e,t));function ce(e,t){let n=Array(t.length),r=e.ranges.every(e=>e.lo===e.hi)?new Map(e.ranges.map(e=>[e.lo,e.to])):null;for(let i=0;i<t.length;i++){let a=t[i];if(a!==a){n[i]=null;continue}let o=e.def;if(r){let e=r.get(a);e!==void 0&&(o=e)}else for(let t of e.ranges)if(a>=t.lo&&(e.int||t.lo===t.hi?a<=t.hi:a<t.hi)){o=t.to;break}n[i]=se(o,a)}return n}function le(e,t){let n=(e,t)=>({type:e,bigEndian:t,encoding:`latin1`});switch(e){case 0:return n(`uint`,!t);case 1:return n(`int`,!t);case 2:case 3:return n(`float`,!t);case 7:return n(`string`,!1);case 8:return n(`bytes`,!1);case 9:return n(`uint`,!0);case 10:return n(`int`,!0);case 11:case 12:return n(`float`,!0);case 13:return n(`uint`,!1);case 14:return n(`int`,!1);case 15:case 16:return n(`float`,!1);default:return null}}async function ue(e,t,n){let r=T(t).getUint16(24,!0)===0,i=async t=>{let n=T(await e.read(t,4)).getUint16(2,r),i=await e.read(t,n);return{id:s(i.subarray(0,2)),v:T(i),b:i,size:n}},a=(e,t)=>e.getUint32(t,r),o=(e,t)=>e.getUint16(t,r),c=(e,t)=>e.getFloat64(t,r),u=async e=>e?l((await i(e)).b.subarray(4),!0):``,d=[],f=new Set,p=e=>{if(f.has(e))throw Error(`This MDF file is damaged (its blocks link in a loop).`);f.add(e)},m=async(e,t)=>{if(!e)return{conv:D,unit:``};let{v:n,b:r}=await i(e),s=l(r.subarray(22,42),!0),d=o(n,42),f=o(n,44),p=e=>c(n,46+8*e);switch(d){case 0:return{conv:{k:`lin`,a:p(1),b:p(0)},unit:s};case 1:case 2:{let e=new Float64Array(f),t=new Float64Array(f);for(let n=0;n<f;n++)e[n]=p(2*n),t[n]=p(2*n+1);return{conv:{k:`tab`,keys:e,vals:t,interp:d===1},unit:s}}case 6:return{conv:{k:`poly`,p:[0,1,2,3,4,5].map(p)},unit:s};case 9:return{conv:{k:`rat`,p:[0,1,2,3,4,5].map(p)},unit:s};case 10:{let e=l(r.subarray(46,302),!0),t=ie(e);return{conv:t?{k:`alg`,f:t}:{k:`unsupported`,what:`the formula "${e}"`},unit:s}}case 11:return{conv:{k:`text`,ranges:Array.from({length:f},(e,t)=>{let i=46+40*t,a=c(n,i);return{lo:a,hi:a,to:l(r.subarray(i+8,i+40),!0)}}),def:null,int:t},unit:s};case 12:{let e=await Promise.all(Array.from({length:f},async(e,t)=>{let r=46+20*t;return{lo:c(n,r),hi:c(n,r+8),to:await u(a(n,r+16))}}));return{conv:{k:`text`,ranges:e.slice(1),def:e[0]?.to??null,int:t},unit:s}}case 65535:return{conv:D,unit:s};default:return{conv:{k:`unsupported`,what:`MDF3 conversion type ${d}`},unit:s}}},h=await i(64),g=null;if(h.size>=172&&(a(h.v,164)||a(h.v,168))){let e=a(h.v,168)*4294967296+a(h.v,164);g=new Date(e/1e6).toISOString()}else{let e=s(h.b.subarray(18,28)),t=s(h.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(g=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let _=[],v=0;for(let e=a(h.v,4),t=0;e;t++){p(e);let n=await i(e),s=o(n.v,22),c=[];for(let e=a(n.v,8);e;){p(e);let n=await i(e),f=[],h=null;for(let e=a(n.v,8);e;){p(e);let t=await i(e),n=l(t.b.subarray(26,58),!0),s=(t.size>=222?await u(a(t.v,218)):``)||n,c=le(o(t.v,190),r),g=o(t.v,186)+(t.size>=228?8*o(t.v,226):0);if(!c)d.push(`${s}: MDF3 data type ${o(t.v,190)} is not supported; skipped.`);else{let{conv:e,unit:n}=await m(a(t.v,8),c.type!==`float`),r={name:s,unit:n,kind:o(t.v,24)===1?`master`:`value`,...c,conv:e,sd:null,sdRecordId:null,byteOffset:g>>3,bitOffset:g&7,bitCount:o(t.v,188),invalBit:null,allInvalid:!1};r.kind===`master`&&!h?h=r:r.kind===`value`&&f.push(r)}e=a(t.v,4)}v++,c.push({name:await u(a(n.v,12))||`Group ${v}`,dg:t,recordId:o(n.v,16),recordIdSize:+(s>0),idTrailer:+(s===2),dataBytes:o(n.v,20),invalBytes:0,cycles:a(n.v,22),vlsdCg:!1,sorted:!0,master:h,channels:f,stream:[],busType:0,busEvent:!1}),e=a(n.v,4)}let f=c.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),h=[{offset:a(n.v,16),length:f,zip:null}];for(let e of c)e.stream=h,e.sorted=c.length===1,_.push(e);e=a(n.v,4)}return{version:`MDF ${n}`,startTime:g,groups:_,notes:d,meta:{}}}var de=`This MF4 is damaged (its blocks link in a loop).`;function k(e,t){if(e.seen.has(t))throw Error(de);e.seen.add(t)}async function A(e,t){let n=await e.read(t,24);if(n.length<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let r=T(n),i=s(n.subarray(0,4)),o=a(r,8),c=a(r,16);if(!i.startsWith(`##`)||o<24+8*c||o>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let l=await e.read(t,o);if(l.length<o)throw Error(`This MF4 is damaged (the block at byte ${t} runs past the end of the file).`);let u=T(l),d=[];for(let e=0;e<c;e++)d.push(a(u,24+8*e));let f=l.subarray(24+8*c);return{id:i,links:d,data:T(f),bytes:f}}var fe={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`};function pe(e){let t=e.indexOf(`<TX>`),n=t<0?-1:e.indexOf(`</TX>`,t+4);return(n>=0?e.slice(t+4,n):e.replace(/<[^<>]*>/g,``)).replace(/&(lt|gt|amp|quot|apos);/g,(e,t)=>fe[t]).trim()}function j(e,t){if(!t)return Promise.resolve(``);let n=e.texts.get(t);return n||(n=A(e.io,t).then(e=>{let t=l(e.bytes);return e.id===`##MD`?pe(t):t}),e.texts.set(t,n)),n}async function M(e,t,n=0){if(!t)return[];let r=e.io,i=await r.read(t,24),o=s(i.subarray(0,4)),c=i.length<24?0:a(T(i),8);switch(o){case`##DT`:case`##SD`:case`##RD`:return[{offset:t+24,length:c-24,zip:null}];case`##DZ`:{let e=T(await r.read(t+24,24));if(e.byteLength<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let n=e.getUint8(2);if(n===2||n===3)throw Error(`This MF4 uses zstd compression, which isn't supported yet.`);if(n===4||n===5)throw Error(`This MF4 uses LZ4 compression, which isn't supported yet.`);if(n>5)throw Error(`This MF4 is damaged (unknown compression type ${n}).`);let i=e.getUint32(4,!0),o=a(e,8),s=a(e,16);if(o>d(s)||n===1&&i===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${t}).`);if(n===1&&o>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:t+48,length:s,zip:{type:n,param:i,orgLength:o}}]}case`##DL`:{if(n>1)throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`);let i=[];for(let n=t;n;){k(e,n);let t=await A(r,n);for(let n of t.links.slice(1))i.push(...await M(e,n,2));n=t.links[0]}return i}case`##HL`:if(n>0)throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`);return k(e,t),M(e,(await A(r,t)).links[0],1);case`##DV`:case`##DI`:throw Error(`This MF4 uses column-oriented storage (MDF 4.2 DV/DI blocks), which Kymoscope cannot read yet.`);default:throw Error(`This MF4 is damaged (unexpected ${o} block in its data).`)}}async function me(e,t,n){return t?s(await e.io.read(t,4))===`##CC`?he(e,t,n+1):j(e,t):null}async function he(e,t,n=0){if(!t||n>4||e.busy.has(t))return D;let r=e.convs.get(t);if(r)return r;e.busy.add(t);try{let r=await ge(e,t,n);return e.convs.set(t,r),r}finally{e.busy.delete(t)}}async function ge(e,t,n){let r=await A(e.io,t),i=r.data,a=i.getUint8(0),o=i.getUint16(4,!0),s=i.getUint16(6,!0),c=new Float64Array(s);for(let e=0;e<s;e++)c[e]=i.getFloat64(24+8*e,!0);let l=r.links.slice(4,4+o),u=()=>Promise.all(l.map(t=>me(e,t,n)));switch(a){case 0:return D;case 1:return{k:`lin`,b:c[0],a:c[1]};case 2:return{k:`rat`,p:[...c]};case 3:{let t=await j(e,l[0]),n=ie(t);return n?{k:`alg`,f:n}:{k:`unsupported`,what:`the formula "${t}"`}}case 4:case 5:{let e=s>>1,t=new Float64Array(e),n=new Float64Array(e);for(let r=0;r<e;r++)t[r]=c[2*r],n[r]=c[2*r+1];return{k:`tab`,keys:t,vals:n,interp:a===4}}case 6:{let e=Math.max(0,Math.floor((s-1)/3)),t=new Float64Array(e),n=new Float64Array(e),r=new Float64Array(e);for(let i=0;i<e;i++)t[i]=c[3*i],n[i]=c[3*i+1],r[i]=c[3*i+2];return{k:`rtv`,lo:t,hi:n,vals:r,def:c[s-1]}}case 7:{let e=await u();return{k:`text`,ranges:[...c].map((t,n)=>({lo:t,hi:t,to:e[n]??null})),def:e[s]??null,int:!0}}case 8:{let e=await u(),t=s>>1;return{k:`text`,ranges:Array.from({length:t},(t,n)=>({lo:c[2*n],hi:c[2*n+1],to:e[n]??null})),def:e[t]??null,int:!0}}default:return{k:`unsupported`,what:`conversion type ${a}`}}}var _e={0:{type:`uint`,bigEndian:!1,encoding:`latin1`},1:{type:`uint`,bigEndian:!0,encoding:`latin1`},2:{type:`int`,bigEndian:!1,encoding:`latin1`},3:{type:`int`,bigEndian:!0,encoding:`latin1`},4:{type:`float`,bigEndian:!1,encoding:`latin1`},5:{type:`float`,bigEndian:!0,encoding:`latin1`},6:{type:`string`,bigEndian:!1,encoding:`latin1`},7:{type:`string`,bigEndian:!1,encoding:`utf-8`},8:{type:`string`,bigEndian:!1,encoding:`utf-16le`},9:{type:`string`,bigEndian:!0,encoding:`utf-16be`},10:{type:`bytes`,bigEndian:!1,encoding:`latin1`}};async function ve(e,t){let{io:n,notes:r}=e,i=t.data,o=i.getUint8(0),c=i.getUint8(1),l=i.getUint8(2),u=await j(e,t.links[2]),d=_e[l];if(!d)return r.push(`${u}: data type ${l} is not supported; the channel was skipped.`),null;let f;if(o===2||o===3)if(c===1)f=o===2?`master`:`vmaster`;else{if(r.push(`The master channel ${u} is not time (sync type ${c}): samples are numbered instead.`),o===3)return null;f=`value`}else if(o===1)f=`vlsd`;else if(o===0||o===4)f=`value`;else return r.push(`${u}: channel type ${o} is not supported; skipped.`),null;let p=await he(e,t.links[4]),m=p.k===`text`?{...p,int:d.type!==`float`}:p,h=await j(e,t.links[6]);!h&&t.links[4]&&(h=await j(e,(await A(n,t.links[4])).links[1]));let g=null,_=null;f===`vlsd`&&t.links[5]&&(s(await n.read(t.links[5],4))===`##CG`?_=a((await A(n,t.links[5])).data,0):g=await M(e,t.links[5]));let v=i.getUint32(12,!0);return{name:u,unit:h,kind:f,...d,conv:m,sd:g,sdRecordId:_,byteOffset:i.getUint32(4,!0),bitOffset:i.getUint8(3),bitCount:i.getUint32(8,!0),invalBit:v&2?i.getUint32(16,!0):null,allInvalid:(v&1)!=0}}async function ye(e,t,n,r=0){let{io:i,notes:a}=e;for(let o=t;o;){k(e,o);let t=await A(i,o),c=t.links[1];c&&r<4&&(s(await i.read(c,4))===`##CN`?await ye(e,c,n,r+1):a.push(`${await j(e,t.links[2])}: array channels (CA) are not supported yet; skipped.`));let l=await ve(e,t);l&&n.push(l),o=t.links[0]}}async function be(e,t,n,r){let i=t.data,o=i.getUint16(16,!0),s=0;t.links[3]&&(s=(await A(e.io,t.links[3])).data.getUint8(1));let c={name:await j(e,t.links[2]),dg:n,recordId:a(i,0),recordIdSize:r,idTrailer:0,dataBytes:i.getUint32(24,!0),invalBytes:i.getUint32(28,!0),cycles:a(i,8),vlsdCg:(o&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:s,busEvent:(o&2)!=0};if(c.vlsdCg)return c;let l=[];await ye(e,t.links[1],l);for(let e of l)e.kind===`master`||e.kind===`vmaster`?c.master||=e:c.channels.push(e);return c}async function xe(e,t){let n=await A(e,64);if(n.id!==`##HD`)throw Error(`This MF4 is damaged (no header block).`);let r=a(n.data,0),i=(n.data.getUint8(12)&1)!=0,o=new Date(r/1e6).toISOString(),s=r>0?i?o.slice(0,-1):o:null,c={io:e,notes:[],seen:new Set,texts:new Map,convs:new Map,busy:new Set},l=[],u=0;for(let t=n.links[0],r=0;t;r++){k(c,t);let n=await A(e,t),i=n.data.getUint8(0),a=[];for(let t=n.links[1];t;){k(c,t);let n=await A(e,t),o=await be(c,n,r,i);o.vlsdCg||(u++,o.name||=`Group ${u}`),a.push(o),t=n.links[0]}let o=await M(c,n.links[2]),s=a.length===1;for(let e of a)e.stream=o,e.sorted=s,l.push(e);t=n.links[0]}return{version:`MF4 ${t}`,startTime:s,groups:l,notes:c.notes,meta:{}}}function Se(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}function N(e,t,n,r,i,a,o=0){let s=T(t),c=!e.bigEndian,l=i+e.byteOffset,u=e.bitCount;if(e.bitOffset===0)if(e.type===`float`){if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat64(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat32(l,c);return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=Se(s.getUint16(l,c));return}}else if(e.type===`int`){if(u===8){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt8(l);return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt16(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l,c);return}if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}else{if(u===8){for(let e=0;e<n;e++,l+=r)a[o+e]=t[l];return}if(u===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint16(l,c);return}if(u===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l,c);return}if(u===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}let d=e.bitOffset+u+7>>3,f=2**e.bitOffset,p=2**u,m=p/2,h=e.type===`int`;for(let e=0;e<n;e++,l+=r){let n=0;if(c)for(let e=d-1;e>=0;e--)n=n*256+t[l+e];else for(let e=0;e<d;e++)n=n*256+t[l+e];n=Math.floor(n/f)%p,a[o+e]=h&&n>=m?n-p:n}}var Ce=new Map,we=e=>{let t=Ce.get(e);return t||Ce.set(e,t=new TextDecoder(e)),t};function Te(e){let t=e.indexOf(`\0`);return t<0?e:e.slice(0,t)}function Ee(e,t,n,r,i){let a=we(e.encoding),o=e.bitCount>>3,s=Array(n);for(let c=0,l=i+e.byteOffset;c<n;c++,l+=r)s[c]=Te(a.decode(t.subarray(l,l+o)));return s}function De(e,t,n,r,i,a){let o=a instanceof Float64Array?NaN:null;if(e.allInvalid){for(let e=0;e<n;e++)a[e]=o;return}if(e.invalBit===null)return;let s=1<<(e.invalBit&7);for(let c=0,l=i+(e.invalBit>>3);c<n;c++,l+=r)t[l]&s&&(a[c]=o)}var P=e=>e.recordIdSize+e.dataBytes+e.invalBytes+e.idTrailer,Oe=64<<20,ke=(e,t)=>e.reduce((e,n)=>e+(n.zip?n.zip.orgLength:Math.max(0,Math.min(n.length,t-n.offset))),0),Ae=e=>e.byteOffset+Math.ceil((e.bitOffset+e.bitCount)/8);function je(e,t){return e.kind===`vmaster`?!0:(e.kind===`vlsd`||e.type===`uint`||e.type===`int`||e.type===`float`?!(e.bitCount>=1&&e.bitCount<=64):!(e.bitCount>=8))?!1:Ae(e)<=t.dataBytes}function Me(e,t){let n=e.notes;for(let r of e.groups){if(![0,1,2,4,8].includes(r.recordIdSize))throw Error(`This MDF file is damaged (bad record id size).`);if(r.vlsdCg)continue;let e=P(r);if(e>Oe||e===0){r.cycles>0&&n.push(`${r.name||`A group`}: its records are ${e===0?`empty`:`too large`} (damaged); skipped.`),r.cycles=0;continue}r.cycles=Math.min(r.cycles,Math.floor(ke(r.stream,t)/e));let i=r.channels.filter(e=>!je(e,r));for(let e of i)n.push(`${e.name}: its bits lie outside its record (damaged); skipped.`);i.length&&(r.channels=r.channels.filter(e=>!i.includes(e))),r.master&&!je(r.master,r)&&(n.push(`${r.master.name}: the time channel lies outside its record (damaged): samples are numbered instead.`),r.master=null);for(let e of r.master?[...r.channels,r.master]:r.channels)e.invalBit!==null&&e.invalBit>=8*r.invalBytes&&(e.invalBit=null)}}function Ne(e,t){let n=0;for(let r of e.master?[...t,e.master]:t){if(r.invalBit!==null)return 1/0;r.kind!==`vmaster`&&(n=Math.max(n,r.byteOffset+(r.bitOffset+r.bitCount+7>>3)))}return e.recordIdSize+n}var Pe=65536,Fe=`This file's compressed data is damaged.`;async function*Ie(e){for(let t=0;t<e.length;t+=Pe)yield e.subarray(t,t+Pe)}async function*Le(e){if(typeof DecompressionStream!=`function`){let t=[],n=new p(e=>{t.push(e)});for await(let r of e)for(n.push(r,!1);t.length;)yield t.shift();for(n.push(new Uint8Array,!0);t.length;)yield t.shift();return}let t=new DecompressionStream(`deflate`),n=t.writable.getWriter();(async()=>{for await(let t of e)await n.write(t);await n.close()})().catch(e=>n.abort(e).catch(()=>{}));let r=t.readable.getReader();try{for(;;){let{done:e,value:t}=await r.read().catch(e=>{throw e instanceof TypeError?Error(Fe):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function F(e,t=-1,n=1/0){let r=[],i=Math.min(t,n),a=t>=0?new Uint8Array(i):null,o=0;for await(let s of Le(Ie(e))){if(a){if(o+s.length>t&&n>t)throw Error(`Compressed data is longer than its header says.`);a.set(o+s.length>i?s.subarray(0,i-o):s,o)}else r.push(s);if(o+=s.length,o>=n)break}if(a)return o>=i?a:a.subarray(0,o);let s=r.length===1?r[0]:new Uint8Array(o);return r.length>1&&r.reduce((e,t)=>(s.set(t,e),e+t.length),0),o>n?s.subarray(0,n):s}var Re=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function ze(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&Re?new Uint32Array(a.buffer,0,i*r>>2):null,s=r>>2;for(let t=0;t<i;t+=512){let n=Math.min(i,t+512);if(o)for(let a=0;a<r;a+=4){let r=a*i,c=r+i,l=c+i,u=l+i;for(let i=t,d=t*s+(a>>2);i<n;i++,d+=s)o[d]=e[r+i]|e[c+i]<<8|e[l+i]<<16|e[u+i]<<24}else for(let o=0;o<r;o++){let s=o*i;for(let i=t,c=t*r+o;i<n;i++,c+=r)a[c]=e[s+i]}}let c=i*t;return r===t&&a.set(e.subarray(c,n),c),a}function Be(e,t,n){if(!(n<t)||e.length===0)return t;let r=Math.min(t,n+3&-4);return r===t?t:e.every(e=>e.zip?.type===1&&e.zip.param===t&&e.zip.orgLength%t===0)?r:t}async function Ve(e,t,n=1/0,r=1/0){let i=await e.slice(t.offset,t.length),{type:a,param:o,orgLength:s}=t.zip;if(a===0)return F(i,s,r);let c=Math.min(n,o);return ze(await F(i,s,c<o?s/o*c:1/0),o,s,c)}async function*I(e,t,n,r=1/0){let i=e=>!!e?.zip&&!(e.zip.type===0&&(e.length>16777216||e.zip.orgLength>268435456)),a=null;for(let o=0;o<t.length;o++){let s=t[o];if(n?.throwIfAborted(),!s.zip)for await(let t of e.windows(s.offset,s.length))yield t.bytes;else if(i(s)){let n=a??Ve(e,s,r);a=i(t[o+1])?Ve(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of Le((async function*(){for await(let t of e.windows(s.offset,s.length))yield t.bytes})()))if(yield n.length>t?n.subarray(0,t):n,(t-=n.length)<=0)break}}}async function*He(e,t,n,r){if(r<=0||t<=0)return;let i=Math.min(n,r),a=null,o=0,s=0;for await(let n of e){let e=0;for(;e<n.length&&s<r;){if(o===0){let a=Math.min(i,r-s,Math.floor((n.length-e)/t));if(a>0){yield{buf:n.subarray(e,e+a*t),n:a},s+=a,e+=a*t;continue}}a??=new Uint8Array(t*i);let c=Math.min(a.length,(r-s)*t),l=Math.min(n.length-e,c-o);if(a.set(n.subarray(e,e+l),o),o+=l,e+=l,o===c){let e=o/t;yield{buf:a,n:e},s+=e,o=0}}if(s>=r)return}a&&o>=t&&(yield{buf:a,n:Math.floor(o/t)})}async function Ue(e,t,n,r){let i=n*r,a=0;for(let n of t){let t=n.zip?n.zip.orgLength:n.length;if(i<a)return null;if(i+r<=a+t)return n.zip?null:e.read(n.offset+i-a,r);a+=t}return null}var We=(e,t)=>(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0,Ge=class{#e;#t;#n;#r;#i=new Uint8Array;#a=0;#o;#s=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=I(e,t,n),this.#o=t.reduce((e,t)=>e+(t.zip?t.zip.orgLength:t.length),0)}peek(e){let t=e-this.#a;if(t<0||t+4>this.#i.length)return null;let n=We(this.#i,t);return t+4+n>this.#i.length?null:this.#i.subarray(t+4,t+4+n)}async get(e){for(;;){let t=this.peek(e);if(t)return t;let n=e-this.#a;if(e+4>this.#o||n>=0&&n+4<=this.#i.length&&e+4+We(this.#i,n)>this.#o)throw Error(`This MF4 is damaged (string data ends early).`);e<this.#a&&(this.#r=I(this.#e,this.#t,this.#n),this.#i=new Uint8Array,this.#a=0);let r=await this.#r.next();if(r.done)throw Error(`This MF4 is damaged (string data ends early).`);if((this.#s+=r.value.length)>4*this.#o+16777216)throw Error(`This MF4 is damaged (its string offsets jump back and forth).`);let i=Math.max(0,Math.min(e-this.#a,this.#i.length)),a=this.#i.subarray(i),o=new Uint8Array(a.length+r.value.length);o.set(a),o.set(r.value,a.length),this.#a+=i,this.#i=o}}},Ke=e=>Math.max(1,Math.min(65536,Math.floor((8<<20)/Math.max(1,e)))),qe=64<<20,Je=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t){this.#e=e,this.#t=t}want(e){this.#r.has(e)||this.#r.set(e,new Map)}wanted(e){return this.#r.has(e)}put(e,t,n){this.#r.get(e).set(t,n)}async bytes(e,t){let n=Array(t.length);if(e.sdRecordId!==null){let r=this.#r.get(e.sdRecordId);for(let e=0;e<t.length;e++)n[e]=r?.get(t[e])??null,r?.delete(t[e]);return n}if(!e.sd)return n.fill(null);let r=this.#n.get(e);r||this.#n.set(e,r=new Ge(this.#e,e.sd,this.#t));for(let e=0;e<t.length;e++)n[e]=r.peek(t[e])??await r.get(t[e]);return n}async strings(e,t){let n=we(e.encoding);return(await this.bytes(e,t)).map(e=>e?Te(n.decode(e)):null)}};function Ye(e,t,n,r,i=P(e),a=new Float64Array(n)){let o=e.master;if(!o)return null;if(o.kind===`vmaster`)for(let e=0;e<n;e++)a[e]=r+e;else N(o,t,n,i,e.recordIdSize,a);return O(o.conv,a),a}function Xe(e,t,n){return n===1?e[t]:n===2?e[t]|e[t+1]<<8:n===4?(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0:((e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0)+4294967296*((e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24)>>>0)}function Ze(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*Qe(e,t,n,r,i,a=1/0){let o=t.groups[n[0]];if(o.sorted){let t=Be(o.stream,P(o),a),r=0;for await(let{buf:a,n:s}of He(I(e,o.stream,i,t),t,Ke(t),o.cycles))yield{g:n[0],buf:a,n:s,start:r,size:t},r+=s;return}let s=t.groups.map((e,t)=>({g:e,k:t})).filter(({g:e})=>e.dg===o.dg),c=o.recordIdSize,l=new Map;for(let e of n){let n=t.groups[e],r=P(n);l.set(n.recordId,{k:e,size:r,buf:new Uint8Array(r*Math.min(Ke(r),Math.max(1,n.cycles))),fill:0,start:0})}let u=new Map(s.map(({g:e})=>[e.recordId,e.vlsdCg?-1:P(e)])),d=new Map,f=new Uint8Array;for await(let t of I(e,o.stream,i)){let e=f.length?Ze(f,t):t,n=0;for(;!(n+c>e.length);){let t=Xe(e,n,c),i=u.get(t);if(i===void 0)throw Error(`This MF4 is damaged (unknown record id ${t}).`);if(i<0){if(n+c+4>e.length)break;let i=(e[n+c]|e[n+c+1]<<8|e[n+c+2]<<16|e[n+c+3]<<24)>>>0;if(i>qe)throw Error(`This MF4 is damaged (a string record of ${i} bytes).`);let a=n+c+4+i;if(a>e.length)break;let o=d.get(t)??0;r.wanted(t)&&r.put(t,o,e.slice(n+c+4,a)),d.set(t,o+4+i),n=a;continue}if(n+i>e.length)break;let a=l.get(t);if(a&&(a.buf.set(e.subarray(n,n+i),a.fill),a.fill+=i,a.fill===a.buf.length)){let e=a.fill/a.size;yield{g:a.k,buf:a.buf,n:e,start:a.start,size:a.size},a.start+=e,a.fill=0}n+=i}f=e.slice(n)}for(let e of l.values())e.fill&&(yield{g:e.k,buf:e.buf,n:e.fill/e.size,start:e.start,size:e.size})}var L=(e,t)=>t?e+2147483648:e,$e=/^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/,et=/^SG_\s+(\w+)\s*(?:(M|m\d+M?)\s*)?:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,)]*),([^)]*)\)\s*\[[^\]]*\]\s*"([^"]*)"/,tt=/^VAL_\s+(\d+)\s+(\w+)\s+(.*);/,nt=/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*([12])\s*;/,rt=/^-?\d+(?:\.\d+)?$/;function it(e){let t=e.split(`"`),n=new Map;for(let e=0;e+1<t.length;e+=2){let r=t[e].trim();rt.test(r)&&n.set(Number(r),t[e+1])}return n}var at=(e,t)=>e<=511&&t>=1&&t<=64;function ot(e){let t=new Map,n=new Map,r=new Map,i=(e,t)=>{let i=n.get(Number(e));return i?r.get(i)?.get(t):void 0},a=null;for(let o of e.split(/\r?\n/)){let e=o.trim(),s;if(s=$e.exec(e)){let e=Number(s[1]),r=e>=2147483648,i=r?e-2147483648:e;a={id:i,extended:r,name:s[2],size:Number(s[3]),signals:[]},t.set(L(i,r),a),n.set(e,a)}else if((s=et.exec(e))&&a){let e=s[2],t=Number(s[3]),n=Number(s[4]);if(!at(t,n)||!s[7].trim()||!s[8].trim())continue;let i={name:s[1],start:t,length:n,littleEndian:s[5]===`1`,signed:s[6]===`-`,factor:Number(s[7]),offset:Number(s[8]),unit:s[9],mux:e?e===`M`?`switch`:parseInt(e.slice(1),10):null,float:0,values:null};a.signals.push(i);let o=r.get(a);o||r.set(a,o=new Map),o.has(i.name)||o.set(i.name,i)}else if(s=tt.exec(e)){let e=i(s[1],s[2]);e&&(e.values=it(s[3]))}else if(s=nt.exec(e)){let e=i(s[1],s[2]);e&&(e.float=s[3]===`1`?32:64)}else (e.startsWith(`BO_`)||e===``)&&e===``&&(a=null)}return t}function R(e){if(e.float){let t=e.float/8,n=e.start>>3,r=e.littleEndian,i=new DataView(new ArrayBuffer(8));return(e,a)=>{for(let r=0;r<t;r++)i.setUint8(r,e[a+n+r]??0);return t===4?i.getFloat32(0,r):i.getFloat64(0,r)}}let t=e.length,n=2**t,r=n/2,i=e.signed;if(e.littleEndian){let a=e.start>>3,o=e.start&7;if(o+t<=32){let e=t===32?-1:(1<<t)-1;return(t,s)=>{let c=s+a,l=((t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24)>>>o&e)>>>0;return i&&l>=r?l-n:l}}let s=o+t+7>>3,c=2**(t-(32-o)),l=2**(32-o);return(e,t)=>{let u=t+a,d=(e[u]|e[u+1]<<8|e[u+2]<<16|e[u+3]<<24)>>>o,f=0;for(let t=s-1;t>=4;t--)f=f*256+(e[u+t]??0);let p=d+f%c*l;return i&&p>=r?p-n:p}}let a=e.start>>3,o=e.start&7;if(7-o+t<=32){let e=32-(7-o)-t,s=t===32?-1:(1<<t)-1;return(t,o)=>{let c=o+a,l=((t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>e&s)>>>0;return i&&l>=r?l-n:l}}let s=(1<<o+1)-1,c=t-(o+1)>>3,l=t-(o+1)&7,u=2**l;return(e,t)=>{let o=(e[t+a]??0)&s,d=t+a+1;for(let t=0;t<c;t++)o=o*256+(e[d++]??0);return l>0&&(o=o*u+((e[d]??0)>>8-l)),i&&o>=r?o-n:o}}function st(e){let t=e.length,n=2**t,r=n/2,i=e.signed,a=t===32?-1:(1<<t)-1;if(!e.float&&e.littleEndian&&(e.start&7)+t<=32){let t=e.start>>3,o=e.start&7;return(e,s,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=s[c[p]]+t,m=((e[l]|e[l+1]<<8|e[l+2]<<16|e[l+3]<<24)>>>o&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}if(!e.float&&!e.littleEndian&&7-(e.start&7)+t<=32){let o=e.start>>3,s=32-(7-(e.start&7))-t;return(e,t,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=t[c[p]]+o,m=((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])>>>s&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}let o=R(e);return(e,t,n,r,i,a,s)=>{for(let c=0;c<r;c++)i[c]=o(e,t[n[c]])*a+s}}function ct(e){if(!e.busEvent||e.busType!==2)return null;let t=t=>e.channels.find(e=>e.name.endsWith(t))??null,n=t(`DataFrame.ID`),r=t(`DataFrame.DataBytes`);return!n||!r?null:{id:n,ide:t(`DataFrame.IDE`),data:r}}var lt=()=>({n:0,time:new Float64Array,key:new Float64Array,id:new Float64Array,ide:new Float64Array,bytes:null,buf:new Uint8Array,dataAt:new Int32Array});async function ut(e,t,n,r,i,a,o,s){s.key.length<r&&Object.assign(s,{time:new Float64Array(r),key:new Float64Array(r),id:new Float64Array(r),ide:new Float64Array(r),dataAt:new Int32Array(r)});let c=e.recordIdSize,{id:l,ide:u,key:d,dataAt:f}=s;N(t.id,n,r,a,c,l),t.ide&&N(t.ide,n,r,a,c,u);for(let e=0;e<r;e++){let n=l[e],r=n&536870911;d[e]=L(r,t.ide?u[e]!==0:n>=2147483648||r>2047)}if(s.bytes=null,t.data.kind===`vlsd`){let e=new Float64Array(r);N({...t.data,type:`uint`},n,r,a,c,e),s.bytes=await o.bytes(t.data,e)}else for(let e=0,n=c+t.data.byteOffset;e<r;e++,n+=a)f[e]=n;if(!Ye(e,n,r,i,a,s.time.subarray(0,r)))for(let e=0;e<r;e++)s.time[e]=i+e;return s.n=r,s.buf=n,s}var dt=new Uint8Array;function ft(e){return e.float?(e.start>>3)+e.float/8:e.littleEndian?(e.start>>3)+((e.start&7)+e.length+7>>3):(e.start>>3)+1+(Math.max(0,e.length-((e.start&7)+1))+7>>3)}function pt(e,t,n){let r=0;for(let e of n.values())for(let t of e.signals)r=Math.max(r,ft(t));let i=t.data.kind===`vlsd`?t.data:{...t.data,bitCount:Math.min(t.data.bitCount,r*8)};return Ne(e,t.ide?[t.id,t.ide,i]:[t.id,i])}function mt(e,t){let n=t.map(t=>e.signals[e.channels[t].s]);return{route:e,col:n.map(st),read:n.map(R),factor:n.map(e=>e.factor),offset:n.map(e=>e.offset),table:t.map((t,r)=>e.channels[t].text?n[r].values:null),idx:new Int32Array,cnt:0,n:0,t0:NaN,t1:NaN}}function z(e,t,n,r,i,a=1,o=0){let s=new Float64Array(i);if(n.bytes)for(let e=0;e<i;e++)s[e]=t(n.bytes[r[e]]??dt,0)*a+o;else e(n.buf,n.dataAt,r,i,s,a,o);return s}function ht(e,t){let{idx:n,cnt:r}=e,i=new Float64Array(r);for(let e=0;e<r;e++)i[e]=t.time[n[e]];return e.n===0&&(e.t0=i[0]),e.t1=i[r-1],e.n+=r,e.cnt=0,{time:i,cols:e.col.map((i,a)=>{let o=e.table[a];return o?Array.from(z(i,e.read[a],t,n,r),e=>o.get(e)??null):z(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}var gt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function _t(e,t){let n=e.signals.find(e=>e.mux===`switch`);return{key:L(e.id,e.extended),skip:!1,frames:0,all:t,sw:n?{col:st(n),read:R(n)}:null,byMux:new Map,idx:new Int32Array,cnt:0}}var vt=class{#e=Array(2048);#t=new Map;#n;constructor(e){this.#n=e}get(e){let t=e<2048?this.#e[e]:this.#t.get(e);return t||(t=this.#n(e),e<2048?this.#e[e]=t:this.#t.set(e,t)),t}};function yt(e,t,n){let r=[];for(let n=0;n<e.n;n++){let i=t.get(e.key[n]);if(i.skip){i.frames++;continue}i.cnt===0&&(r.push(i),i.idx.length<e.n&&(i.idx=new Int32Array(e.n))),i.idx[i.cnt++]=n}let i=[];for(let t of r){if(t.all&&(t.all.idx=t.idx,t.all.cnt=t.cnt,i.push(t.all)),t.sw){let r=z(t.sw.col,t.sw.read,e,t.idx,t.cnt);for(let e=0;e<t.cnt;e++){let a=t.byMux.get(r[e]);a===void 0&&((a=n(t,r[e]))||t.byMux.size<4096)&&t.byMux.set(r[e],a),a&&(a.cnt===0&&(i.push(a),a.idx.length<t.cnt&&(a.idx=new Int32Array(t.cnt))),a.idx[a.cnt++]=t.idx[e])}}t.cnt=0}return i}var bt=48e6;async function xt(e,t,n,r){let i=new Map;if(t.groups.forEach((e,t)=>{let n=ct(e);n&&e.cycles>0&&i.set(t,n)}),i.size===0)return null;if(n.length===0)return{dbc:new Map,layouts:i,routes:[],notes:[],cache:new Map};let a=ot(u(new Uint8Array(await n[0].arrayBuffer()))),o=[],s=new Map,c=new Map,l=0,d=new Je(e,r);for(let[n,u]of i){let i=t.groups[n],f=(e,t)=>{let n=e.signals.filter(e=>t===null?typeof e.mux!=`number`:e.mux===t),r=[];return n.forEach((e,t)=>{r.push({s:t,text:!1}),e.values&&r.push({s:t,text:!0})}),mt({key:L(e.id,e.extended),mux:t,signals:n,channels:r},r.map((e,t)=>t))},p=new vt(e=>{let t=a.get(e);if(!t){let t=gt(e);return s.set(e,t),t}let r=_t(t,f(t,null));return o.push({model:n,m:r}),r});u.data.sdRecordId!==null&&d.want(u.data.sdRecordId);let m=lt();for await(let o of Qe(e,t,[n],d,r,pt(i,u,a))){let e=await ut(i,u,o.buf,o.n,o.start,o.size,d,m),t=(e,t)=>{let n=a.get(e.key);return n.signals.some(e=>e.mux===t)?f(n,t):null};for(let n of yt(e,p,t)){let t=ht(n,e);if(l<0)continue;if((l+=t.time.length*(1+t.cols.length))>bt){l=-1,c.clear();continue}let r=c.get(n);r||c.set(n,r=[]),r.push(t)}}}let f=[],p=new Map;for(let{model:e,m:t}of o)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:o}=n;if(t.signals.length===0)continue;let s=a.get(t.key);l>=0&&p.set(t,c.get(n)??[]),f.push({model:e,route:t,group:{name:t.mux===null?s.name:`${s.name} [m=${t.mux}]`,channels:t.channels.map(e=>({name:e.text?`${t.signals[e.s].name} (text)`:t.signals[e.s].name,unit:e.text?``:t.signals[e.s].unit,text:e.text})),samples:r,time:{kind:`timestamps`},rateHz:r>1&&o>i?Math.round((r-1)/(o-i)*1e6)/1e6:null}})}let m=[];if(s.size){let e=[...s.values()].reduce((e,t)=>e+t.frames,0),t=[...s.keys()].map(e=>`0x${(e%2147483648).toString(16).toUpperCase()}`).join(`, `);m.push(`${e} frame${e===1?``:`s`} with ${s.size} id${s.size===1?``:`s`} not in the DBC ${e===1?`was`:`were`} skipped (${t}).`)}return{dbc:a,layouts:i,routes:f,notes:m,cache:p}}async function*St(e,t,n,r,i,a){let o=[];for(let e of i){let t=r.cache.get(e.route);if(!t){o.push(e);continue}r.cache.delete(e.route);let n=0;for(let r of t)yield{group:e.group,start:n,length:r.time.length,time:r.time,columns:e.sel.map(e=>r.cols[e])},n+=r.time.length}if(!o.length)return;let s=r.layouts.get(n),c=t.groups[n],l=new Map,u=new Map;for(let e of o){let t=mt(e.route,e.sel);l.set(t,e.group);let n=u.get(e.route.key);n||u.set(e.route.key,n={all:null,byMux:new Map}),e.route.mux===null?n.all=t:n.byMux.set(e.route.mux,t)}let d=new vt(e=>{let t=u.get(e);if(!t)return gt(e);let n=_t(r.dbc.get(e),t.all);return t.byMux.size||(n.sw=null),n}),f=new Je(e,a);s.data.sdRecordId!==null&&f.want(s.data.sdRecordId);let p=lt();for await(let i of Qe(e,t,[n],f,a,pt(c,s,r.dbc))){let e=await ut(c,s,i.buf,i.n,i.start,i.size,f,p);for(let t of yt(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=ht(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}var Ct=e=>Math.round(e*1e6)/1e6,wt=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,Tt=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function Et(e,t){let n=t.master;if(!n||t.cycles<2)return null;if(n.kind===`vmaster`)return n.conv.k===`lin`&&n.conv.a>0?Ct(1/n.conv.a):null;if(!t.sorted)return null;let r=P(t),i=t.cycles,a,o;if(t.stream[0]?.zip){let n=Be(t.stream.slice(0,1),r,Ne(t,[])),s=await Ve(e,t.stream[0],n,4096*r);if(i=Math.min(t.cycles,Math.floor(s.length/n)),i<2)return null;a=s.subarray(0,n),o=s.subarray((i-1)*n,i*n)}else a=await Ue(e,t.stream,0,r),o=await Ue(e,t.stream,t.cycles-1,r);if(!a||!o)return null;let s=new Float64Array(2);return N(n,a,1,r,t.recordIdSize,s,0),N(n,o,1,r,t.recordIdSize,s,1),O(n.conv,s),s[1]>s[0]?Ct((i-1)/(s[1]-s[0])):null}async function Dt(e,t,n,r,i,a,o){let s;if(e.kind===`vlsd`){let a=new Float64Array(n);N({...e,type:`uint`},t,n,r,i,a),s=await o.strings(e,a)}else if(e.type===`string`)s=Ee(e,t,n,r,i);else{let a=new Float64Array(n);N(e,t,n,r,i,a),e.conv.k===`text`?s=ce(e.conv,a):(O(e.conv,a),s=a)}return De(e,t,n,r,a,s),s}async function Ot(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await Dt(e.channels[i],n,r,a,c,c+e.dataBytes,s));return{group:o,time:Ye(e,n,r,i,a),start:i,length:r,columns:l}}async function*kt(e,t){let n=e.plan.state,r=t.filter(e=>n.groups[e].route),i=t.filter(e=>!n.groups[e].route);if(r.length){let t=r.map(t=>({group:t,route:n.groups[t].route,sel:E(e,t)}));yield*St(e.io,n.model,n.groups[r[0]].model,n.bus,t,e.signal)}if(!i.length)return;let a=new Je(e.io,e.signal),o=new Map;for(let t of i){let r=n.groups[t],i=E(e,t).map(e=>r.channels[e]);for(let e of i){let t=n.model.groups[r.model].channels[e].sdRecordId;t!==null&&a.want(t)}o.set(r.model,{pg:t,cols:i})}let[s,{cols:c}]=o.entries().next().value,l=n.model.groups[s],u=o.size===1?Ne(l,c.map(e=>l.channels[e])):1/0;for await(let t of Qe(e.io,n.model,[...o.keys()],a,e.signal,u)){let{pg:e,cols:r}=o.get(t.g);yield await Ot(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function At(e){let t=e.plan.state,n=new Map;for(let r of e.selection){let e=t.model.groups[t.groups[r.group].model].dg;n.set(e,[...n.get(e)??[],r.group])}return[...n].sort((e,t)=>e[0]-t[0]).map(([,e])=>e)}var jt={...o,async plan(e,t){let n=await t.read(0,64);if(i(n,`UnFinMF`))throw Error(`This MF4 was not finalized by its logger (it starts with UnFinMF). Finalize it with the logger software or asammdf, then open it again.`);let r=s(n.subarray(8,16)).replace(/\0/g,``).trim(),a=Number(r.replace(`.`,``).slice(0,3))>=400?await xe(t,r):await ue(t,n,r);Me(a,t.size);let o=await xt(t,a,e.companions.filter(e=>e.name.toLowerCase().endsWith(`.dbc`))),c=new Set(o?.layouts.keys()??[]),l=[],u=[],d=[...a.notes],f=0;for(let e=0;e<a.groups.length;e++){let n=a.groups[e];if(n.vlsdCg||n.cycles===0||c.has(e))continue;let r=[];if(n.channels.forEach((e,t)=>{wt(e)?r.push(t):f++}),r.length!==0){for(let e of r){let t=n.channels[e].conv;t.k===`unsupported`&&d.push(`${n.channels[e].name}: ${t.what} is not supported; raw values are shown.`)}u.push({model:e,channels:r}),l.push({name:n.name,channels:r.map(e=>Tt(n.channels[e])),samples:n.cycles,time:n.master?{kind:`timestamps`}:{kind:`index`},rateHz:await Et(t,n)})}}if(f&&d.push(`${f} byte-array channel${f===1?` was`:`s were`} skipped.`),o){if(o.routes.length===0&&o.dbc.size===0){if(l.length===0)throw Error(`This MF4 has raw CAN frames. Drop its .dbc file together with it to decode signals.`);d.push(`This MF4 also has raw CAN frames. Drop its .dbc file together with it to decode signals.`)}for(let e of o.routes)u.push({model:e.model,route:e.route}),l.push(e.group);d.push(...o.notes)}if(l.length===0)throw Error(`This MDF file has no channels with samples.`);let p={model:a,groups:u,bus:o};return{format:a.version,startTime:a.startTime,groups:l,meta:a.meta,events:[],notes:d,interleaved:!!o?.routes.length||a.groups.some(e=>!e.sorted&&!e.vlsdCg),state:p}},async*stream(e){for(let t of At(e))yield*kt(e,t)},streamGroup(e,t){return kt(e,[t])}};function Mt(e){let t=[];for(let n of u(e).split(`\0`)){if(!n)continue;let e=n.split(``),r=parseFloat(e[0].split(``)[0]);Number.isFinite(r)&&t.push({onset:r,texts:e.slice(1).filter(e=>e.length>0)})}return t}function Nt(e,t){let n=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(e),r=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(t);if(!n||!r)return null;let i=Number(n[3]);return`${i>=85?1900+i:2e3+i}-${n[2]}-${n[1]}T${r[1]}:${r[2]}:${r[3]}`}var Pt=e=>`${+e.toFixed(6)} Hz`;function Ft(e,t,n,r,i,a,o,s){let{bit:c,off:l}=e;if(a===2)for(let e=0;e<i;e++)o[s+e]=c*(l+t.getInt16(r+2*e,!0));else for(let e=0,t=r;e<i;e++,t+=3)o[s+e]=c*(l+((n[t]|n[t+1]<<8|n[t+2]<<16)<<8>>8))}var It={...g,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>s(n.subarray(e,e+t)).trim(),i=n[0]===255,a=parseInt(r(252,4),10),o=parseInt(r(184,8),10),c=r(192,44),l=/^(EDF|BDF)\+/.test(c),u=/^(EDF|BDF)\+D/.test(c),d=parseFloat(r(244,8));if(!(a>0)||o!==256*(a+1)||!(d>0))throw Error(`This EDF/BDF header is damaged.`);let f=await t.read(256,a*256),p=(e,t,n)=>s(f.subarray(e*a+t*n,e*a+t*(n+1))).trim(),m=i?3:2,h=[],g=0;for(let e=0;e<a;e++){let t=parseFloat(p(104,8,e)),n=parseFloat(p(112,8,e)),r=parseFloat(p(120,8,e)),i=parseFloat(p(128,8,e)),a=Number(p(216,8,e));if(!(Number.isInteger(a)&&a>=0))throw Error(`This EDF/BDF header is damaged (samples per record).`);let o=(n-t)/(i-r);h.push({label:p(0,16,e),unit:p(96,8,e),spr:a,offset:g,bit:o,off:n/o-i}),g+=a*m}let _=g;if(!(_>0&&o+_<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-o)/_),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=l?h.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;h.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let ee=[...S.values()],C=ee.map(e=>{let t=h[e[0]].spr/d;return{name:Pt(t),channels:e.map(e=>({name:h[e].label,unit:h[e].unit})),samples:y*h[e[0]].spr,rateHz:t,time:u?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),w={headerBytes:o,records:y,duration:d,recordBytes:_,bps:m,signals:h,groups:ee,annotations:x,discontinuous:u};return{format:`${i?`BDF`:`EDF`}${l?u?`+D`:`+`:``}`,startTime:Nt(r(168,8),r(176,8)),groups:C,meta:{patient:r(8,80),recording:r(88,80)},events:[],notes:u?[`Discontinuous recording: each gap shows as a break in the traces.`,...b]:b,state:w}},async*stream(e){let t=e.plan.state,n=Math.max(1,Math.floor(te/t.recordBytes)),r=e.selection.map(e=>({g:e.group,chans:e.channels.map(n=>t.signals[t.groups[e.group][n]]),spr:t.signals[t.groups[e.group][0]].spr})),i=r.map(()=>0),a=0,o=NaN;for await(let s of e.io.windows(t.headerBytes,t.records*t.recordBytes,n*t.recordBytes)){e.signal?.throwIfAborted();let n=Math.floor(s.bytes.length/t.recordBytes);if(n===0)break;let c=T(s.bytes),l=new Float64Array(n),u=[];for(let e=0;e<n;e++)l[e]=(a+e)*t.duration,t.annotations.forEach((n,r)=>{let i=t.signals[n],a=e*t.recordBytes+i.offset,o=Mt(s.bytes.subarray(a,a+i.spr*t.bps));r===0&&o.length&&(l[e]=o[0].onset);for(let e of o)for(let t of e.texts)u.push({time:e.onset,text:t})});let d=new Uint8Array(n),f=0;if(t.discontinuous)for(let e=0;e<n;e++){let n=e?l[e-1]+t.duration:o;n===n&&l[e]>n+1e-9&&(d[e]=1,f++)}for(let e=0;e<r.length;e++){let a=r[e],p=a.spr/t.duration,m=n*a.spr+f,h=t.discontinuous?new Float64Array(m):null,g=a.chans.map(()=>new Float64Array(m)),_=0;for(let e=0;e<n;e++){if(d[e]){h[_]=e?l[e-1]+t.duration:o;for(let e of g)e[_]=NaN;_++}if(h)for(let t=0;t<a.spr;t++)h[_+t]=l[e]+t/p;let n=e*t.recordBytes;a.chans.forEach((e,r)=>Ft(e,c,s.bytes,n+e.offset,a.spr,t.bps,g[r],_)),_+=a.spr}let v={group:a.g,time:h,start:i[e],length:m,columns:g};e===0&&u.length&&(v.events=u),i[e]+=m,yield v}o=l[n-1]+t.duration,a+=n}}},B={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function V(e,t,n=0){let r=e.indexOf(`<${t}>`,n);if(r<0)return``;let i=e.indexOf(`</${t}>`,r);return i<0?``:e.slice(r+t.length+2,i).trim()}function Lt(e,t){let n=[];for(let r=e.indexOf(`<${t}>`);r>=0;){let i=e.indexOf(`</${t}>`,r);if(i<0)break;n.push(e.slice(r,i+t.length+3)),r=e.indexOf(`<${t}>`,i)}return n}var Rt=1e5,zt=e=>e.fmt===`string`||B[e.fmt]!==void 0;function H(e,t,n){let r=e[n];if((r===1||r===4||r===8)&&n+1+r<=e.length)return r===1?[e[n+1],2]:r===4?[t.getUint32(n+1,!0),5]:[a(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function Bt(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+B[r.fmt]*r.nch<=e.length?n+B[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=H(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*Vt(e,t){let n=new Uint8Array;for await(let r of e.windows(4,e.size-4)){t?.throwIfAborted();let i=r.bytes,a=r.offset-n.length;if(n.length){let e=new Uint8Array(n.length+i.length);e.set(n),e.set(i,n.length),i=e}let o=T(i),s=0;for(;!(s+1>i.length);){let t=i[s];if(s+1+t>i.length)break;let[n,r]=H(i,o,s),c=s+r+n;if(a+c>e.size)return;if(c>i.length)break;yield{tag:i[s+r]|i[s+r+1]<<8,body:i.subarray(s+r+2,c)},s=c}n=i.slice(s)}}function Ht(e,t,n){let r=t-e.i0,i=n-e.t0;e.n++,e.si+=r,e.st+=i,e.sii+=r*r,e.sit+=r*i}function Ut(e){let t=e.n*e.sii-e.si*e.si;e.b=t>0?(e.n*e.sit-e.si*e.st)/t:0,e.a=(e.st-e.b*e.si)/Math.max(1,e.n)}function Wt(e){if(e.length===0)return[0,0];if(e.length===1)return[e[0][1],0];let t={i0:e[0][0],t0:0,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0};for(let[n,r]of e)Ht(t,n,r);return Ut(t),[t.a-t.b*t.i0,t.b]}function Gt(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}var Kt={...e,async plan(e,t){let n=new Map,r=``;for await(let e of Vt(t)){let t=T(e.body);if(e.tag===1)r=u(e.body);else if(e.tag===2){let r=t.getUint32(0,!0),i=u(e.body.subarray(4)),a=parseInt(V(i,`channel_count`),10)||1;if(!(a>=1&&a<=Rt))throw Error(`This XDF file is damaged (a stream with ${a} channels).`);let o=Lt(i,`channel`);n.set(r,{id:r,name:V(i,`name`)||`Stream ${r}`,nch:a,srate:parseFloat(V(i,`nominal_srate`))||0,fmt:V(i,`channel_format`)||`float32`,labels:Array.from({length:a},(e,t)=>V(o[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:a},(e,t)=>V(o[t]??``,`unit`)),count:0,segs:[],clock:[],c0:0,c1:0,lastTs:NaN})}else if(e.tag===3){let r=n.get(t.getUint32(0,!0));if(!r||!zt(r))continue;let[i,a]=H(e.body,t,4),o=4+a,s=B[r.fmt],c=r.srate>0?Math.max(1,500/r.srate):1/0;for(let n=0;n<i&&!(Bt(e.body,t,o,r)<0);n++){let n;if(e.body[o++]===8?(n=t.getFloat64(o,!0),o+=8):n=r.lastTs+(r.srate>0?1/r.srate:0),r.fmt===`string`)for(let n=0;n<r.nch;n++){let[n,r]=H(e.body,t,o);o+=r+n}else o+=s*r.nch;if(r.srate>0){let e=r.segs[r.segs.length-1];(!e||n-r.lastTs>c)&&r.segs.push(e={i0:r.count,t0:n,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0}),Ht(e,r.count,n)}else r.count===0&&r.segs.push({i0:0,t0:n,n:1,si:0,st:0,sii:0,sit:0,a:0,b:0});r.lastTs=n,r.count++}}else if(e.tag===4){let e=n.get(t.getUint32(0,!0));e&&e.clock.push([t.getFloat64(4,!0),t.getFloat64(12,!0)])}}let i=[],a=[...n.values()].sort((e,t)=>e.id-t.id).filter(e=>(zt(e)||i.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),zt(e))),o=1/0;for(let e of a){[e.c0,e.c1]=Wt(e.clock);for(let t of e.segs)Ut(t);if(e.count===0)continue;let t=e.srate>0?Gt(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;o=Math.min(o,t)}let s=f(a.map(e=>e.name),[]),c=a.map((e,t)=>({name:s[t],channels:e.labels.map((t,n)=>({name:t,unit:e.units[n],...e.fmt===`string`?{text:!0,sparse:!0}:{}})),samples:e.count,time:{kind:`timestamps`},rateHz:e.srate>0?e.srate:null,irregular:e.srate===0})),l=V(r,`version`);return{format:`XDF ${l||`1.0`}`,startTime:null,groups:c,meta:{header:l},events:[],notes:i,state:{streams:a,origin:Number.isFinite(o)?o:0}}},async*stream(e){let t=e.plan.state,n=8192,r=new Map,i=e=>e.sel.map(()=>e.s.fmt===`string`?Array(n):new Float64Array(n));for(let a of e.selection){let o=t.streams[a.group],s={g:a.group,s:o,sel:E(e,a.group),time:new Float64Array(n),cols:[],n:0,start:0,seg:0,i:0,raw:NaN};s.cols=i(s),r.set(o.id,s)}let a=e=>{let t={group:e.g,time:e.time.slice(0,e.n),start:e.start,length:e.n,columns:e.cols.map(t=>t.slice(0,e.n))};return e.start+=e.n,e.n=0,e.time=new Float64Array(n),e.cols=i(e),t};for await(let i of Vt(e.io,e.signal)){if(i.tag!==3)continue;let e=T(i.body),o=r.get(e.getUint32(0,!0));if(!o)continue;let s=o.s,[c,l]=H(i.body,e,4),d=4+l,f=B[s.fmt],p=[];for(let r=0;r<c&&!(Bt(i.body,e,d,s)<0);r++){let r;i.body[d++]===8?(r=e.getFloat64(d,!0),d+=8):r=o.raw+(s.srate>0?1/s.srate:0),o.raw=r;let c;if(s.srate>0){for(;o.seg+1<s.segs.length&&s.segs[o.seg+1].i0<=o.i;)o.seg++;c=Gt(s,s.segs[o.seg],o.i)}else c=r+s.c0+s.c1*r;if(o.time[o.n]=c-t.origin,s.fmt===`string`){let n=[];for(let t=0;t<s.nch;t++){let[t,r]=H(i.body,e,d);n.push(u(i.body.subarray(d+r,d+r+t))),d+=r+t}o.sel.forEach((e,t)=>{o.cols[t][o.n]=n[e]}),p.push({time:c-t.origin,text:n.join(` `)})}else o.sel.forEach((t,n)=>{let r=d+t*f,i=o.cols[n];switch(s.fmt){case`float32`:i[o.n]=e.getFloat32(r,!0);break;case`double64`:i[o.n]=e.getFloat64(r,!0);break;case`int8`:i[o.n]=e.getInt8(r);break;case`int16`:i[o.n]=e.getInt16(r,!0);break;case`int32`:i[o.n]=e.getInt32(r,!0);break;default:i[o.n]=e.getInt32(r+4,!0)*4294967296+e.getUint32(r,!0)}}),d+=f*s.nch;o.i++,++o.n===n&&(yield a(o))}p.length&&(yield{group:o.g,time:new Float64Array,start:o.start,length:0,columns:o.sel.map(()=>new Float64Array),events:p})}for(let e of r.values())e.n&&(yield a(e))}},qt=2,Jt=8,Yt=4,Xt=32,Zt=64,Qt=4713,$t=4714,U=32,W=68,G={1:1,2:2,3:4,4:8,5:1,6:2,7:4,8:8,9:4,10:8,25:4,26:8,33:1,68:16},en={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:W},tn=65536,nn=65536,rn=(e,t,n)=>n?r(e,t+8,n)+a(e,t,n)/2**64:r(e,t,n)+a(e,t+8,n)/2**64;function an(e,t,n,i,o){switch(i){case U:{let r=e.getUint32(n,o);return[u(t.subarray(n+4,n+4+r)),4+r]}case 1:return[e.getInt8(n),1];case 2:return[e.getInt16(n,o),2];case 3:return[e.getInt32(n,o),4];case 4:return[r(e,n,o),8];case 5:return[e.getUint8(n),1];case 6:return[e.getUint16(n,o),2];case 7:return[e.getUint32(n,o),4];case 8:return[a(e,n,o),8];case 9:case 25:return[e.getFloat32(n,o),4];case 10:case 26:return[e.getFloat64(n,o),8];case 33:return[e.getUint8(n)!==0,1];case W:return[rn(e,n,o),16];default:throw Error(`This TDMS file has a property of type ${i}, which Kymoscope cannot read.`)}}function on(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}var sn=4294967295;function cn(e){if(e.has(`NI_Number_Of_Scales`))return Number(e.get(`NI_Number_Of_Scales`));let t=0;for(let n of e.keys()){let e=/^NI_Scale\[(\d+)\]_Scale_Type$/.exec(n);e&&(t=Math.max(t,Number(e[1])+1))}return t}function ln(e,t,n){let r=e.find(e=>cn(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===sn||e<0||a>8)return e=>e;let o=r.get(`NI_Scale[${e}]_Scale_Type`);if(o===void 0)return e=>e;if(o===`Linear`){let t=Number(r.get(`NI_Scale[${e}]_Linear_Slope`)),n=Number(r.get(`NI_Scale[${e}]_Linear_Y_Intercept`)??0),o=i(Number(r.get(`NI_Scale[${e}]_Linear_Input_Source`)??sn),a+1);return o&&(e=>t*o(e)+n)}if(o===`Polynomial`){let o=Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients_Size`)??4);if(!(Number.isInteger(o)&&o>=0&&o<=64))return t.push(`${n}: an NI polynomial scale with ${o} coefficients is not supported; raw values are shown.`),null;let s=Array.from({length:o},(t,n)=>Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients[${n}]`))),c=i(Number(r.get(`NI_Scale[${e}]_Polynomial_Input_Source`)??sn),a+1);return c&&(e=>{let t=c(e),n=0;for(let e=o-1;e>=0;e--)n=n*t+s[e];return n})}return t.push(`${n}: NI scale type ${String(o)} is not supported; raw values are shown.`),null};return i(cn(r)-1,0)}var un={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function dn(e,t,n,i,o,s,c,l){let u=un[e];if(u&&s&&i===G[e]&&(t.byteOffset+n)%i===0){c.set(new u(t.buffer,t.byteOffset+n,o),l);return}switch(e){case 1:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getInt8(n);return;case 2:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getInt16(n,s);return;case 3:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getInt32(n,s);return;case 4:for(let e=0;e<o;e++,n+=i)c[l+e]=r(t,n,s);return;case 5:case 33:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getUint8(n);return;case 6:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getUint16(n,s);return;case 7:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getUint32(n,s);return;case 8:for(let e=0;e<o;e++,n+=i)c[l+e]=a(t,n,s);return;case 9:case 25:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getFloat32(n,s);return;case 10:case 26:for(let e=0;e<o;e++,n+=i)c[l+e]=t.getFloat64(n,s);return;case W:for(let e=0;e<o;e++,n+=i)c[l+e]=rn(t,n,s);return;default:c.fill(NaN,l,l+o)}}async function fn(e,t,n){let r=new Map,i=[],o=[],s=new Map,c=new Map,l=t??e,d=0,f=0;for(;d+28<=e.size&&f+28<=l.size;){let p=t?f:d,m=await l.read(p,28),h=T(m);if(!(m[0]===84&&m[1]===68&&m[2]===83&&(m[3]===109||m[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let g=h.getUint32(4,!0),_=!(g&Zt),v=a(h,12,_),y=a(h,20,_),b=v>=2**53?e.size:Math.min(e.size,d+28+v);if(y>b-d-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(g&qt){let e=await l.read(p+28,y),t=T(e);g&Yt&&(o=[],s=new Map);let i=0,d=t.getUint32(i,_);i+=4;for(let l=0;l<d;l++){let l=t.getUint32(i,_),d=u(e.subarray(i+4,i+4+l));i+=4+l;let f=on(d),p=r.get(d);p||r.set(d,p={path:d,group:f?.[0]??``,name:f?.[1]??``,type:0,props:new Map,pieces:[],total:0});let m=t.getUint32(i,_);i+=4;let h=null;if(m===4294967295)h=null;else if(m===0)h=c.get(p)??null;else if(m===Qt||m===$t){let e=a(t,i+8,_),r=t.getUint32(i+16,_),o=m===Qt?20:17,s=i+20,c=en[t.getUint32(s,_)]??0,l=t.getUint32(s+8,_);i=s+r*o;let u=t.getUint32(i,_);i+=4;let d=0;for(let e=0;e<u;e++)d+=t.getUint32(i+4*e,_);i+=4*u,m===$t?n.push(`${p.name}: DAQmx digital line data is not supported; skipped.`):(r>1&&n.push(`${p.name}: only the first of its ${r} DAQmx scalers is read.`),h={type:c,count:e,bytes:0,daqmx:{byteOffset:l,stride:d}})}else{let e=t.getUint32(i,_),n=a(t,i+8,_),r=e===U?a(t,i+16,_):n*(G[e]??0);i+=m-4,h={type:e,count:n,bytes:r,daqmx:null}}h&&(p.type=h.type,c.set(p,h));let g=t.getUint32(i,_);i+=4;for(let n=0;n<g;n++){let n=t.getUint32(i,_),r=u(e.subarray(i+4,i+4+n));i+=4+n;let a=t.getUint32(i,_);i+=4;let[o,s]=an(t,e,i,a,_);p.props.set(r,o),i+=s}let v=s.get(p);v===void 0?s.set(p,o.push({obj:p,idx:h})-1):o[v].idx=h}}if(g&Jt){let e=d+28+y,t=o.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(g&Xt)!==0,a=0,s=0;n.length?(s=n[0].idx.daqmx.stride,a=n[0].idx.count*s):r?(s=t.reduce((e,t)=>e+(G[t.idx.type]??0),0),a=(t[0]?.idx.count??0)*s):a=t.reduce((e,t)=>e+t.idx.bytes,0);let c=a>0?Math.floor((b-e)/a):0,l=i.push({rawStart:e,chunkSize:a,chunks:c,le:_})-1,u=0;for(let e of t){let t=e.idx,n=G[t.type]??0,i=t.daqmx?{seg:l,count:t.count,offset:t.daqmx.byteOffset,bytes:0,stride:s,type:t.type}:{seg:l,count:t.count,offset:u,bytes:t.bytes,stride:r?s:n,type:t.type};t.daqmx||(u+=r?n:t.bytes),i.type===U?i.count=Math.min(i.count,Math.floor(i.bytes/4)):n>0&&(i.count=Math.min(i.count,i.stride>0?Math.max(0,Math.floor((a-i.offset-n)/i.stride)+1):0)),e.obj.pieces.push(i),c&&(e.obj.total+=i.count*c)}}if(d=b,f+=28+y,b>=e.size)break}return{objs:[...r.values()],segments:i}}var pn={..._,async plan(e,t){let n=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),r=[],{objs:i,segments:a}=await fn(t,n?new C(n):null,r),o=i.find(e=>e.path===`/`)?.props,s=i.filter(e=>e.name&&e.total>0&&(e.type===U||G[e.type])),c=new Set(s);for(let e of i)e.name&&e.total>0&&!c.has(e)&&r.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let l=s.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),u=l.reduce((e,t)=>Math.min(e,t),l.length?1/0:0),d=new Map;for(let e of s){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=d.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),d.set(e.group,n)}let f=[],p=[];for(let[e,t]of d)for(let n of t.values()){let r=n[0].props.get(`wf_increment`),i=typeof r==`number`&&r>0?1/r:null,a=i?null:n.find(e=>e.type===W)??n.find(e=>e.type!==U&&/^(time|timestamp|t)$/i.test(e.name))??null,o=n.filter(e=>e!==a),s=n[0].props.get(`wf_start_time`),c=i?Number(n[0].props.get(`wf_start_offset`)??0)+(typeof s==`number`?s-u:0):0;f.push({name:t.size===1?e:`${e} (${i?+i.toFixed(6):n[0].total} ${i?`Hz`:`samples`})`,channels:o.map(e=>({name:e.name,unit:String(e.props.get(`unit_string`)??``),text:e.type===U})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),p.push({channels:o,time:a,origin:0})}if(f.length===0)throw Error(`This TDMS file has no channels with data.`);let m=[];for(let e of p){if(!e.time)continue;let n=e.time.pieces[0],r=a[n.seg],i=await t.read(r.rawStart+n.offset,G[n.type]??8),o=new Float64Array(1);dn(n.type,T(i),0,0,1,r.le,o,0),m.push(o[0])}let h=m.reduce((e,t)=>Math.min(e,t),m.length?1/0:0);for(let e of p)e.origin=h;let g=new Date(Date.UTC(1904,0,1)+u*1e3),_=u&&Number.isFinite(g.getTime())?g.toISOString():null,v={objs:i,segments:a,groups:p},y={};for(let[e,t]of o??[])typeof t==`string`&&(y[e]=t);return{format:`TDMS`,startTime:_,groups:f,meta:y,events:[],notes:r,state:v}},async*stream(e){for(let t of e.selection)yield*hn(e,t.group)},streamGroup:(e,t)=>hn(e,t)};function mn(e,t,n,r,i,a){let o=0;for(;o<i&&r.pi<t.pieces.length;){let s=t.pieces[r.pi],c=e.segments[s.seg];if(r.chunk>=c.chunks){r.pi++,r.chunk=0,r.row=0;continue}let l=Math.min(i-o,s.count-r.row),u=c.rawStart+r.chunk*c.chunkSize+s.offset;if(s.type===U)a.push({ch:n,at:u,end:u+s.bytes,rows:l,first:r.row,out:o,piece:s,le:c.le,range:0});else{let e=u+r.row*s.stride;a.push({ch:n,at:e,end:e+(l-1)*s.stride+G[s.type],rows:l,first:r.row,out:o,piece:s,le:c.le,range:0})}o+=l,r.row+=l,r.row>=s.count&&(r.chunk++,r.row=0)}}async function*hn(e,t){let n=e.plan.state,r=n.groups[t],i=E(e,t).map(e=>r.channels[e]),a=r.time?[r.time,...i]:i;if(!a.length)return;let o=new Map(n.objs.map(e=>[e.path,e.props])),s=e=>o.get(e)??new Map,c=s(`/`),l=a.map(e=>ln([e.props,s(`/'${e.group.replace(/'/g,`''`)}'`),c],[],e.name)),d=a.map(()=>({pi:0,chunk:0,row:0})),f=a.reduce((e,t)=>Math.min(e,t.total),1/0);for(let i=0;i<f;){e.signal?.throwIfAborted();let o=Math.min(tn,f-i),s=[];a.forEach((e,t)=>mn(n,e,t,d[t],o,s));let c=s.slice().sort((e,t)=>e.at-t.at),p=[];for(let e of c){let t=p[p.length-1];t&&e.at<=t.end+nn&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):p.push({at:e.at,end:e.end}),e.range=p.length-1}let m=[];for(let t of p)m.push(await e.io.slice(t.at,t.end-t.at));let h=m.map(T),g=a.map(e=>e.type===U?Array(o).fill(null):new Float64Array(o).fill(NaN));for(let e of s){let t=e.at-p[e.range].at,n=e.piece;if(n.type===U){let r=m[e.range],i=h[e.range],a=t+4*n.count,o=g[e.ch];for(let n=0;n<e.rows;n++){let s=e.first+n,c=s===0?0:i.getUint32(t+4*(s-1),e.le),l=i.getUint32(t+4*s,e.le);o[e.out+n]=u(r.subarray(a+c,a+l))}}else dn(n.type,h[e.range],t,n.stride,e.rows,e.le,g[e.ch],e.out)}for(let e=0;e<a.length;e++){let t=l[e],n=g[e];if(t&&n instanceof Float64Array)for(let e=0;e<o;e++)n[e]=t(n[e])}let _=null;if(r.time){_=g.shift();for(let e=0;e<o;e++)_[e]-=r.origin}yield{group:t,time:_,start:i,length:o,columns:g},i+=o}}var gn=e=>!!e&&typeof e.keys==`function`,_n=1e5;function vn(){let e=new Set,t=0,n=!1;return{enter(t){let r=null;try{r=t.create_reference?Array.prototype.join.call(t.create_reference().ref_data,`,`):null}catch{r=null}return r===null?!0:e.has(r)?(n=!0,!1):(e.add(r),!0)},count:()=>++t<=_n,note:()=>t>1e5?`This file has more than ${_n.toLocaleString(`en-US`)} objects (or links that repeat its groups); only the first were read.`:n?`Some groups of this file link back to a group already read; each was read once.`:null}}function yn(e,t,n,r){return t.reduce((e,t)=>e*t,1)*Math.max(1,e.metadata.size||1)>(r?n*1032+1024:n)}var bn=e=>!!e&&typeof e.slice==`function`,xn=null,K=null,Sn=new WeakMap;function Cn(){!xn||K||(K=xn(),K.catch(()=>{K=null}))}function wn(e){if(!xn)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));Cn();let t=Sn.get(e);return t||(t=K.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),Sn.set(e,t),t.catch(()=>Sn.delete(e))),t}var Tn=new WeakMap;function q(e,t,n){let r=Tn.get(e);r||Tn.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function J(e){return e instanceof Float64Array?e:e instanceof BigInt64Array||e instanceof BigUint64Array?Float64Array.from(e,e=>Number(e)):ArrayBuffer.isView(e)?new Float64Array(e):Float64Array.from(e)}var En={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function Y(e,...t){for(let n of t){let t=e[n]?.value;if(typeof t==`string`)return t;if(Array.isArray(t)&&typeof t[0]==`string`)return t[0]}return``}function Dn(e,...t){for(let n of t){let t=e[n]?.value,r=typeof t==`number`?t:ArrayBuffer.isView(t)?Number(t[0]):NaN;if(Number.isFinite(r))return r}return null}var On=0,kn=1,An=3,jn=6,Mn=new Set([1,2,3,4,5,6]),Nn=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,Pn=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function Fn(e,t,n,r,i,a,o=0){i.set(n,t.attrs);for(let s of t.keys()){if(!a.count())return;let c=n===`/`?`/${s}`:`${n}/${s}`,l=t.get(s);if(gn(l))o<16&&a.enter(l)&&Fn(e,l,c,r,i,a,o+1);else if(bn(l)){let t=q(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}var X=e=>e===`/`?`root`:e.slice(1),In=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function Ln(e,t){let n=q(e,t.path);if(t.col===null)return J(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}var Rn={...t,async plan(e){let t=await wn(e.main);try{let n=[],r=new Map,i=vn();i.enter(t.root),Fn(t.root,t.root,`/`,n,r,i);let a=[],o=i.note();o&&a.push(o);let s=new Map,c=[],l=0;for(let t of n){let n=t.ds.metadata.shape??[],r=t.ds.metadata.type,i=t.ds.metadata.chunks?t.ds.filters??[]:[],o=i.find(e=>!Mn.has(e.id)),u=!o;if(u&&i.length>0&&n.length>0&&n.every(e=>e>0))try{t.ds.slice(n.map(()=>[0,1]))}catch{u=!1}if(!u){a.push(`${t.path}: compressed with a filter Kymoscope cannot read${o?` (${o.name||o.id})`:``}; skipped.`);continue}if(yn(t.ds,n,e.main.size,i.length>0)){a.push(`${t.path}: larger than the file can hold (never written, or damaged); skipped.`);continue}if(n.length===1&&n[0]>1&&(r===On||r===kn||r===An)){let e=`${t.parent}|${n[0]}`,r=s.get(e)??{parent:t.parent,n:n[0],leaves:[]};r.leaves.push(t),s.set(e,r)}else if(n.length===2&&n[0]>1&&n[1]<=4096&&(r===On||r===kn)){let e=Dn(t.attrs,...Pn);c.push({name:X(t.path),kind:`matrix`,rows:n[0],rate:e,time:null,origin:0,cols:Array.from({length:n[1]},(e,n)=>({path:t.path,col:n,text:!1,factor:1}))})}else if(n.length===1&&r===jn){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===On||e.type===kn?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>Nn.test(e.name));c.push({name:X(t.path),kind:`compound`,rows:n[0],rate:null,origin:0,time:r??null,cols:e.filter(e=>e!==r)})}else l++}for(let e of s.values()){let t=[...s.values()].filter(t=>t.parent===e.parent).length>1,n=e.leaves.find(e=>Y(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>Nn.test(e.name)&&e.ds.metadata.type!==An),i=n?En[Y(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:Dn(r.get(e.parent)??{},...Pn);c.push({name:t?`${X(e.parent)} (${e.n} rows)`:X(e.parent),kind:`vectors`,rows:e.n,rate:a,origin:0,time:n?{path:n.path,col:null,text:!1,factor:i}:null,cols:e.leaves.filter(e=>e!==n).map(e=>({path:e.path,col:null,text:e.ds.metadata.type===An,factor:1}))})}l&&a.push(`${l} dataset${l===1?``:`s`} with other shapes or types (images, references, 3-D) skipped.`),c.sort((e,t)=>e.name.localeCompare(t.name));let u=c.map((e,t)=>e.time||e.rate?t:-1).filter(e=>e>=0),d=1/0;for(let e of c)e.time&&(d=Math.min(d,await Ln(t.root,e.time)));for(let e of c)e.origin=Number.isFinite(d)?d:0;let f=new Map(n.map(e=>[e.path,e]));for(let e of c)e.chunk=[...e.cols,...e.time?[e.time]:[]].reduce((e,t)=>Math.max(e,f.get(t.path).ds.metadata.chunks?.[0]??0),0);let p=e=>Y(f.get(e.path).attrs,`units`,`unit`,`Units`,`UNITS`),m=(e,t)=>e.kind===`matrix`?`${e.name.split(`/`).pop()}[${t.col+1}]`:e.kind===`compound`?f.get(t.path).ds.metadata.compound_type.members[t.col].name:t.path.split(`/`).pop(),h=c.map(e=>({name:e.name,channels:e.cols.map(t=>({name:m(e,t),unit:e.kind===`vectors`?p(t):``,text:t.text})),samples:e.rows,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}));if(h.length===0)throw Error(`This HDF5 file has no datasets Kymoscope can plot.`);let g=h.length>20||h.length>1&&u.length<h.length,_=g?u.length?u:[c.reduce((e,t,n)=>t.rows*t.cols.length>c[e].rows*c[e].cols.length?n:e,0)]:void 0;return g&&a.push(`Only the groups with a time base are read unless you choose others in the channel picker.`),{format:`HDF5`,startTime:null,groups:h,meta:{},events:[],notes:a,pick:g,defaultGroups:_,state:{groups:c}}}finally{t.close()}},async*stream(e){for(let t of e.selection)yield*zn(e,t.group)},streamGroup:(e,t)=>zn(e,t)};async function*zn(e,t){let n=e.plan.state.groups[t],r=E(e,t).map(e=>n.cols[e]),i=await wn(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(In(r.length+1)/a)))*a:In(r.length+1);for(let a=0;a<n.rows;a+=o){e.signal?.throwIfAborted();let s=Math.min(n.rows,a+o),c=s-a,l=null,u=e=>{let t=q(i.root,e.path);if(n.kind===`vectors`){let n=t.slice([[a,s]]);if(e.text)return Array.from(n,e=>e==null?null:String(e));let r=J(n);if(e.factor!==1)for(let t=0;t<c;t++)r[t]*=e.factor;return r}let r=new Float64Array(c);if(n.kind===`matrix`){let n=(t.shape??[0,1])[1],i=l??=t.slice([[a,s],[0,n]]);for(let t=0;t<c;t++)r[t]=Number(i[t*n+e.col])}else{let n=l??=t.slice([[a,s]]);for(let t=0;t<c;t++)r[t]=Number(n[t][e.col])*e.factor}return r},d=null;if(n.time){d=u(n.time);for(let e=0;e<c;e++)d[e]-=n.origin}yield{group:t,time:d,start:a,length:c,columns:r.map(u)}}}finally{i.close()}}var Bn=/^(time|t|tout|timestamps?)$/i,Vn=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,Hn=e=>e.slice(e.lastIndexOf(`.`)+1),Un=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function Wn(e,t){let n=/^(.*)\.values(\[\d+\])?$/.exec(e.name),r=n&&(t.get(`${n[1]}.label`)||t.get(`${n[1]}.blockName`));return r?{...e,name:`${r}${n[2]??``}`}:e}function Gn(e,t,n){let r=new Map;for(let t of e){if(!(t.length>1))continue;let e=r.get(t.length);e?e.push(t):r.set(t.length,[t])}let i=[...n].filter(([e])=>Vn.test(Hn(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>Bn.test(Hn(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?Un(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>Wn(e,t)),time:r,rate:r?null:a,origin:0})}return o}function Kn(e){return e.map(e=>({name:e.name,channels:e.channels.map(e=>({name:e.name,unit:``})),samples:e.channels[0]?.length??e.time?.length??0,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}))}async function qn(e){let t=1/0;for(let n of e)n.time&&(t=Math.min(t,(await n.time.read(0,1))[0]));for(let n of e)n.origin=Number.isFinite(t)?t:0}var Jn=class{#e;size;constructor(e){this.#e=e,this.size=e.size}read(e,t){return t>=65536?this.#e.slice(e,t):this.#e.read(e,t)}release(){}},Yn=class{#e;#t;#n;#r=null;keep=!0;size;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.size=r.length}async read(e,t){return this.#r??=await F(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}},Z={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function Xn(e,t,n,r,i=1){let a=T(t),o=r.length,s=Z[e]*i;if(e===9&&i===1&&n){r.set(t.byteOffset%8==0?new Float64Array(t.buffer,t.byteOffset,o):new Float64Array(t.slice(0,o*8).buffer));return}switch(e){case 1:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt8(t);return;case 2:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint8(t);return;case 3:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt16(t,n);return;case 4:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint16(t,n);return;case 5:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t,n);return;case 6:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t,n);return;case 7:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat32(t,n);return;case 9:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat64(t,n);return;case 12:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;case 13:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;default:r.fill(NaN)}}async function Q(e,t,n){let r=T(await e.read(t,8)),i=r.getUint32(0,n);if(i>>>16)return{type:i&65535,bytes:i>>>16,data:t+4,next:t+8};let a=r.getUint32(4,n);return{type:i,bytes:a,data:t+8,next:i===15?t+8+a:t+8+a+(8-a%8)%8}}function Zn(e,t,n,r,i){let[a,o]=t,s=Z[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?Xn(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):Xn(r.type,await n.read(r.data+(e+a*t)*s,((o-a-1)*t+1)*s),i,c,t),c};return a===1||o===1?[{name:e,length:a*o,read:c(0,1)}]:a>=o?Array.from({length:o},(t,n)=>({name:`${e}[${n+1}]`,length:a,read:c(n*a,1)})):Array.from({length:a},(t,n)=>({name:`${e}[${n+1}]`,length:o,read:c(n,a)}))}async function Qn(e,t,n,r,i,a,o){let c=t,d=await Q(e,c,n),f=T(await e.read(d.data,8)).getUint32(0,n),p=f&255;c=d.next;let m=await Q(e,c,n);if(m.bytes>128){a.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let h=T(await e.read(m.data,m.bytes)),g=Array.from({length:m.bytes/4},(e,t)=>h.getInt32(4*t,n));c=m.next;let _=await Q(e,c,n),v=s(await e.read(_.data,_.bytes));c=_.next;let y=i??v,b=r?`${r}.${y}`:y,x=g.reduce((e,t)=>e*t,1);if(p>=6&&p<=15){if(x===0)return;let t=await Q(e,c,n);if(f&2048&&a.notes.push(`${b}: the imaginary part was skipped.`),g.length>2){a.notes.push(`${b}: arrays with more than two dimensions are skipped.`);return}if(!Z[t.type])return;if(!(x>0)||x*Z[t.type]>t.bytes||t.data+t.bytes>e.size){a.notes.push(`${b}: its data is shorter than its dimensions (damaged); skipped.`);return}if(x===1){let r=new Float64Array(1);Xn(t.type,await e.read(t.data,Z[t.type]??8),n,r),a.scalars.set(b,r[0]);return}a.channels.push(...Zn(b,g,e,t,n));return}if(p===4){let t=await Q(e,c,n);if(t.bytes>$n)return;let r=await e.read(t.data,t.bytes),i=t.type===3||t.type===4||t.type===17?new TextDecoder(n?`utf-16le`:`utf-16be`).decode(r.subarray(0,r.length&-2)):u(r);g[0]<=1&&a.strings.set(b,i);return}if(p===2){let t=await Q(e,c,n),r=T(await e.read(t.data,4)).getInt32(0,n);c=t.next;let i=await Q(e,c,n);if(!(r>0))return;let s=await e.read(i.data,i.bytes),u=Array.from({length:Math.floor(s.length/r)},(e,t)=>l(s.subarray(t*r,(t+1)*r)));if(c=i.next,u.length===0||x*u.length*8>e.size-c){x>0&&u.length>0&&a.notes.push(`${b}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<x;t++){let r=x>1?`${b}(${t+1})`:b;for(let t of u){let i=await Q(e,c,n);i.type===14&&i.bytes>0&&o<16&&await Qn(e,i.data,n,r,t,a,o+1),c=i.next}}return}p===1?a.notes.push(`${b}: cell arrays are skipped.`):p===5?a.notes.push(`${b}: sparse arrays are skipped.`):a.notes.includes(er)||a.notes.push(er)}var $n=1<<17,er=`MATLAB objects (timeseries, SimulationOutput) were skipped: save them as 'Structure with time' or as structs.`,tr=512<<20;async function nr(e){let t=s((await e.read(0,128)).subarray(126,128))===`IM`,n={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},r=new Jn(e),i=0;for(let a=128;a+8<=e.size;){let o=await Q(r,a,t);if(o.type===15){if(o.bytes>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let r=await e.slice(o.data,o.bytes),a=await F(r,-1,8),s=a.length<8?0:8+T(a).getUint32(4,t);if(s>d(o.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(s>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let c=await F(r,s,s),l=new Yn(e,o.data,o.bytes,c);n.sources.push(l),i+=c.length;let u=await Q(l,0,t);if(u.type===14&&await Qn(l,u.data,t,``,null,n,0),i>tr)for(let e of n.sources)e.keep=!1,e.release()}else o.type===14&&await Qn(r,o.data,t,``,null,n,0);a=o.next}return n}var rr=65536,ir=new Set([`double`,`single`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`logical`]);function ar(e,t){let n={channels:[],strings:new Map,scalars:new Map,notes:[]},r=vn();r.enter(e);let i=t=>q(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:J(t?i(e).slice([[0,n],[a,o]]):i(e).slice([[a,o],[0,n]]))}),r.v)},o=(e,s,c,l)=>{for(let u of e.keys()){if(!r.count())return;if(u.startsWith(`#`))continue;let d=e.get(u);if(!d)continue;let f=`${s}/${u}`,p=c?`${c}.${u}`:u,m=d.attrs,h=Y(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(gn(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!bn(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>rr)continue;let e=J(d.slice(g.map(e=>[0,e])));n.strings.set(p,new TextDecoder(`utf-16le`).decode(Uint16Array.from(e)))}else if(ir.has(h)&&g.length===2&&yn(d,g,t,!!d.metadata.chunks))n.notes.push(`${p}: larger than the file can hold (never written, or damaged); skipped.`);else if(ir.has(h)&&g.length===2){let[e,t]=g;if(e*t===1){n.scalars.set(p,J(i(f).slice([[0,1],[0,1]]))[0]);continue}if(e===1||t===1){let r=e*t;n.channels.push({name:p,length:r,read:async(t,n)=>J(e===1?i(f).slice([[0,1],[t,n]]):i(f).slice([[t,n],[0,1]]))})}else if(t>=e){let r=a(f,!0,e);for(let i=0;i<e;i++)n.channels.push({name:`${p}[${i+1}]`,length:t,read:async(e,t)=>r(e,t).slice(i*(t-e),(i+1)*(t-e))})}else{let r=a(f,!1,t);for(let i=0;i<t;i++)n.channels.push({name:`${p}[${i+1}]`,length:e,read:async(e,n)=>{let a=r(e,n),o=new Float64Array(n-e);for(let e=0;e<o.length;e++)o[e]=a[e*t+i];return o}})}}else h===`cell`?n.notes.push(`${p}: cell arrays are skipped.`):h&&n.notes.push(`${p}: MATLAB class ${h} is skipped.`)}};o(e,``,``,0);let s=r.note();return s&&n.notes.push(s),n}var or=e=>Math.max(4096,Math.min(1<<18,Math.floor((16<<20)/(8*Math.max(1,e))))),sr={...c,async plan(e,t){let n=i(await t.read(0,20),`MATLAB 7.3`),r,a=[];if(n)r=ar((await wn(e.main)).root,e.main.size);else{let e=await nr(t);a=e.sources,r=e}let o=Gn(r.channels,r.strings,r.scalars).filter(e=>e.channels.length>0);await qn(o);let s=Kn(o);if(s.length===0)throw Error(`This MAT file has no numeric vectors or matrices to plot.`);let c=s.flatMap((e,t)=>e.time.kind===`index`?[]:[t]),l=s.length>1&&c.length<s.length,u=Object.fromEntries(r.strings);for(let[e,t]of r.scalars)u[e]=String(t);return{format:n?`MAT 7.3`:`MAT 5`,startTime:null,groups:s,meta:u,events:[],notes:r.notes,pick:l,defaultGroups:l&&c.length?c:void 0,state:{groups:o,sources:a}}},async*stream(e){for(let t of e.selection)yield*cr(e,t.group)},streamGroup:(e,t)=>cr(e,t)};async function*cr(e,t){let n=e.plan.state,r=n.groups[t],i=E(e,t).map(e=>r.channels[e]),a=r.channels[0].length,o=or(i.length+1);try{for(let n=0;n<a;n+=o){e.signal?.throwIfAborted();let s=Math.min(a,n+o),c=null;if(r.time){c=await r.time.read(n,s);for(let e=0;e<c.length;e++)c[e]-=r.origin}let l=[];for(let e of i)l.push(await e.read(n,s));yield{group:t,time:c,start:n,length:s-n,columns:l}}}finally{for(let e of n.sources)e.release()}}function lr(e,t){let n=/^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*,\s*(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))?/.exec(e??``);if(!n)return[null,0,!1];let[r,i]=t===1991?[n[2],n[1]]:[n[1],n[2]],a=n[3].length===2?2e3+Number(n[3]):Number(n[3]),o=Number(`${n[6]}.${n[7]??`0`}`);return[`${a}-${i.padStart(2,`0`)}-${r.padStart(2,`0`)}T${n[4].padStart(2,`0`)}:${n[5]}:${o.toFixed(3).padStart(6,`0`)}`,Date.UTC(a,Number(i)-1,Number(r),Number(n[4]),Number(n[5]))/1e3+o,(n[7]??``).length>6]}function ur(e){let t=e.split(/\r?\n/).map(e=>e.trim()),[n,,r]=t[0].split(`,`),i=Number(r)||1991,a=/(\d+)A\s*,\s*(\d+)D/i.exec(t[1]??``);if(!a)throw Error(`This COMTRADE .cfg is damaged (second line).`);let o=Number(a[1]),s=Number(a[2]);if(o+s>t.length)throw Error(`This COMTRADE .cfg is damaged (more channels than lines).`);let c=2,l=[];for(let e=0;e<o;e++,c++){let e=(t[c]??``).split(`,`);l.push({name:(e[1]??``).trim(),unit:(e[4]??``).trim(),a:Number(e[5]),b:Number(e[6]??0)||0})}let u=[];for(let e=0;e<s;e++,c++)u.push(((t[c]??``).split(`,`)[1]??``).trim());c++;let d=Number(t[c++]);if(!(Number.isInteger(d)&&d>=0&&d<=t.length-c))throw Error(`This COMTRADE .cfg is damaged (sample rates).`);let f=[];for(let e=0;e<Math.max(1,d);e++,c++){let[e,n]=(t[c]??``).split(`,`).map(Number);f.push([d===0?0:e,n])}let[p,m,h]=lr(t[c++],i),[g,_,v]=lr(t[c++],i),y=(t[c++]||`ASCII`).toUpperCase(),b=Number(t[c++])||1;return{station:n.trim(),rev:i,analog:l,digital:u,rates:f,start:p,trigger:g,startSec:m,triggerSec:_,ft:y,timemult:b,timebase:h||v?1e-9:1e-6}}var dr={BINARY:2,BINARY32:4,FLOAT32:4},fr=16<<20;async function pr(e){let t=s(await e.read(0,Math.min(e.size,1<<20))),n=t.search(/---\s*file type:\s*CFG\s*---\r?\n/i),r=/---\s*file type:\s*DAT\s+(ASCII|BINARY32|BINARY|FLOAT32)(?:\s*:\s*(\d+))?\s*---\r?\n/i.exec(t);if(n<0||!r)throw Error(`This COMTRADE .cff is damaged (no CFG or DAT section in its first megabyte).`);let i=t.indexOf(`
3
- `,n)+1,a=t.slice(i).search(/---\s*file type:\s*(INF|HDR|DAT)/i),o=t.slice(i,a<0?void 0:i+a),c=r.index+r[0].length;return{cfg:o,offset:c,length:r[2]?Number(r[2]):e.size-c}}function mr(e,t,n,r){let i=0,a=0,o=t,s=0;for(let[t,c]of e){for(;o<c&&s<n;)r[s++]=a+(o-i)/t,o++;if(a+=(c-i)/t,i=c,s>=n)return}let c=e[e.length-1];for(;s<n;s++,o++)r[s]=a+(o-i)/c[0]}var hr=e=>e.companions.find(e=>e.name.toLowerCase().endsWith(`.dat`)),gr={...n,async plan(e,t){let n=e.main.name.toLowerCase().endsWith(`.cff`),r,i;if(n){let e=await pr(t);r=e.cfg,i={data:`self`,offset:e.offset,length:e.length}}else{let n=hr(e);if(!n)throw Error(`This COMTRADE .cfg needs its .dat file: drop both together.`);if(t.size>fr)throw Error(`This .cfg is too large to be a COMTRADE configuration file.`);r=s(await t.read(0,t.size)),i={data:`companion`,offset:0,length:n.size}}let a=ur(r);if(a.ft!==`ASCII`&&!dr[a.ft])throw Error(`This COMTRADE file has data file type ${a.ft}, which Kymoscope cannot read.`);let o=Math.ceil(a.digital.length/16),c=a.ft===`ASCII`?0:8+a.analog.length*dr[a.ft]+2*o,l=c?Math.floor(i.length/c):i.length,u=Math.min(a.rates[a.rates.length-1][1]||(c?l:-1),l),d=a.rates.length===1&&a.rates[0][0]>0?a.rates[0][0]:null,f=[`Analog values are shown as recorded (primary or secondary, per the CFG).`];return{format:`COMTRADE ${a.rev} (${a.ft})`,startTime:a.start,meta:{station:a.station,trigger:a.trigger??``},groups:[{name:a.station||`COMTRADE`,channels:[...a.analog.map(e=>({name:e.name,unit:e.unit})),...a.digital.map(e=>({name:e,unit:``}))],samples:u,time:{kind:`timestamps`},rateHz:d}],events:a.start&&a.trigger?[{time:Math.round((a.triggerSec-a.startSec)*1e6)/1e6,text:`Trigger`}]:[],notes:f,state:{...i,cfg:a,samples:u,recordSize:c}}},stream:e=>_r(e)};async function*_r(e){let t=e.plan.state,{cfg:n}=t,r=t.data===`self`?e.io:new C(hr(e.files)),i=E(e,0),a=n.analog.length,o=n.rates[0][0]>0,s=n.timemult*n.timebase,c=65536,l=0,u=(e,t,r)=>{let i=new Float64Array(e);if(o)mr(n.rates,l,e,i);else for(let n=0;n<e;n++)i[n]=t[n]*s;let a={group:0,time:i,start:l,length:e,columns:r};return l+=e,a};if(n.ft===`ASCII`){let o=n.rev>=1999?`99999`:``,s=i.map(e=>e<a?n.analog[e]:null),l=new Float64Array(c),d=i.map(()=>new Float64Array(c)),f=0,p=(e,t,n)=>{let r=e.slice(t,n).split(`,`);if(!(r.length<2)){l[f]=Number(r[1]);for(let e=0;e<i.length;e++){let t=(r[2+i[e]]??``).trim(),n=s[e];d[e][f]=t===``||n&&t===o?NaN:n?n.a*Number(t)+n.b:Number(t)}f++}},m=``,h=new TextDecoder(`latin1`);for await(let n of r.windows(t.offset,t.length)){e.signal?.throwIfAborted();let t=m+h.decode(n.bytes),r=0;for(let e=t.indexOf(`
4
- `,r);e>=0;e=t.indexOf(`
5
- `,r))p(t,r,e),r=e+1,f===c&&(yield u(f,l,d),l=new Float64Array(c),d=i.map(()=>new Float64Array(c)),f=0);m=t.slice(r)}m.trim()&&p(m,0,m.length),f&&(yield u(f,l.slice(0,f),d.map(e=>e.slice(0,f))));return}let d=t.recordSize,f=dr[n.ft],p=Math.max(1,Math.floor(Math.min(te,c*d)/d)),m=t.samples;for await(let s of r.windows(t.offset,Math.min(t.length,t.samples*d),p*d)){e.signal?.throwIfAborted();let t=Math.min(m,Math.floor(s.bytes.length/d));if(t<=0)break;let r=T(s.bytes),c=new Float64Array(t);if(!o)for(let e=0;e<t;e++)c[e]=r.getUint32(e*d+4,!0);yield u(t,c,i.map(e=>{let i=new Float64Array(t);if(e<a){let{a,b:o}=n.analog[e],s=8+e*f;if(n.ft===`BINARY`)for(let e=0,n=s;e<t;e++,n+=d){let t=r.getInt16(n,!0);i[e]=t===-32768?NaN:a*t+o}else if(n.ft===`BINARY32`)for(let e=0,n=s;e<t;e++,n+=d){let t=r.getInt32(n,!0);i[e]=t===-2147483648?NaN:a*t+o}else for(let e=0,n=s;e<t;e++,n+=d)i[e]=a*r.getFloat32(n,!0)+o}else{let n=e-a,o=8+a*f+2*(n>>4),s=1<<(n&15);for(let e=0,n=o;e<t;e++,n+=d)i[e]=r.getUint16(n,!0)&s?1:0}return i})),m-=t}}var $=8192;async function*vr(e){let t=0;for(;t+56<=e.size;){let n=x(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function yr(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}var br=4096;function xr(e){let t=2166136261^e.length;for(let n=0,r=Math.min(e.length,64);n<r;n++)t=Math.imul(t^e[n],16777619);return t>>>0}var Sr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Cr=class{known=new Map;real=new Set;pending=new Set;held=new Set;note(e){for(let t of e){let e=this.known.get(t.name);(!e||t.t>=e.t)&&this.known.set(t.name,{t:t.t,v:t.v,unit:t.unit}),!this.real.has(t.name)&&!this.held.has(t.name)&&this.pending.add(t.name)}}sampled(e){for(let t of[this.pending,this.held])for(let n of t){let r=e[n];if(r){for(let e=0;e<r.length;e++)if(Number.isFinite(r[e])){this.real.add(n),t.delete(n);break}}}}start(e){if(this.pending.size===0||e.t.length===0)return e;let t={...e.columns},n={...e.units};for(let r of this.pending){let i=this.known.get(r),a=new Float64Array(e.t.length).fill(NaN);a[0]=i.v,t[r]=a,i.unit&&!n[r]&&(n[r]=i.unit),this.held.add(r)}return this.pending.clear(),{...e,columns:t,units:n}}end(e,t){if(e===null||this.held.size===0)return null;let n={},r={};for(let e of this.held){let t=this.known.get(e);n[e]=Float64Array.of(t.v),t.unit&&(r[e]=t.unit)}return{at:t,t:[e],columns:n,units:r}}};async function*wr(e,t,n,r){let i=S(e.keys??[]),a=new Map,o=new Map,s=r?null:new Cr,c=null,l=0,u=e=>s?(s.sampled(e.columns),e.t.length&&(c=+e.t[e.t.length-1],l=e.at),s.start(e)):e;for await(let e of vr(t)){let{header:t,messages:c}=y(e);n.t0??=t.t0;for(let e of c){let t=xr(e.bytes),c=o.get(t);if(c&&Sr(c,e.bytes))continue;o.set(t,e.bytes),o.size>br&&o.delete(o.keys().next().value);let l=await i(e.bytes);if(!l){n.lost++;continue}try{if(l.kind===5){let e=h(l.plaintext);a.set(e.id,e);continue}if(l.kind===4){let t=await m(l.plaintext,a);if(!t){n.lost++;continue}let i={at:e.at,t:t.block.t,columns:t.block.columns,units:t.block.units??{},historical:t.historical};t.historical&&s?.sampled(i.columns),(r===void 0||r===!!t.historical)&&(yield t.historical?i:u(i));continue}if(r)continue;if(l.kind===7){let e=b(l.plaintext,a);e&&s?.note(e)}else if(l.kind===3){let t=v(l.plaintext);yield u({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(l.kind===2){let t=ee(l.plaintext);yield u({at:e.at,...yr(Array.isArray(t?.frames)?t.frames:[])})}}catch{n.lost++}}}let d=s?.end(c,l);d&&(yield d)}function Tr(e,t,n){let r=e===null?t:t===null?e:Math.min(e,t);return r===null?{}:r>1e9?{wallOrigin:String(r),wallQuality:`exact`}:Number.isFinite(n)?{wallOrigin:String(r+n),wallQuality:`approx`}:{}}var Er={mdf:jt,edf:It,xdf:Kt,tdms:pn,hdf5:Rn,mat:sr,comtrade:gr,krc:{id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[w],r=new Map([[w,`s`]]),i={lost:0,t0:null},a=0,o=!1,s=null,c=null,l=0,u=-1/0,d=0,f=1/0;for await(let p of wr(e,t,i)){a+=p.t.length,p.historical&&(o=!0);let e=p.t.length;e&&p.historical?c??=+p.t[0]:e&&(s??=+p.t[0],+p.t[0]+l<u&&(l=u+Math.max(0,(p.at-d)/1e3)-+p.t[0]),d=p.at,u=+p.t[e-1]+l,f=Math.min(f,p.at/1e3-u));for(let e of Object.keys(p.columns))e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&p.units[e]&&r.set(e,p.units[e]):(n.push(e),r.set(e,p.units[e]??``)))}let p=n.map(e=>({name:e,unit:r.get(e)??``})),m=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[];return{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:p,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:Tr(s,c,f),events:[],notes:m,state:{names:n,backlog:o}}},async*stream(e){let{names:t,backlog:n=!1}=e.plan.state,r=e.selection.find(e=>e.group===0)?.channels??[],i=new Map(r.map((e,n)=>[t[e],n])),a=i.get(w),o=()=>r.map(()=>new Float64Array($).fill(NaN)),s=new Float64Array($),c=o(),l=0,u=0,d=0,f=-1/0,p=0,m=null,h=()=>{let e={group:0,time:s.slice(0,l),start:u,length:l,columns:c.map(e=>e.slice(0,l))};return u+=l,l=0,s=new Float64Array($),c=o(),e};function*g(e){let t=e.t.length;for(let n=0;n<t;){let r=Math.min(t-n,$-l);for(let t=0;t<r;t++){let r=+e.t[n+t]+d;m??=r,s[l+t]=r-m}if(a!==void 0)for(let t=0;t<r;t++)c[a][l+t]=+e.t[n+t];for(let[t,a]of Object.entries(e.columns)){let e=t===`ElapsedTime`?void 0:i.get(t);if(e===void 0)continue;let o=c[e];if(a instanceof Float64Array||a instanceof Float32Array)o.set(a.subarray(n,n+r),l);else for(let e=0;e<r;e++)o[l+e]=+a[n+e]}l+=r,n+=r,l===$&&(yield h())}}let _=n?wr(e.files,e.io,{lost:0,t0:null},!0):null,v=async()=>{for(let e=await _?.next();e&&!e.done;e=await _.next())if(e.value.t.length)return e.value;return null},y=await v();for await(let t of wr(e.files,e.io,{lost:0,t0:null},n?!1:void 0)){if(e.signal?.aborted)return;let n=t.t.length;if(n!==0){for(+t.t[0]+d<f&&(d=f+Math.max(0,(t.at-p)/1e3)-+t.t[0]),p=t.at;y&&+y.t[0]<+t.t[0];y=await v())yield*g(y);yield*g(t),f=+t.t[n-1]+d}}for(;y&&!e.signal?.aborted;y=await v())yield*g(y);l>0&&(yield h())}}};function Dr(e){let t=Er[e];if(!t)throw Error(`No importer for format ${e}.`);return t}export{Dr as importerFor};
@@ -1,51 +0,0 @@
1
- /**
2
- * Historian ranges as a DataSource (plan P5): a list of pieces, each one block's times with Float32 values per channel
3
- * (raw: lo and hi are the same arrays; a rollup: the bucket's min and max at its middle). The time column is
4
- * `ElapsedTime` in Unix seconds, the same X as a collector's live stream. Decimation reads each piece on its own times,
5
- * so tag groups never share a padded table. Everything is pure computation (sync), like the in-memory sources.
6
- */
7
- import type { ColumnSchema, DataSource, DecimatedSeries, MultiSeriesResult, SeriesQuery, Viewport } from './dataSource';
8
- import type { DatasetRow } from '../parseDataset';
9
- import type { HistoryLevel } from '../historian/khd1';
10
- export interface HistoryPiece {
11
- /** Unix seconds, ascending. */
12
- t: Float64Array;
13
- /** Per channel: the value (raw) or the bucket minimum (rollup). NaN: no value at that time. */
14
- lo: Map<string, Float32Array>;
15
- /** Per channel: the bucket maximum (rollup); the very same Map as `lo` for raw data. */
16
- hi: Map<string, Float32Array>;
17
- level: HistoryLevel;
18
- }
19
- /** First index with t[i] >= x, or with t[i] > x when `after`. */
20
- export declare function bound(t: Float64Array, x: number, after?: boolean): number;
21
- /** Rows [i, j) of a piece (views, nothing copied); null when empty. */
22
- export declare function slicePiece(p: HistoryPiece, i: number, j: number): HistoryPiece | null;
23
- /** The rows of `p` with t in [t0, t1]. */
24
- export declare const clipPiece: (p: HistoryPiece, t0: number, t1: number) => HistoryPiece | null;
25
- /** The overview outside [a, b] with the detail inside: the pan/zoom view (plan P6). */
26
- export declare function splicePieces(overview: HistoryPiece[], detail: HistoryPiece[], a: number, b: number): HistoryPiece[];
27
- export declare class HistoryDataSource implements DataSource {
28
- #private;
29
- readonly pieces: readonly HistoryPiece[];
30
- constructor(pieces: HistoryPiece[], units?: Record<string, string>);
31
- schemaSync(): ColumnSchema[];
32
- getSchema(): Promise<ColumnSchema[]>;
33
- /** Rows are the pieces' rows in time order (a rollup: its minimum); NaN where a piece lacks the channel. */
34
- readColumns(columns: string[], offset: number, limit: number): Promise<Record<string, Float64Array>>;
35
- getSeriesMultiSync(columns: string[], viewport: Viewport, maxPoints: number): MultiSeriesResult;
36
- getSeriesMulti(columns: string[], viewport: Viewport, maxPoints: number): Promise<MultiSeriesResult>;
37
- getSeries(q: SeriesQuery): Promise<DecimatedSeries>;
38
- xBoundsSync(column: string): {
39
- x0: number;
40
- x1: number;
41
- };
42
- xBounds(column: string): Promise<{
43
- x0: number;
44
- x1: number;
45
- }>;
46
- /** At most `maxRows` rows in time order for the row-based charts and math channels: one stride over all pieces' rows
47
- * end to end (pieces smaller than the stride may be skipped); a row holds its piece's channels only (a rollup: the
48
- * bucket minimum). ponytail: no cross-group alignment in the sample. */
49
- sampleRowsSync(maxRows: number): DatasetRow[];
50
- dispose(): Promise<void>;
51
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * History bytes cached in the origin-private file system (spec D2; plan P4): "<segmentId>/footer" and
3
- * "<segmentId>/<block>". It keeps the bytes as stored (sealed): the device holds ciphertext only, and a segment id
4
- * never changes content (a new version is a new segment), so nothing is invalidated. Past the budget (min(2 GiB,
5
- * 20 % of the origin's quota)) the oldest-written files go, down to 90 %. Without OPFS (old browsers, some private
6
- * windows) every call is a no-op. ponytail: eviction by write time (FIFO); track reads (LRU) if old ranges miss too often.
7
- * ponytail: each tab keeps its own index and total, so several tabs writing at once can overshoot the budget until one
8
- * of them rescans (next page load); share the index through a BroadcastChannel or a Web Lock if that ever matters.
9
- */
10
- export interface BlockCache {
11
- get(key: string): Promise<Uint8Array | null>;
12
- put(key: string, bytes: Uint8Array): Promise<void>;
13
- }
14
- /** The part of FileSystemDirectoryHandle the cache uses (a fake in tests). */
15
- export interface CacheDir {
16
- getFileHandle(name: string, o?: {
17
- create?: boolean;
18
- }): Promise<{
19
- getFile(): Promise<File>;
20
- createWritable(): Promise<{
21
- write(b: BufferSource): Promise<void>;
22
- close(): Promise<void>;
23
- abort?(): Promise<void>;
24
- }>;
25
- }>;
26
- removeEntry(name: string): Promise<void>;
27
- entries(): AsyncIterable<[string, {
28
- kind: string;
29
- getFile?: () => Promise<File>;
30
- }]>;
31
- }
32
- export declare function blockCache(root?: () => Promise<CacheDir | null>, budget?: () => Promise<number>): BlockCache;
@@ -1,31 +0,0 @@
1
- import type { ExportPart } from '../recordings/export';
2
- import { type HistoryPiece } from '../data/historyDataSource';
3
- import { type HistoryReadOptions, type HistorySegmentRef } from './reader';
4
- export type HistoryExportFormat = 'csv' | 'mf4' | 'parquet';
5
- /** ponytail: wide tables over unaligned tag groups grow as times x channels (float32 cells); Parquet (long) has no such limit. */
6
- export declare const MAX_WIDE_CELLS = 25000000;
7
- /** ponytail: the Parquet file is built in DuckDB-WASM's memory (~4 GB address space); stream row groups out if larger
8
- * exports are needed. */
9
- export declare const MAX_PARQUET_VALUES = 30000000;
10
- /** The shortest decimal that reads back as the same float32 (0.1, not 0.10000000149011612). */
11
- export declare function f32text(v: number): string;
12
- /** ISO 8601 UTC with microseconds. */
13
- export declare function isoMicros(t: number): string;
14
- /** One row per distinct time across `channels`, NaN where a channel has none. */
15
- export declare function wideDay(pieces: HistoryPiece[], channels: string[]): {
16
- t: Float64Array;
17
- cols: Float32Array[];
18
- };
19
- export declare function exportHistoryTo(o: Omit<HistoryReadOptions, 'level'>, format: HistoryExportFormat, write: (part: ExportPart) => void | Promise<void>, opts?: {
20
- onProgress?: (fraction: number) => void;
21
- }): Promise<{
22
- skippedDays: string[];
23
- missingDays: string[];
24
- }>;
25
- /** Days of raw values into one Parquet file: appended to DuckDB `chunk` values at a time, at most `max` values. */
26
- export declare function parquetTo(raw: HistorySegmentRef[], day: (s: HistorySegmentRef) => Promise<{
27
- pieces: HistoryPiece[];
28
- }>, channels: string[], write: (part: ExportPart) => void | Promise<void>, step: (i: number) => void, limits?: {
29
- max: number;
30
- chunk: number;
31
- }): Promise<void>;
@@ -1,41 +0,0 @@
1
- export declare const KHD1_TRAILER_BYTES = 9;
2
- export type HistoryKind = 'raw' | 'rollup';
3
- export type HistoryLevel = 0 | 60 | 3600;
4
- export interface KhdChannel {
5
- n: string;
6
- u: string;
7
- }
8
- export interface KhdBlock {
9
- ch: number[];
10
- t0: number;
11
- t1: number;
12
- off: number;
13
- len: number;
14
- rows: number;
15
- values: number;
16
- }
17
- export interface KhdFooter {
18
- format: 1;
19
- stream: string;
20
- day: string;
21
- tz: string;
22
- kind: HistoryKind;
23
- level: HistoryLevel;
24
- t0: number;
25
- t1: number;
26
- channels: KhdChannel[];
27
- blocks: KhdBlock[];
28
- }
29
- /** Which file of a history: what the AAD of its blocks and footer binds. */
30
- export interface KhdFileId {
31
- stream: string;
32
- day: string;
33
- kind: HistoryKind;
34
- level: HistoryLevel;
35
- }
36
- export declare const blockAad: (f: KhdFileId, index: number | "footer") => string;
37
- /** The sealed footer's length, from bytes that end where the file ends (at least the 9-byte trailer). */
38
- export declare function footerLength(tail: Uint8Array): number;
39
- /** One sealed block (or the footer) opened; WebCrypto throws on a wrong key, file or index. */
40
- export declare function openSealed(key: CryptoKey, sealed: Uint8Array, f: KhdFileId, index: number | 'footer'): Promise<Uint8Array>;
41
- export declare function openFooter(key: CryptoKey, sealed: Uint8Array, f: KhdFileId): Promise<KhdFooter>;
@@ -1,21 +0,0 @@
1
- export interface RawBlock {
2
- t: Float64Array;
3
- cols: Float32Array[];
4
- }
5
- export interface RollupBlock {
6
- t: Float64Array;
7
- ch: Int32Array;
8
- min: Float32Array;
9
- max: Float32Array;
10
- }
11
- /** Loads DuckDB-WASM ahead of the first read (the History dialog calls it while the user picks). */
12
- /** Loads DuckDB and runs one tiny Parquet round trip, so the first real decode doesn't pay the first-query cost
13
- * (0.3-0.7 s measured, historian-notes/phase4.md). Call it while the user picks channels. */
14
- export declare function warmHistoryDecoder(): void;
15
- /** A raw block's times (Unix seconds) and the columns of `channels` (footer indexes; NaN = no value). */
16
- export declare function decodeRawBlock(bytes: Uint8Array, channels: number[]): Promise<RawBlock>;
17
- /** Rollup blocks' rows of their `channels`, one result per block, sorted by (ch, t): one query for the whole batch. */
18
- export declare function decodeRollupBlocks(blocks: Array<{
19
- bytes: Uint8Array;
20
- channels: number[];
21
- }>): Promise<RollupBlock[]>;
@@ -1,73 +0,0 @@
1
- /**
2
- * Reading a time range of a history (spec D1; plan Formats "Reading a range"): one file per local day at the wanted
3
- * level (else the nearest that day has), its footer (memo, cache, one suffix GET, or the whole file when small), then
4
- * only the blocks that overlap the range and hold a wanted channel (neighbours in one GET), RANGE_PARALLEL requests at
5
- * a time; opened with the history key and decoded into pieces. Days need no joining: each block carries its own times.
6
- */
7
- import { type HistoryPiece } from '../data/historyDataSource';
8
- import { type HistoryKind, type HistoryLevel, type KhdFooter } from './khd1';
9
- import type { BlockCache } from './blockCache';
10
- /** One verified file of a history (the latest version of its day, kind and level). */
11
- export interface HistorySegmentRef {
12
- id: string;
13
- day: string;
14
- kind: HistoryKind;
15
- level: HistoryLevel;
16
- bytes: number;
17
- keyId: string;
18
- }
19
- export interface HistoryReadOptions {
20
- historyStreamId: string;
21
- /** Segments of the days in range (any levels; the latest version of each). */
22
- segments: HistorySegmentRef[];
23
- t0: number;
24
- t1: number;
25
- channels: string[];
26
- level: HistoryLevel;
27
- key: (keyId: string) => Promise<CryptoKey>;
28
- /** Bytes [start, end) of a segment's file. */
29
- fetchRange: (segmentId: string, start: number, end: number, signal?: AbortSignal) => Promise<Uint8Array>;
30
- cache?: BlockCache;
31
- /** Opened footers by segment id, kept by the caller between reads of one history. */
32
- footers?: Map<string, KhdFooter>;
33
- signal?: AbortSignal;
34
- /** The segments of the same days listed again. A read that fails (a 404 or 403, or no URL for a segment) asks for
35
- * it once: a newer version may have replaced a segment meanwhile (today's summaries every 15 min, a late-data
36
- * rebuild), and the older one is deleted. When the listing picks other files the read runs again on them; when it
37
- * picks the same, the error stands. */
38
- relist?: () => Promise<HistorySegmentRef[]>;
39
- /** false: blocks are read from `cache` but not added to it (an export would push out what charts reuse). Default true. */
40
- cacheWrite?: boolean;
41
- /** 'gap': a segment whose `fetchRange` throws an error with `code: 'missing'` (its file is gone from storage) is read
42
- * as no data for its day, listed in `missingDays`, and the rest of the range is read. Default 'error': the read fails. */
43
- onMissing?: 'error' | 'gap';
44
- }
45
- export interface HistoryRange {
46
- pieces: HistoryPiece[];
47
- units: Record<string, string>;
48
- /** The level each day was read at (a day without the wanted level falls back). */
49
- levels: Record<string, HistoryLevel>;
50
- /** Days whose file is missing from storage (onMissing 'gap'): read as no data. */
51
- missingDays: string[];
52
- }
53
- export declare const RANGE_PARALLEL = 16;
54
- export declare const HISTORY_PIXELS = 2000;
55
- /** The coarsest level giving at least half a bucket per pixel over `spanS` (plan P2). */
56
- export declare function chooseLevel(spanS: number, pixels?: number): HistoryLevel;
57
- /** One file per day, in day order: the wanted level, else the nearest the day has (raw expired, today, a failed upload). */
58
- export declare function pickSegments(segments: HistorySegmentRef[], level: HistoryLevel): HistorySegmentRef[];
59
- /** f over items, n at a time; results in order. */
60
- export declare function pool<T, R>(items: T[], n: number, f: (x: T) => Promise<R>): Promise<R[]>;
61
- /** Byte ranges covering `blocks`: neighbours closer than 64 KiB join, up to 8 MiB per range. */
62
- export declare function coalesce(blocks: Array<{
63
- off: number;
64
- len: number;
65
- }>): Array<{
66
- start: number;
67
- end: number;
68
- }>;
69
- type Reader = Pick<HistoryReadOptions, 'historyStreamId' | 'key' | 'fetchRange' | 'cache' | 'footers' | 'signal'>;
70
- /** A segment's opened footer: the memo, else the cache, else the file (whole when ≤ 512 KiB, kept in `whole`). */
71
- export declare function readFooter(o: Reader, s: HistorySegmentRef, whole?: Map<string, Uint8Array<ArrayBufferLike>>): Promise<KhdFooter>;
72
- export declare function readHistoryRange(o: HistoryReadOptions): Promise<HistoryRange>;
73
- export {};