fitsjs-ng 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,19 @@
1
- 'use strict';// fitsjs-ng v1.0.0 | MIT License
2
- var P=80,x=2880,he=36,se=600,ne=-2147483647,ie=-2147483646,N=1e4,me="1.0.0";var D=class extends Error{constructor(e){super(e),this.name="FITSError";}},B=class extends D{constructor(e){super(e),this.name="HeaderError";}},G=class extends D{constructor(e){super(e),this.name="DataError";}},R=class extends D{constructor(e){super(e),this.name="DecompressionError";}};function O(s,e,t){t!==s.cardIndex&&s.warn(`${e} should appear at index ${t} in the FITS header`);}function X(s,e,t,r){if(e<t||e>r)throw new B(`The ${s} value of ${e} is not between ${t} and ${r}`)}function Y(s){return s==="T"}var K={SIMPLE(s,e){return s.primary=true,O(s,"SIMPLE",0),Y(e)},XTENSION(s,e){return s.extension=true,s.extensionType=e,O(s,"XTENSION",0),s.extensionType},BITPIX(s,e){let t=parseInt(String(e),10);if(O(s,"BITPIX",1),![8,16,32,-32,-64].includes(t))throw new B(`BITPIX value ${t} is not permitted`);return t},NAXIS(s,e,t){let r=parseInt(String(e),10);if(!t&&(O(s,"NAXIS",2),X("NAXIS",r,0,999),s.isExtension()&&(s.extensionType==="TABLE"||s.extensionType==="BINTABLE")&&r!==2))throw new B("NAXIS must be 2 for TABLE and BINTABLE extensions");return r},PCOUNT(s,e){let t=parseInt(String(e),10),n=3+s.get("NAXIS");if(O(s,"PCOUNT",n),s.isExtension()&&(s.extensionType==="IMAGE"||s.extensionType==="TABLE")&&t!==0)throw new B(`PCOUNT must be 0 for the ${s.extensionType} extensions`);return t},GCOUNT(s,e){let t=parseInt(String(e),10),n=3+s.get("NAXIS")+1;if(O(s,"GCOUNT",n),s.isExtension()&&(s.extensionType==="IMAGE"||s.extensionType==="TABLE"||s.extensionType==="BINTABLE")&&t!==1)throw new B(`GCOUNT must be 1 for the ${s.extensionType} extensions`);return t},EXTEND(s,e){if(!s.isPrimary())throw new B("EXTEND must only appear in the primary header");return Y(e)},BSCALE(s,e){return parseFloat(String(e))},BZERO(s,e){return parseFloat(String(e))},BLANK(s,e){let t=s.get("BITPIX");return t<=0&&s.warn(`BLANK is not to be used for BITPIX = ${t}`),parseInt(String(e),10)},DATAMIN(s,e){return parseFloat(String(e))},DATAMAX(s,e){return parseFloat(String(e))},EXTVER(s,e){return parseInt(String(e),10)},EXTLEVEL(s,e){return parseInt(String(e),10)},TFIELDS(s,e){let t=parseInt(String(e),10);return X("TFIELDS",t,0,999),t},TBCOL(s,e,t,r){let n=s.get("TFIELDS");return r!==void 0&&X("TBCOL",parseInt(r,10),0,n),e},ZIMAGE(s,e){return Y(e)},ZCMPTYPE(s,e){let t=String(e);if(!["GZIP_1","RICE_1","PLIO_1","HCOMPRESS_1"].includes(t))throw new B(`ZCMPTYPE value ${t} is not permitted`);if(!["RICE_1"].includes(t))throw new B(`Compress type ${t} is not yet implemented`);return t},ZBITPIX(s,e){let t=parseInt(String(e),10);if(![8,16,32,64,-32,-64].includes(t))throw new B(`ZBITPIX value ${t} is not permitted`);return t},ZNAXIS(s,e,t){let r=parseInt(String(e),10);return t||X("ZNAXIS",r,0,999),r},ZTILE(s,e){return parseInt(String(e),10)},ZSIMPLE(s,e){return e==="T"},ZPCOUNT(s,e){return parseInt(String(e),10)},ZGCOUNT(s,e){return parseInt(String(e),10)},ZDITHER0(s,e){return parseInt(String(e),10)}};var U=class s{static ARRAY_PATTERN=/(\D+)(\d+)/;primary=false;extension=false;extensionType;cards=new Map;comments=[];history=[];cardIndex=0;warn;maxLines;block;constructor(e,t=600,r){this.maxLines=t,this.warn=r??console.warn,this.block=e,this.readBlock(e);}get(e){return this.contains(e)?this.cards.get(e).value:null}getNumber(e,t){let r=this.get(e);if(r===null)return t??0;if(typeof r=="number")return r;throw new B(`Expected number for keyword ${e}, got ${typeof r}`)}getString(e,t){let r=this.get(e);if(r===null)return t??"";if(typeof r=="string")return r;throw new B(`Expected string for keyword ${e}, got ${typeof r}`)}getBoolean(e,t){let r=this.get(e);if(r===null)return t??false;if(typeof r=="boolean")return r;throw new B(`Expected boolean for keyword ${e}, got ${typeof r}`)}set(e,t,r=""){this.cards.set(e,{index:this.cardIndex,value:t,comment:r}),this.cardIndex+=1;}contains(e){return this.cards.has(e)}getComments(){return this.comments}getHistory(){return this.history}keys(){return Array.from(this.cards.keys())}hasDataUnit(){let e=this.getNumber("NAXIS");if(e===0)return false;for(let t=1;t<=e;t++)if(this.getNumber(`NAXIS${t}`)!==0)return true;return false}getDataLength(){if(!this.hasDataUnit())return 0;let e=this.getNumber("NAXIS"),t=[];for(let i=1;i<=e;i++)t.push(this.getNumber(`NAXIS${i}`));let r=this.getNumber("BITPIX"),n=t.reduce((i,o)=>i*o,1)*Math.abs(r)/8;return n+=this.getNumber("PCOUNT"),n}getDataType(){switch(this.extensionType){case "BINTABLE":return this.contains("ZIMAGE")?"CompressedImage":"BinaryTable";case "TABLE":return "Table";case "IMAGE":return this.hasDataUnit()?"Image":null;default:return this.hasDataUnit()?"Image":null}}isPrimary(){return this.primary}isExtension(){return this.extension}readBlock(e){let r=e.length/80,n=Math.min(r,this.maxLines);for(let i=0;i<n;i++){let o=e.slice(i*80,(i+1)*80);this.readLine(o);}}readLine(e){let t=e.slice(0,8).trim();if(t==="")return;let r=e.slice(8,10),n=e.slice(10);if(r!=="= "){let a=e.slice(8).trim();t==="COMMENT"?this.comments.push(a):t==="HISTORY"&&this.history.push(a);return}let i,o;if(n.trimStart().startsWith("'")){let a=n.indexOf("'"),u=-1,m=a+1;for(;m<n.length;){let c=n.indexOf("'",m);if(c===-1)break;if(c+1<n.length&&n[c+1]==="'"){m=c+2;continue}u=c;break}if(u!==-1){let c=n.slice(u+1),f=c.indexOf(" /");f!==-1?(i=n.slice(0,u+1).trim(),o=c.slice(f+2).trim()):(i=n.slice(0,u+1).trim(),o="");}else i=n.trim(),o="";}else {let a=n.indexOf(" /");a!==-1?(i=n.slice(0,a).trim(),o=n.slice(a+2).trim()):(i=n.trim(),o="");}let l;i.startsWith("'")?l=i.slice(1,-1).replaceAll("''","'").trim():i==="T"||i==="F"?l=i:l=parseFloat(i),l=this.validate(t,l),this.set(t,l,o);}validate(e,t){let r=e,n=false,i,o=s.ARRAY_PATTERN.exec(e);return o&&(n=true,r=o[1],i=o[2]),r in K&&(t=K[r](this,t,n,i)),t}};var _=class{header;data;constructor(e,t){this.header=e,this.data=t;}hasData(){return this.data!==void 0}};var oe=s=>s,ae=s=>(s&255)<<8|s>>8&255,ce=s=>(s&255)<<24|(s&65280)<<8|s>>8&65280|s>>24&255,$={8:oe,B:oe,16:ae,I:ae,32:ce,J:ce},pe=new TextDecoder("ascii");function H(s){return pe.decode(s)}function q(s){return (2880-s%2880)%2880}function le(s){let e=[],t=128;for(;t>=1;)e.push(s&t?1:0),t>>=1;return e}var C=class{buffer;blob;static swapEndian=$;constructor(e){e instanceof ArrayBuffer?this.buffer=e:typeof Blob<"u"&&e instanceof Blob&&(this.blob=e);}};function M(s){let e=s.length,t,r,n=0;for(;n<e;n++){let i=s[n];if(!isNaN(i)){t=r=i,n++;break}}if(t===void 0||r===void 0)return [NaN,NaN];for(;n<e;n++){let i=s[n];isNaN(i)||(i<t?t=i:i>r&&(r=i));}return [t,r]}function k(s,e,t,r){let n=t*r+e;return n<0||n>=s.length?NaN:s[n]}var z=class s extends C{bitpix;naxis;width;height;depth;bzero;bscale;bytes;length;frameLength;frameOffsets;constructor(e,t){super(t);let r=e.getNumber("NAXIS");this.bitpix=e.getNumber("BITPIX"),this.naxis=[];for(let n=1;n<=r;n++)this.naxis.push(e.getNumber(`NAXIS${n}`));this.width=e.getNumber("NAXIS1"),this.height=e.getNumber("NAXIS2",1),this.depth=e.getNumber("NAXIS3",1),this.bzero=e.getNumber("BZERO"),this.bscale=e.getNumber("BSCALE",1),this.bytes=Math.abs(this.bitpix)/8,this.length=this.naxis.reduce((n,i)=>n*i,1)*Math.abs(this.bitpix)/8,this.frameOffsets=[],this.frameLength=this.bytes*this.width*this.height;for(let n=0;n<this.depth;n++){let i=n*this.frameLength,o={begin:i};this.buffer&&(o.buffers=[this.buffer.slice(i,i+this.frameLength)]),this.frameOffsets.push(o);}}static computeFrame(e,t,r,n){let i=Math.abs(t)/8,o=e.byteLength/i,l=r===0&&n===1,a=new DataView(e),u=!(Number.isInteger(r)&&Number.isInteger(n));if(t===8){if(l)return new Uint8Array(e.slice(0));let c=u?new Float32Array(o):new Int32Array(o);for(let f=0;f<o;f++)c[f]=r+n*a.getUint8(f);return c}if(t===16){if(l){let f=new Int16Array(o);for(let h=0;h<o;h++)f[h]=a.getInt16(h*2,false);return f}let c=u?new Float32Array(o):new Int32Array(o);for(let f=0;f<o;f++)c[f]=r+n*a.getInt16(f*2,false);return c}if(t===32){if(l){let f=new Int32Array(o);for(let h=0;h<o;h++)f[h]=a.getInt32(h*4,false);return f}let c=new Float64Array(o);for(let f=0;f<o;f++)c[f]=r+n*a.getInt32(f*4,false);return c}if(t===-32){let c=new Float32Array(o);if(l)for(let f=0;f<o;f++)c[f]=a.getFloat32(f*4,false);else for(let f=0;f<o;f++)c[f]=r+n*a.getFloat32(f*4,false);return c}let m=new Float64Array(o);if(l)for(let c=0;c<o;c++)m[c]=a.getFloat64(c*8,false);else for(let c=0;c<o;c++)m[c]=r+n*a.getFloat64(c*8,false);return m}async getFrame(e=0){let t=this.frameOffsets[e];if(t.buffers&&t.buffers.length>0)return s.computeFrame(t.buffers[0],this.bitpix,this.bzero,this.bscale);if(!this.blob)throw new Error("No data source available for this image frame");let r=t.begin,i=await this.blob.slice(r,r+this.frameLength).arrayBuffer();return t.buffers=[i],s.computeFrame(i,this.bitpix,this.bzero,this.bscale)}async getFrames(e,t){let r=Array.from({length:t},(n,i)=>e+i);return Promise.all(r.map(n=>this.getFrame(n)))}isDataCube(){return this.naxis.length>2}async*[Symbol.asyncIterator](){for(let e=0;e<this.depth;e++)yield this.getFrame(e);}getExtent(e){return M(e)}getPixel(e,t,r){return k(e,t,r,this.width)}};var Q={L:1,B:1,I:2,J:4,K:8,A:1,E:4,D:8,C:8,M:16},v={B:Uint8Array,I:Int16Array,J:Int32Array,E:Float32Array,D:Float64Array,1:Uint8Array,2:Int16Array,4:Int32Array};var F=class extends C{maxMemory=1048576;rowByteSize;rows;cols;length;heapLength;columns;accessors=[];descriptors=[];elementByteLengths=[];columnTypes=[];heap;typedArray=v;firstRowInBuffer=0;lastRowInBuffer=0;nRowsInBuffer=0;cachedBuffer;constructor(e,t){super(t),this.rowByteSize=e.getNumber("NAXIS1"),this.rows=e.getNumber("NAXIS2"),this.cols=e.getNumber("TFIELDS"),this.length=this.rowByteSize*this.rows,this.heapLength=e.getNumber("PCOUNT"),this.columns=this.getColumns(e),this.buffer?this.heap=this.buffer.slice(this.length,this.length+this.heapLength):(this.firstRowInBuffer=0,this.lastRowInBuffer=0,this.nRowsInBuffer=Math.floor(this.maxMemory/this.rowByteSize));}initAccessors(e){this.resetAccessors(),this.setAccessors(e);}resetAccessors(){this.accessors=[],this.descriptors=[],this.elementByteLengths=[],this.columnTypes=[];}rowsInMemory(e,t){return this.buffer&&!this.blob?true:this.cachedBuffer?!(e<this.firstRowInBuffer||t>this.lastRowInBuffer):false}getColumns(e){let t=[];for(let r=1;r<=this.cols;r++){let n=`TTYPE${r}`;if(!e.contains(n))return null;t.push(e.getString(n));}return t}async getRows(e,t){if(this.rowsInMemory(e,e+t)){let a;if(this.cachedBuffer){let u=(e-this.firstRowInBuffer)*this.rowByteSize;a=this.cachedBuffer.slice(u,u+t*this.rowByteSize);}else if(this.buffer){let u=e*this.rowByteSize,m=u+t*this.rowByteSize;a=this.buffer.slice(u,m);}else throw new Error("No data source available");return this._getRows(a,t)}if(!this.blob)throw new Error("No data source available");let r=e*this.rowByteSize,n=Math.max(this.nRowsInBuffer,t),i=r+n*this.rowByteSize,l=await this.blob.slice(r,i).arrayBuffer();return this.cachedBuffer=l,this.firstRowInBuffer=e,this.lastRowInBuffer=e+n,this._getRows(l,t)}async getTableBuffer(e,t){let r=Math.min(this.rows-e,t),n=e*this.rowByteSize,i=n+r*this.rowByteSize;if(this.buffer)return this.buffer.slice(n,i);if(!this.blob)throw new Error("No data source available");return this.blob.slice(n,i).arrayBuffer()}async getColumn(e){if(!this.columns)throw new Error("Column names not available");let t=this.columns.indexOf(e);if(t===-1)throw new Error(`Column "${e}" not found`);if(this.buffer&&!this.blob)return (await this.getRows(0,this.rows)).map(y=>y[e]);let r=this.descriptors[t],n=this.accessors[t],i=this.elementByteLengths.slice(0,t).reduce((h,y)=>h+y,0),o=r&&this.typedArray[r]?this.typedArray[r]:null,l=o?Array.from(new o(this.rows)):new Array(this.rows),a=Math.min(Math.max(1,Math.floor(this.maxMemory/this.rowByteSize)),this.rows),u=this.rows/a,m=Math.floor(u)===u?u:Math.floor(u)+1,c=0,f=0;for(;m>0;){let h=f*a,y=await this.getTableBuffer(h,a),A=y.byteLength/this.rowByteSize,b=new DataView(y),g=i;for(let p=0;p<A;p++)l[c]=n(b,g)[0],c++,g+=this.rowByteSize;m--,f++;}return l}};var ye={A:s=>s.trim(),I:s=>parseInt(s,10),F:s=>parseFloat(s),E:s=>parseFloat(s),D:s=>parseFloat(s)},Z=class extends F{asciiAccessors=[];colStarts=[];colWidths=[];hasTBCOL=false;constructor(e,t){super(e,t),this.initAccessors(e);}setAccessors(e){this.asciiAccessors=[],this.colStarts=[],this.colWidths=[],this.hasTBCOL=false;let t=/([AIFED])(\d+)\.*(\d+)*/;for(let r=1;r<=this.cols;r++)if(e.contains(`TBCOL${r}`)){this.hasTBCOL=true;break}for(let r=1;r<=this.cols;r++){let n=e.getString(`TFORM${r}`),i=t.exec(n);if(!i){this.asciiAccessors.push(m=>m.trim()),this.colStarts.push(0),this.colWidths.push(0);continue}let o=i[1],l=parseInt(i[2],10),a=ye[o]??(m=>m.trim());this.asciiAccessors.push(a);let u=e.contains(`TBCOL${r}`)?e.getNumber(`TBCOL${r}`)-1:0;this.colStarts.push(u),this.colWidths.push(l);}}_getRows(e,t){let r=e.byteLength/this.rowByteSize,n=new Uint8Array(e),i=[],o=this.asciiAccessors??[];for(let l=0;l<r;l++){let a=l*this.rowByteSize,u=a+this.rowByteSize,m=n.subarray(a,u),c=H(m),f={};if(this.hasTBCOL)for(let h=0;h<o.length;h++){let y=this.colStarts[h],A=this.colWidths[h],b=c.substring(y,y+A).trim();this.columns&&(f[this.columns[h]]=o[h](b));}else {let h=c.trim().split(/\s+/);for(let y=0;y<o.length;y++){let A=h[y]??"";this.columns&&(f[this.columns[y]]=o[y](A));}}i.push(f);}return i}};var ue={L(s,e){return [s.getInt8(e)===84,e+1]},B(s,e){return [s.getUint8(e),e+1]},I(s,e){return [s.getInt16(e,false),e+2]},J(s,e){return [s.getInt32(e,false),e+4]},K(s,e){let t=s.getBigInt64(e,false);return [Number(t),e+8]},A(s,e){return [String.fromCharCode(s.getUint8(e)),e+1]},E(s,e){return [s.getFloat32(e,false),e+4]},D(s,e){return [s.getFloat64(e,false),e+8]},C(s,e){let t=s.getFloat32(e,false),r=s.getFloat32(e+4,false);return [[t,r],e+8]},M(s,e){let t=s.getFloat64(e,false),r=s.getFloat64(e+8,false);return [[t,r],e+16]}},L=class extends F{constructor(e,t){super(e,t),this.initAccessors(e);}setAccessors(e){let t=/(\d*)([PQ]*)([LXBIJKAEDCM])$/;for(let r=1;r<=this.cols;r++){let n=e.getString(`TFORM${r}`),i=e.getString(`TTYPE${r}`),o=t.exec(n);if(!o)throw new Error(`Unsupported or invalid TFORM${r} value: '${n}'`);let l=parseInt(o[1],10)||1,a=o[2],u=o[3];this.descriptors.push(u),this.columnTypes.push(i),this.elementByteLengths.push((Q[u]??1)*l),a?this.setupArrayAccessor(u,i):l===1?this.setupSingleAccessor(u):u==="X"?this.setupBitArrayAccessor(l):u==="A"?this.setupCharArrayAccessor(l):this.setupMultiAccessor(u,l);}}getFromHeap(e,t,r){let n=e.getInt32(t,false);t+=4;let i=e.getInt32(t,false);if(t+=4,!this.heap)throw new Error("Heap not available");let o=Q[r]??1,l=this.heap.slice(i,i+n*o),a=v[r];if(!a)throw new Error(`No typed array constructor for descriptor: ${r}`);let u=new a(l),m=$[r];if(m&&r!=="B")for(let c=0;c<u.length;c++)u[c]=m(u[c]);return [u,t]}setupArrayAccessor(e,t){if(t==="COMPRESSED_DATA"){let r=(n,i)=>{let[o,l]=this.getFromHeap(n,i,e);return [o,l]};this.accessors.push(r);}else if(t==="GZIP_COMPRESSED_DATA"){let r=(n,i)=>{throw new R("GZIP decompression is not yet implemented")};this.accessors.push(r);}else {let r=(n,i)=>this.getFromHeap(n,i,e);this.accessors.push(r);}}setupSingleAccessor(e){let t=ue[e];if(!t)throw new Error(`Unknown binary table type code: ${e}`);let r=(n,i)=>t(n,i);this.accessors.push(r);}setupBitArrayAccessor(e){let t=Math.ceil(e/8),r=(n,i)=>{let o=n.buffer.slice(i,i+t),l=new Uint8Array(o),a=[];for(let u=0;u<l.length;u++)a=a.concat(le(l[u]));return [a.slice(0,e),i+t]};this.accessors.push(r);}setupCharArrayAccessor(e){let t=(r,n)=>{let i=r.buffer.slice(n,n+e),o=new Uint8Array(i),l="";for(let a=0;a<o.length;a++)l+=String.fromCharCode(o[a]);return [l.trim(),n+e]};this.accessors.push(t);}setupMultiAccessor(e,t){let r=ue[e];if(!r)throw new Error(`Unknown binary table type code: ${e}`);let n=(i,o)=>{let l=[],a=o;for(let u=0;u<t;u++){let[m,c]=r(i,a);l.push(m),a=c;}return [l,a]};this.accessors.push(n);}_getRows(e,t){let r=new DataView(e),n=0,i=[];for(let o=0;o<t;o++){let l={};for(let a=0;a<this.accessors.length;a++){let[u,m]=this.accessors[a](r,n);n=m,this.columns&&(l[this.columns[a]]=u);}i.push(l);}return i}};var W={1(s){return [3,6,s[0],1]},2(s){let n=0;return n=n|s[0]<<8,n=n|s[1],[4,14,n,2]},4(s){let n=0;return n=n|s[0]<<24,n=n|s[1]<<16,n=n|s[2]<<8,n=n|s[3],[5,25,n,4]}};function J(s,e,t,r,n,i=W){let o=i[t];if(!o)throw new Error(`Unsupported bytepix value: ${t}`);let[l,a,u,m]=o(s),c=u,f=m,h=1<<l,y=new Uint8Array(256),A=8,b=128,g=255;for(;g>=0;){for(;g>=b;)y[g]=A,g--;b=b/2,A--;}y[0]=0;let p=s[f++],d=8,w=0;for(;w<n;){for(d-=l;d<0;)p=p<<8|s[f++],d+=8;let E=(p>>d)-1;p&=(1<<d)-1;let S=w+e;if(S>n&&(S=n),E<0)for(;w<S;)r[w]=c,w++;else if(E===a)for(;w<S;){b=h-d;let T=p<<b;for(b-=8;b>=0;)p=s[f++],T|=p<<b,b-=8;d>0?(p=s[f++],T|=p>>-b,p&=(1<<d)-1):p=0,(T&1)===0?T=T>>1:T=~(T>>1),r[w]=T+c,c=r[w],w++;}else for(;w<S;){for(;p===0;)d+=8,p=s[f++];for(A=d-y[p],d-=A+1,p^=1<<d,d-=E;d<0;)p=p<<8|s[f++],d+=8;let T=A<<E|p>>d;p&=(1<<d)-1,(T&1)===0?T=T>>1:T=~(T>>1),r[w]=T+c,c=r[w],w++;}}return r}function be(){let t=1,r=new Float32Array(1e4);for(let n=0;n<1e4;n++){let i=16807*t;t=i-2147483647*Math.floor(i/2147483647),r[n]=t/2147483647;}return r}var j=be(),V=class extends L{zcmptype;zbitpix;znaxis;zblank;blank;zdither;ztile;width;height;bzero;bscale;algorithmParameters;zquantiz;constructor(e,t){super(e,t),this.zcmptype=e.getString("ZCMPTYPE"),this.zbitpix=e.getNumber("ZBITPIX"),this.znaxis=e.getNumber("ZNAXIS"),this.zblank=e.contains("ZBLANK")?e.getNumber("ZBLANK"):null,this.blank=e.contains("BLANK")?e.getNumber("BLANK"):null,this.zdither=e.getNumber("ZDITHER0"),this.ztile=[];for(let n=1;n<=this.znaxis;n++){let i=e.contains(`ZTILE${n}`)?e.getNumber(`ZTILE${n}`):n===1?e.getNumber("ZNAXIS1"):1;this.ztile.push(i);}this.width=e.getNumber("ZNAXIS1"),this.height=e.getNumber("ZNAXIS2",1),this.algorithmParameters={},this.zcmptype==="RICE_1"&&(this.algorithmParameters.BLOCKSIZE=32,this.algorithmParameters.BYTEPIX=4);let r=1;for(;e.contains(`ZNAME${r}`);){let n=e.getString(`ZNAME${r}`),i=e.getNumber(`ZVAL${r}`);this.algorithmParameters[n]=i,r++;}this.zquantiz=e.getString("ZQUANTIZ","LINEAR_SCALING"),this.bzero=e.getNumber("BZERO"),this.bscale=e.getNumber("BSCALE",1),this.initAccessors(e);}setAccessors(e){super.setAccessors(e);for(let t=0;t<this.columnTypes.length;t++){let r=this.columnTypes[t],n=this.descriptors[t];r==="COMPRESSED_DATA"?this.accessors[t]=(i,o)=>{let[l,a]=this.getFromHeap(i,o,n),u=this.algorithmParameters.BYTEPIX??4,m=this.algorithmParameters.BLOCKSIZE??32,c=v[u];if(!c)throw new Error(`No typed array for bytepix: ${u}`);let f=this.ztile[0]??this.width,h=new c(f);return J(l,m,u,h,f,W),[h,a]}:r==="GZIP_COMPRESSED_DATA"&&(this.accessors[t]=(i,o)=>{throw new R("GZIP decompression is not yet implemented")});}}_getRows(e,t){let r=new DataView(e),n=0,i=new Float32Array(this.width*this.height),o=0,l=t;for(;l--;){o++;let a={};for(let b=0;b<this.accessors.length;b++){let[g,p]=this.accessors[b](r,n);n=p,this.columns&&(a[this.columns[b]]=g);}let u=a.COMPRESSED_DATA||a.UNCOMPRESSED_DATA||a.GZIP_COMPRESSED_DATA,m=a.ZSCALE||this.bscale,c=a.ZZERO||this.bzero,f=o,h=this.zquantiz==="SUBTRACTIVE_DITHER_1"||this.zquantiz==="SUBTRACTIVE_DITHER_2",y=0,A=0;if(h){let g=(f+this.zdither-1-1)%1e4;A=g<0?g+1e4:g,y=Math.floor(j[A]*500);}for(let b=0;b<u.length;b++){let g=(f-1)*this.width+b,p=u[b];if(p===-2147483647)i[g]=NaN;else if(p===-2147483646)i[g]=0;else if(h){let d=j[y];i[g]=(p-d+.5)*m+c;}else i[g]=p*m+c;h&&(y++,y===1e4&&(A=(A+1)%1e4,y=Math.floor(j[A]*500)));}}return i}async getFrame(e=0){if(this.heap)return await this.getRows(0,this.rows);if(!this.blob)throw new Error("No data source available");let t=this.blob.slice(this.length,this.length+this.heapLength);return this.heap=await t.arrayBuffer(),this.getFrame(e)}getExtent(e){return M(e)}getPixel(e,t,r){return k(e,t,r,this.width)}};function fe(s,e){let t=s.getDataType();if(t)switch(t){case "Image":return new z(s,e);case "BinaryTable":return new L(s,e);case "Table":return new Z(s,e);case "CompressedImage":return new V(s,e);default:return}}function ee(s,e){let t=[],r=s.byteLength,n=0;for(;n<r;){let i=0,o=new Uint8Array(0),l=false;for(;!l&&n+i*2880+2880<=r;){let a=n+i*2880,u=new Uint8Array(s,a,2880),m=new Uint8Array(o.length+2880);m.set(o,0),m.set(u,o.length),o=m;let c=2880/80;for(let p=c-1;p>=0;p--){let d=p*80,w=u[d];if(w!==32){if(w===69&&u[d+1]===78&&u[d+2]===68&&u[d+3]===32){l=true;break}break}}if(i++,!l)continue;let f=H(o),h=new U(f,e?.maxHeaderLines,e?.onWarning),y=n+i*2880,A=h.getDataLength(),b=s.slice(y,y+A),g;if(h.hasDataUnit()&&(g=fe(h,b)),t.push(new _(h,g)),n=y+A+q(A),n>=r)break}if(!l)break}return t}async function te(s,e){let t=[],r=s.size,n=0;for(;n<r;){let i=0,o=[],l=false;for(;!l&&n+i*2880+2880<=r;){let a=n+i*2880,m=await s.slice(a,a+2880).arrayBuffer(),c=new Uint8Array(m);o.push(c);let f=2880/80;for(let E=f-1;E>=0;E--){let S=E*80,T=c[S];if(T!==32){if(T===69&&c[S+1]===78&&c[S+2]===68&&c[S+3]===32){l=true;break}break}}if(i++,!l)continue;let h=o.reduce((E,S)=>E+S.length,0),y=new Uint8Array(h),A=0;for(let E of o)y.set(E,A),A+=E.length;let b=H(y),g=new U(b,e?.maxHeaderLines,e?.onWarning),p=n+i*2880,d=g.getDataLength(),w;if(g.hasDataUnit()){let E=s.slice(p,p+d);w=fe(g,E);}if(t.push(new _(g,w)),n=p+d+q(d),n>=r)break}if(!l)break}return t}var re=class s{hdus;constructor(e){this.hdus=e;}static fromArrayBuffer(e,t){let r=ee(e,t);return new s(r)}static async fromBlob(e,t){let r=await te(e,t);return new s(r)}static async fromURL(e,t){let r=await fetch(e,t?.requestInit);if(!r.ok)throw new Error(`Failed to fetch FITS file: ${r.status} ${r.statusText}`);let n=await r.arrayBuffer();return s.fromArrayBuffer(n,t)}static fromNodeBuffer(e,t){let r=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return s.fromArrayBuffer(r,t)}getHDU(e){if(e!==void 0)return e>=0&&e<this.hdus.length?this.hdus[e]:void 0;for(let t of this.hdus)if(t.hasData())return t}getHeader(e){return this.getHDU(e)?.header}getDataUnit(e){return this.getHDU(e)?.data}};exports.BLOCK_LENGTH=x;exports.BinaryTable=L;exports.CompressedImage=V;exports.DEFAULT_MAX_HEADER_LINES=se;exports.DataError=G;exports.DataUnit=C;exports.DecompressionError=R;exports.FITS=re;exports.FITSError=D;exports.HDU=_;exports.Header=U;exports.HeaderError=B;exports.Image=z;exports.LINES_PER_BLOCK=he;exports.LINE_WIDTH=P;exports.NULL_VALUE=ne;exports.N_RANDOM=N;exports.RiceSetup=W;exports.Table=Z;exports.VERSION=me;exports.ZERO_VALUE=ie;exports.getExtent=M;exports.getPixel=k;exports.parseBlob=te;exports.parseBuffer=ee;exports.riceDecompress=J;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var fflate=require('fflate'),xmldom=require('@xmldom/xmldom'),lz4js=require('lz4js'),fzstd=require('fzstd'),Nn=require('js-sha3'),fastPng=require('fast-png'),jpegJs=require('jpeg-js'),healpix=require('@hscmap/healpix');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Nn__default=/*#__PURE__*/_interopDefault(Nn);// fitsjs-ng v1.0.2 | MIT License
2
+ var we=80,_=2880,Ki=36,Gr=600,jr=-2147483647,Kr=-2147483646,Ie=1e4,Yi="1.0.2";var se=class extends Error{constructor(t){super(t),this.name="FITSError";}},z=class extends se{constructor(t){super(t),this.name="HeaderError";}},Dt=class extends se{constructor(t){super(t),this.name="DataError";}},O=class extends se{constructor(t){super(t),this.name="DecompressionError";}};function Ce(e,t,r){r!==e.cardIndex&&e.warn(`${t} should appear at index ${r} in the FITS header`);}function at(e,t,r,n){if(t<r||t>n)throw new z(`The ${e} value of ${t} is not between ${r} and ${n}`)}function Ot(e){return e==="T"}var Mt={SIMPLE(e,t){return e.primary=true,Ce(e,"SIMPLE",0),Ot(t)},XTENSION(e,t){return e.extension=true,e.extensionType=t,Ce(e,"XTENSION",0),e.extensionType},BITPIX(e,t){let r=parseInt(String(t),10);if(Ce(e,"BITPIX",1),![8,16,32,64,-32,-64].includes(r))throw new z(`BITPIX value ${r} is not permitted`);return r},NAXIS(e,t,r){let n=parseInt(String(t),10);if(!r&&(Ce(e,"NAXIS",2),at("NAXIS",n,0,999),e.isExtension()&&(e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&n!==2))throw new z("NAXIS must be 2 for TABLE and BINTABLE extensions");return n},PCOUNT(e,t){let r=parseInt(String(t),10),i=3+e.get("NAXIS");if(Ce(e,"PCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE")&&r!==0)throw new z(`PCOUNT must be 0 for the ${e.extensionType} extensions`);return r},GCOUNT(e,t){let r=parseInt(String(t),10),i=3+e.get("NAXIS")+1;if(Ce(e,"GCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&r!==1)throw new z(`GCOUNT must be 1 for the ${e.extensionType} extensions`);return r},EXTEND(e,t){if(!e.isPrimary())throw new z("EXTEND must only appear in the primary header");return Ot(t)},BSCALE(e,t){return parseFloat(String(t))},BZERO(e,t){return parseFloat(String(t))},BLANK(e,t){let r=e.get("BITPIX");return r<=0&&e.warn(`BLANK is not to be used for BITPIX = ${r}`),parseInt(String(t),10)},DATAMIN(e,t){return parseFloat(String(t))},DATAMAX(e,t){return parseFloat(String(t))},EXTVER(e,t){return parseInt(String(t),10)},EXTLEVEL(e,t){return parseInt(String(t),10)},TFIELDS(e,t){let r=parseInt(String(t),10);return at("TFIELDS",r,0,999),r},TBCOL(e,t,r,n){let i=e.get("TFIELDS");return n!==void 0&&at("TBCOL",parseInt(n,10),0,i),t},ZIMAGE(e,t){return Ot(t)},ZCMPTYPE(e,t){let r=String(t);if(!["GZIP_1","RICE_1","PLIO_1","HCOMPRESS_1"].includes(r))throw new z(`ZCMPTYPE value ${r} is not permitted`);return r},ZBITPIX(e,t){let r=parseInt(String(t),10);if(![8,16,32,64,-32,-64].includes(r))throw new z(`ZBITPIX value ${r} is not permitted`);return r},ZNAXIS(e,t,r){let n=parseInt(String(t),10);return r||at("ZNAXIS",n,0,999),n},ZTILE(e,t){return parseInt(String(t),10)},ZSIMPLE(e,t){return t==="T"},ZPCOUNT(e,t){return parseInt(String(t),10)},ZGCOUNT(e,t){return parseInt(String(t),10)},ZDITHER0(e,t){return parseInt(String(t),10)}};var Ue=class e{static ARRAY_PATTERN=/(\D+)(\d+)/;primary=false;extension=false;extensionType;cards=new Map;comments=[];history=[];cardIndex=0;warn;maxLines;block;constructor(t,r=600,n){this.maxLines=r,this.warn=n??console.warn,this.block=t,this.readBlock(t);}get(t){return this.contains(t)?this.cards.get(t).value:null}getNumber(t,r){let n=this.get(t);if(n===null)return r??0;if(typeof n=="number")return n;throw new z(`Expected number for keyword ${t}, got ${typeof n}`)}getString(t,r){let n=this.get(t);if(n===null)return r??"";if(typeof n=="string")return n;throw new z(`Expected string for keyword ${t}, got ${typeof n}`)}getBoolean(t,r){let n=this.get(t);if(n===null)return r??false;if(typeof n=="boolean")return n;throw new z(`Expected boolean for keyword ${t}, got ${typeof n}`)}set(t,r,n=""){this.cards.set(t,{index:this.cardIndex,value:r,comment:n}),this.cardIndex+=1;}contains(t){return this.cards.has(t)}getComments(){return this.comments}getHistory(){return this.history}keys(){return Array.from(this.cards.keys())}getCards(){return [...this.cards.entries()].sort((t,r)=>t[1].index-r[1].index).map(([t,r])=>({key:t,value:r.value,comment:r.comment}))}hasDataUnit(){let t=this.getNumber("NAXIS");if(t===0)return false;for(let r=1;r<=t;r++)if(this.getNumber(`NAXIS${r}`)!==0)return true;return false}getDataLength(){if(!this.hasDataUnit())return 0;let t=this.getNumber("NAXIS"),r=[];for(let o=1;o<=t;o++)r.push(this.getNumber(`NAXIS${o}`));let n=this.getNumber("BITPIX"),i=r.reduce((o,s)=>o*s,1)*Math.abs(n)/8;return i+=this.getNumber("PCOUNT"),i}getDataType(){switch(this.extensionType){case "BINTABLE":return this.contains("ZIMAGE")?"CompressedImage":"BinaryTable";case "TABLE":return "Table";case "IMAGE":return this.hasDataUnit()?"Image":null;default:return this.hasDataUnit()?"Image":null}}isPrimary(){return this.primary}isExtension(){return this.extension}readBlock(t){let n=t.length/80,i=Math.min(n,this.maxLines);for(let o=0;o<i;o++){let s=t.slice(o*80,(o+1)*80);this.readLine(s);}}readLine(t){let r=t.slice(0,8).trim();if(r==="")return;let n=t.slice(8,10),i=t.slice(10);if(n!=="= "){let a=t.slice(8).trim();r==="COMMENT"?this.comments.push(a):r==="HISTORY"&&this.history.push(a);return}let o,s;if(i.trimStart().startsWith("'")){let a=i.indexOf("'"),u=-1,f=a+1;for(;f<i.length;){let l=i.indexOf("'",f);if(l===-1)break;if(l+1<i.length&&i[l+1]==="'"){f=l+2;continue}u=l;break}if(u!==-1){let l=i.slice(u+1),m=l.indexOf(" /");m!==-1?(o=i.slice(0,u+1).trim(),s=l.slice(m+2).trim()):(o=i.slice(0,u+1).trim(),s="");}else o=i.trim(),s="";}else {let a=i.indexOf(" /");a!==-1?(o=i.slice(0,a).trim(),s=i.slice(a+2).trim()):(o=i.trim(),s="");}let c;o.startsWith("'")?c=o.slice(1,-1).replaceAll("''","'").trim():o==="T"||o==="F"?c=o:c=parseFloat(o),c=this.validate(r,c),this.set(r,c,s);}validate(t,r){let n=t,i=false,o,s=e.ARRAY_PATTERN.exec(t);return s&&(i=true,n=s[1],o=s[2]),n in Mt&&(r=Mt[n](this,r,i,o)),r}};var Ne=class{header;data;constructor(t,r){this.header=t,this.data=r;}hasData(){return this.data!==void 0}};var Yr=e=>e,Zr=e=>(e&255)<<8|e>>8&255,qr=e=>(e&255)<<24|(e&65280)<<8|e>>8&65280|e>>24&255,ct={8:Yr,B:Yr,16:Zr,I:Zr,32:qr,J:qr},Zi=new TextDecoder("ascii");function je(e){return Zi.decode(e)}function Xt(e){return (2880-e%2880)%2880}function Jr(e){let t=[],r=128;for(;r>=1;)t.push(e&r?1:0),r>>=1;return t}var Ae=class{buffer;blob;static swapEndian=ct;constructor(t){t instanceof ArrayBuffer?this.buffer=t:typeof Blob<"u"&&t instanceof Blob&&(this.blob=t);}};function qi(e){return e instanceof BigInt64Array||e instanceof BigUint64Array}function Ke(e){if(qi(e)){if(e.length===0)return [NaN,NaN];let o=e[0],s=e[0];for(let c=1;c<e.length;c++){let a=e[c];a<o?o=a:a>s&&(s=a);}return [o,s]}let t=e.length,r,n,i=0;for(;i<t;i++){let o=e[i];if(!isNaN(o)){r=n=o,i++;break}}if(r===void 0||n===void 0)return [NaN,NaN];for(;i<t;i++){let o=e[i];isNaN(o)||(o<r?r=o:o>n&&(n=o));}return [r,n]}function Ye(e,t,r,n){let i=r*n+t;return i<0||i>=e.length?NaN:e[i]}var ee=class e extends Ae{bitpix;naxis;width;height;depth;bzero;bscale;bytes;length;frameLength;frameOffsets;constructor(t,r){super(r);let n=t.getNumber("NAXIS");this.bitpix=t.getNumber("BITPIX"),this.naxis=[];for(let i=1;i<=n;i++)this.naxis.push(t.getNumber(`NAXIS${i}`));this.width=t.getNumber("NAXIS1"),this.height=t.getNumber("NAXIS2",1),this.depth=t.getNumber("NAXIS3",1),this.bzero=t.getNumber("BZERO"),this.bscale=t.getNumber("BSCALE",1),this.bytes=Math.abs(this.bitpix)/8,this.length=this.naxis.reduce((i,o)=>i*o,1)*Math.abs(this.bitpix)/8,this.frameOffsets=[],this.frameLength=this.bytes*this.width*this.height;for(let i=0;i<this.depth;i++){let o=i*this.frameLength,s={begin:o};this.buffer&&(s.buffers=[this.buffer.slice(o,o+this.frameLength)]),this.frameOffsets.push(s);}}static computeFrame(t,r,n,i){let o=Math.abs(r)/8,s=t.byteLength/o,c=n===0&&i===1,a=new DataView(t),u=!(Number.isInteger(n)&&Number.isInteger(i));if(r===8){if(c)return new Uint8Array(t.slice(0));let l=u?new Float32Array(s):new Int32Array(s);for(let m=0;m<s;m++)l[m]=n+i*a.getUint8(m);return l}if(r===16){if(c){let m=new Int16Array(s);for(let d=0;d<s;d++)m[d]=a.getInt16(d*2,false);return m}let l=u?new Float32Array(s):new Int32Array(s);for(let m=0;m<s;m++)l[m]=n+i*a.getInt16(m*2,false);return l}if(r===32){if(c){let m=new Int32Array(s);for(let d=0;d<s;d++)m[d]=a.getInt32(d*4,false);return m}let l=new Float64Array(s);for(let m=0;m<s;m++)l[m]=n+i*a.getInt32(m*4,false);return l}if(r===64){if(i===1&&Number.isInteger(n)&&Number.isSafeInteger(n)){let d=new BigInt64Array(s),p=BigInt(n);for(let h=0;h<s;h++)d[h]=a.getBigInt64(h*8,false)+p;return d}let m=new Float64Array(s);if(c)for(let d=0;d<s;d++)m[d]=Number(a.getBigInt64(d*8,false));else for(let d=0;d<s;d++)m[d]=n+i*Number(a.getBigInt64(d*8,false));return m}if(r===-32){let l=new Float32Array(s);if(c)for(let m=0;m<s;m++)l[m]=a.getFloat32(m*4,false);else for(let m=0;m<s;m++)l[m]=n+i*a.getFloat32(m*4,false);return l}let f=new Float64Array(s);if(c)for(let l=0;l<s;l++)f[l]=a.getFloat64(l*8,false);else for(let l=0;l<s;l++)f[l]=n+i*a.getFloat64(l*8,false);return f}async getFrame(t=0){let r=this.frameOffsets[t];if(r.buffers&&r.buffers.length>0)return e.computeFrame(r.buffers[0],this.bitpix,this.bzero,this.bscale);if(!this.blob)throw new Error("No data source available for this image frame");let n=r.begin,o=await this.blob.slice(n,n+this.frameLength).arrayBuffer();return r.buffers=[o],e.computeFrame(o,this.bitpix,this.bzero,this.bscale)}async getFrameAsNumber(t=0){let r=await this.getFrame(t);if(r instanceof Float64Array)return r;let n=new Float64Array(r.length);for(let i=0;i<r.length;i++)n[i]=Number(r[i]);return n}async getFrames(t,r){let n=Array.from({length:r},(i,o)=>t+o);return Promise.all(n.map(i=>this.getFrame(i)))}isDataCube(){return this.naxis.length>2}async*[Symbol.asyncIterator](){for(let t=0;t<this.depth;t++)yield this.getFrame(t);}getExtent(t){return Ke(t)}getPixel(t,r,n){return Ye(t,r,n,this.width)}};var _t={L:1,B:1,I:2,J:4,K:8,A:1,E:4,D:8,C:8,M:16},Be={B:Uint8Array,I:Int16Array,J:Int32Array,K:BigInt64Array,E:Float32Array,D:Float64Array,1:Uint8Array,2:Int16Array,4:Int32Array};var ve=class extends Ae{maxMemory=1048576;rowByteSize;rows;cols;length;heapLength;columns;accessors=[];descriptors=[];elementByteLengths=[];columnTypes=[];heap;typedArray=Be;firstRowInBuffer=0;lastRowInBuffer=0;nRowsInBuffer=0;cachedBuffer;constructor(t,r){super(r),this.rowByteSize=t.getNumber("NAXIS1"),this.rows=t.getNumber("NAXIS2"),this.cols=t.getNumber("TFIELDS"),this.length=this.rowByteSize*this.rows,this.heapLength=t.getNumber("PCOUNT"),this.columns=this.getColumns(t),this.buffer?this.heap=this.buffer.slice(this.length,this.length+this.heapLength):(this.firstRowInBuffer=0,this.lastRowInBuffer=0,this.nRowsInBuffer=Math.floor(this.maxMemory/this.rowByteSize));}initAccessors(t){this.resetAccessors(),this.setAccessors(t);}resetAccessors(){this.accessors=[],this.descriptors=[],this.elementByteLengths=[],this.columnTypes=[];}rowsInMemory(t,r){return this.buffer&&!this.blob?true:this.cachedBuffer?!(t<this.firstRowInBuffer||r>this.lastRowInBuffer):false}getColumns(t){let r=[];for(let n=1;n<=this.cols;n++){let i=`TTYPE${n}`;if(!t.contains(i))return null;r.push(t.getString(i));}return r}async getRows(t,r){if(this.rowsInMemory(t,t+r)){let a;if(this.cachedBuffer){let u=(t-this.firstRowInBuffer)*this.rowByteSize;a=this.cachedBuffer.slice(u,u+r*this.rowByteSize);}else if(this.buffer){let u=t*this.rowByteSize,f=u+r*this.rowByteSize;a=this.buffer.slice(u,f);}else throw new Error("No data source available");return this._getRows(a,r)}if(!this.blob)throw new Error("No data source available");let n=t*this.rowByteSize,i=Math.max(this.nRowsInBuffer,r),o=n+i*this.rowByteSize,c=await this.blob.slice(n,o).arrayBuffer();return this.cachedBuffer=c,this.firstRowInBuffer=t,this.lastRowInBuffer=t+i,this._getRows(c,r)}async getTableBuffer(t,r){let n=Math.min(this.rows-t,r),i=t*this.rowByteSize,o=i+n*this.rowByteSize;if(this.buffer)return this.buffer.slice(i,o);if(!this.blob)throw new Error("No data source available");return this.blob.slice(i,o).arrayBuffer()}async getColumn(t){if(!this.columns)throw new Error("Column names not available");let r=this.columns.indexOf(t);if(r===-1)throw new Error(`Column "${t}" not found`);if(this.buffer&&!this.blob)return (await this.getRows(0,this.rows)).map(m=>m[t]);let n=this.accessors[r],i=this.elementByteLengths.slice(0,r).reduce((l,m)=>l+m,0),o=new Array(this.rows),s=Math.min(Math.max(1,Math.floor(this.maxMemory/this.rowByteSize)),this.rows),c=this.rows/s,a=Math.floor(c)===c?c:Math.floor(c)+1,u=0,f=0;for(;a>0;){let l=f*s,m=await this.getTableBuffer(l,s),d=m.byteLength/this.rowByteSize,p=new DataView(m),h=i;for(let b=0;b<d;b++)o[u]=n(p,h)[0],u++,h+=this.rowByteSize;a--,f++;}return o}};var Ji={A:e=>e.trim(),I:e=>parseInt(e,10),F:e=>parseFloat(e),E:e=>parseFloat(e),D:e=>parseFloat(e)},Ze=class extends ve{asciiAccessors=[];colStarts=[];colWidths=[];hasTBCOL=false;constructor(t,r){super(t,r),this.initAccessors(t);}setAccessors(t){this.asciiAccessors=[],this.colStarts=[],this.colWidths=[],this.hasTBCOL=false;let r=/([AIFED])(\d+)\.*(\d+)*/;for(let n=1;n<=this.cols;n++)if(t.contains(`TBCOL${n}`)){this.hasTBCOL=true;break}for(let n=1;n<=this.cols;n++){let i=t.getString(`TFORM${n}`),o=r.exec(i);if(!o){this.asciiAccessors.push(f=>f.trim()),this.colStarts.push(0),this.colWidths.push(0);continue}let s=o[1],c=parseInt(o[2],10),a=Ji[s]??(f=>f.trim());this.asciiAccessors.push(a);let u=t.contains(`TBCOL${n}`)?t.getNumber(`TBCOL${n}`)-1:0;this.colStarts.push(u),this.colWidths.push(c);}}_getRows(t,r){let n=t.byteLength/this.rowByteSize,i=new Uint8Array(t),o=[],s=this.asciiAccessors??[];for(let c=0;c<n;c++){let a=c*this.rowByteSize,u=a+this.rowByteSize,f=i.subarray(a,u),l=je(f),m={};if(this.hasTBCOL)for(let d=0;d<s.length;d++){let p=this.colStarts[d],h=this.colWidths[d],b=l.substring(p,p+h).trim();this.columns&&(m[this.columns[d]]=s[d](b));}else {let d=l.trim().split(/\s+/);for(let p=0;p<s.length;p++){let h=d[p]??"";this.columns&&(m[this.columns[p]]=s[p](h));}}o.push(m);}return o}};var Qr={L(e,t){return [e.getInt8(t)===84,t+1]},B(e,t){return [e.getUint8(t),t+1]},I(e,t){return [e.getInt16(t,false),t+2]},J(e,t){return [e.getInt32(t,false),t+4]},K(e,t){return [e.getBigInt64(t,false),t+8]},A(e,t){return [String.fromCharCode(e.getUint8(t)),t+1]},E(e,t){return [e.getFloat32(t,false),t+4]},D(e,t){return [e.getFloat64(t,false),t+8]},C(e,t){let r=e.getFloat32(t,false),n=e.getFloat32(t+4,false);return [[r,n],t+8]},M(e,t){let r=e.getFloat64(t,false),n=e.getFloat64(t+8,false);return [[r,n],t+16]}},q=class extends ve{constructor(t,r){super(t,r),this.initAccessors(t);}setAccessors(t){let r=/(\d*)([PQ]?)([LXBIJKAEDCM])(?:\(\d+\))?$/;for(let n=1;n<=this.cols;n++){let i=t.getString(`TFORM${n}`),o=t.getString(`TTYPE${n}`),s=r.exec(i);if(!s)throw new Error(`Unsupported or invalid TFORM${n} value: '${i}'`);let c=parseInt(s[1],10)||1,a=s[2],u=s[3];this.descriptors.push(u),this.columnTypes.push(o),this.elementByteLengths.push((_t[u]??1)*c),a?this.setupArrayAccessor(u,o):c===1?this.setupSingleAccessor(u):u==="X"?this.setupBitArrayAccessor(c):u==="A"?this.setupCharArrayAccessor(c):this.setupMultiAccessor(u,c);}}getFromHeap(t,r,n){let i=t.getInt32(r,false);r+=4;let o=t.getInt32(r,false);if(r+=4,!this.heap)throw new Error("Heap not available");let s=_t[n]??1,c=this.heap.slice(o,o+i*s),a=Be[n];if(!a)throw new Error(`No typed array constructor for descriptor: ${n}`);let u=new a(c),f=ct[n];if(f&&n!=="B")for(let l=0;l<u.length;l++){let m=u[l];typeof m=="number"&&(u[l]=f(m));}return [u,r]}setupArrayAccessor(t,r){if(r==="COMPRESSED_DATA"){let n=(i,o)=>{let[s,c]=this.getFromHeap(i,o,t);return [s,c]};this.accessors.push(n);}else if(r==="GZIP_COMPRESSED_DATA"){let n=(i,o)=>{throw new O("GZIP decompression is not yet implemented")};this.accessors.push(n);}else {let n=(i,o)=>this.getFromHeap(i,o,t);this.accessors.push(n);}}setupSingleAccessor(t){let r=Qr[t];if(!r)throw new Error(`Unknown binary table type code: ${t}`);let n=(i,o)=>r(i,o);this.accessors.push(n);}setupBitArrayAccessor(t){let r=Math.ceil(t/8),n=(i,o)=>{let s=i.buffer.slice(o,o+r),c=new Uint8Array(s),a=[];for(let u=0;u<c.length;u++)a=a.concat(Jr(c[u]));return [a.slice(0,t),o+r]};this.accessors.push(n);}setupCharArrayAccessor(t){let r=(n,i)=>{let o=n.buffer.slice(i,i+t),s=new Uint8Array(o),c="";for(let a=0;a<s.length;a++)c+=String.fromCharCode(s[a]);return [c.trim(),i+t]};this.accessors.push(r);}setupMultiAccessor(t,r){let n=Qr[t];if(!n)throw new Error(`Unknown binary table type code: ${t}`);let i=(o,s)=>{let c=[],a=s;for(let u=0;u<r;u++){let[f,l]=n(o,a);c.push(f),a=l;}return [c,a]};this.accessors.push(i);}_getRows(t,r){let n=new DataView(t),i=0,o=[];for(let s=0;s<r;s++){let c={};for(let a=0;a<this.accessors.length;a++){let[u,f]=this.accessors[a](n,i);i=f,this.columns&&(c[this.columns[a]]=u);}o.push(c);}return o}};var ut={1(e){return [3,6,e[0],1]},2(e){let i=0;return i=i|e[0]<<8,i=i|e[1],[4,14,i,2]},4(e){let i=0;return i=i|e[0]<<24,i=i|e[1]<<16,i=i|e[2]<<8,i=i|e[3],[5,25,i,4]}};function Ht(e,t,r,n,i,o=ut){let s=o[r];if(!s)throw new Error(`Unsupported bytepix value: ${r}`);let[c,a,u,f]=s(e),l=u,m=f,d=1<<c,p=new Uint8Array(256),h=8,b=128,g=255;for(;g>=0;){for(;g>=b;)p[g]=h,g--;b=b/2,h--;}p[0]=0;let y=e[m++],w=8,S=0;for(;S<i;){for(w-=c;w<0;)y=y<<8|e[m++],w+=8;let I=(y>>w)-1;y&=(1<<w)-1;let A=S+t;if(A>i&&(A=i),I<0)for(;S<A;)n[S]=l,S++;else if(I===a)for(;S<A;){b=d-w;let x=y<<b;for(b-=8;b>=0;)y=e[m++],x|=y<<b,b-=8;w>0?(y=e[m++],x|=y>>-b,y&=(1<<w)-1):y=0,(x&1)===0?x=x>>1:x=~(x>>1),n[S]=x+l,l=n[S],S++;}else for(;S<A;){for(;y===0;)w+=8,y=e[m++];for(h=w-p[y],w-=h+1,y^=1<<w,w-=I;w<0;)y=y<<8|e[m++],w+=8;let x=h<<I|y>>w;y&=(1<<w)-1,(x&1)===0?x=x>>1:x=~(x>>1),n[S]=x+l,l=n[S],S++;}}return n}var Qi=221,eo=153,$t=class{constructor(t){this.bytes=t;}nextChar=0;bitBuffer=0;bitsToGo=0;readInt32BE(){let t=this.readByte(),r=this.readByte(),n=this.readByte(),i=this.readByte();return t<<24|r<<16|n<<8|i|0}readInt64BE(){let t=0n;for(let r=0;r<8;r++)t=(t<<8n)+BigInt(this.readByte());return (t&1n<<63n)!==0n&&(t-=1n<<64n),t}readByte(){if(this.nextChar>=this.bytes.byteLength)throw new O("Unexpected end of HCOMPRESS stream");let t=this.bytes[this.nextChar];return this.nextChar+=1,t}startBitInput(){this.bitsToGo=0;}inputBit(){return this.bitsToGo===0&&(this.bitBuffer=this.readByte(),this.bitsToGo=8),this.bitsToGo-=1,this.bitBuffer>>this.bitsToGo&1}inputNBits(t){return this.bitsToGo<t&&(this.bitBuffer=this.bitBuffer<<8|this.readByte(),this.bitsToGo+=8),this.bitsToGo-=t,this.bitBuffer>>this.bitsToGo&(1<<t)-1}inputNybble(){return this.bitsToGo<4&&(this.bitBuffer=this.bitBuffer<<8|this.readByte(),this.bitsToGo+=8),this.bitsToGo-=4,this.bitBuffer>>this.bitsToGo&15}inputNNybble(t,r){for(let n=0;n<t;n++)r[n]=this.inputNybble();}};function tn(e){let t=e.inputNBits(3);if(t<4)return 1<<t;if(t=e.inputBit()|t<<1,t<13)switch(t){case 8:return 3;case 9:return 5;case 10:return 10;case 11:return 12;case 12:return 15}if(t=e.inputBit()|t<<1,t<31)switch(t){case 26:return 6;case 27:return 7;case 28:return 9;case 29:return 11;case 30:return 13}return t=e.inputBit()|t<<1,t===62?0:14}function rn(e,t,r,n,i,o){let s=1<<o,c=0,a=0;for(;a<t-1;a+=2){let u=i*a,f=0;for(;f<r-1;f+=2){let l=e[c];(l&1)!==0&&(n[u+i+1]=n[u+i+1]|s),(l&2)!==0&&(n[u+i]=n[u+i]|s),(l&4)!==0&&(n[u+1]=n[u+1]|s),(l&8)!==0&&(n[u]=n[u]|s),u+=2,c+=1;}if(f<r){let l=e[c];(l&2)!==0&&(n[u+i]=n[u+i]|s),(l&8)!==0&&(n[u]=n[u]|s),c+=1;}}if(a<t){let u=i*a,f=0;for(;f<r-1;f+=2){let l=e[c];(l&4)!==0&&(n[u+1]=n[u+1]|s),(l&8)!==0&&(n[u]=n[u]|s),u+=2,c+=1;}f<r&&((e[c]&8)!==0&&(n[u]=n[u]|s),c+=1);}}function to(e,t,r,n,i){let o=t+1>>1,s=r+1>>1,c=s*(o-1)+s-1;for(let u=o-1;u>=0;u--){let f=2*(i*u+s-1);for(let l=s-1;l>=0;l--)n[f]=e[c],c-=1,f-=2;}let a=0;for(;a<t-1;a+=2){let u=i*a,f=u+i,l=0;for(;l<r-1;l+=2){let m=n[u];n[f+1]=m&1,n[f]=m>>1&1,n[u+1]=m>>2&1,n[u]=m>>3&1,u+=2,f+=2;}if(l<r){let m=n[u];n[f]=m>>1&1,n[u]=m>>3&1;}}if(a<t){let u=i*a,f=0;for(;f<r-1;f+=2){let l=n[u];n[u+1]=l>>2&1,n[u]=l>>3&1,u+=2;}f<r&&(n[u]=n[u]>>3&1);}}function ro(e,t,r,n,i){to(t,r,n,i,n);for(let o=r*n-1;o>=0;o--)i[o]!==0&&(i[o]=tn(e));}function no(e,t,r,n,i,o,s){let c=(n+1>>1)*(i+1>>1);e.inputNNybble(c,o),rn(o,n,i,t,r,s);}function lt(e,t,r,n,i,o){if(o<=0||n<=0||i<=0)return;let s=n>i?n:i,c=Math.floor(Math.log(s)/Math.log(2)+.5);s>1<<c&&(c+=1);let a=n+1>>1,u=i+1>>1,f=new Uint8Array(a*u);for(let l=o-1;l>=0;l--){let m=e.inputNybble();if(m===0){no(e,t,r,n,i,f,l);continue}if(m!==15)throw new O("Invalid HCOMPRESS bitplane format code");f[0]=tn(e);let d=1,p=1,h=n,b=i,g=1<<c;for(let y=1;y<c;y++)g>>=1,d<<=1,p<<=1,h<=g?d-=1:h-=g,b<=g?p-=1:b-=g,ro(e,f,d,p,f);rn(f,n,i,t,r,l);}}function en(e,t,r,n,i){let o=r+1>>1,s=0,c=t+n*o;for(let u=o;u<r;u++)i[s++]=e[c],c+=n;let a=t+n*(o-1);c=t+(n*(o-1)<<1);for(let u=o-1;u>=0;u--)e[c]=e[a],a-=n,c-=n+n;s=0,c=t+n;for(let u=1;u<r;u+=2)e[c]=i[s++],c+=n+n;}function io(e,t,r,n,i){let o=i>>1;if(o<=0)return;let s=n<<1;for(let c=2;c<t-2;c+=2){let a=n*c,u=a+n;for(let f=0;f<r;f+=2){let l=e[a-s],m=e[a],d=e[a+s],p=d-l,h=Math.max(Math.min(d-m,m-l),0)<<2,b=Math.min(Math.max(d-m,m-l),0)<<2;if(b<h){p=Math.max(Math.min(p,h),b);let g=p-(e[u]<<3);g=g>=0?g>>3:g+7>>3,g=Math.max(Math.min(g,o),-o),e[u]=e[u]+g|0;}a+=2,u+=2;}}for(let c=0;c<t;c+=2){let a=n*c+2;for(let u=2;u<r-2;u+=2){let f=e[a-2],l=e[a],m=e[a+2],d=m-f,p=Math.max(Math.min(m-l,l-f),0)<<2,h=Math.min(Math.max(m-l,l-f),0)<<2;if(h<p){d=Math.max(Math.min(d,p),h);let b=d-(e[a+1]<<3);b=b>=0?b>>3:b+7>>3,b=Math.max(Math.min(b,o),-o),e[a+1]=e[a+1]+b|0;}a+=2;}}for(let c=2;c<t-2;c+=2){let a=n*c+2,u=a+n;for(let f=2;f<r-2;f+=2){let l=e[a-s-2],m=e[a+s-2],d=e[a-s+2],p=e[a+s+2],h=e[a],b=p+l-d-m,g=e[u]<<1,y=e[a+1]<<1,w=Math.min(Math.max(p-h,0)-g-y,Math.max(h-m,0)+g-y),S=Math.min(Math.max(h-d,0)-g+y,Math.max(l-h,0)+g+y),I=Math.min(w,S)<<4;w=Math.max(Math.min(p-h,0)-g-y,Math.min(h-m,0)+g-y),S=Math.max(Math.min(h-d,0)-g+y,Math.min(l-h,0)+g+y);let A=Math.max(w,S)<<4;if(A<I){b=Math.max(Math.min(b,I),A);let x=b-(e[u+1]<<6);x=x>=0?x>>6:x+63>>6,x=Math.max(Math.min(x,o),-o),e[u+1]=e[u+1]+x|0;}a+=2,u+=2;}}}function oo(e,t){if(!(t<=1))for(let r=0;r<e.length;r++)e[r]=Math.imul(e[r],t);}function so(e,t,r,n,i){let o=t>r?t:r,s=Math.floor(Math.log(o)/Math.log(2)+.5);o>1<<s&&(s+=1);let c=new Int32Array(o+1>>1),a=1,u=1<<s-1,f=u<<1,l=u<<2,m=-u,d=m<<1,p=m<<2,h=u>>1,b=f>>1,g=l>>1,y=h-1,w=b-1,S=g-1;e[0]=e[0]+(e[0]>=0?g:S)&p;let I=1,A=1,x=t,E=r,L=1<<s;for(let C=s-1;C>=0;C--){L>>=1,I<<=1,A<<=1,x<=L?I-=1:x-=L,E<=L?A-=1:E-=L,C===0&&(y=0,a=2);for(let R=0;R<I;R++)en(e,r*R,A,1,c);for(let R=0;R<A;R++)en(e,R,I,r,c);n&&io(e,I,A,r,i);let $=I%2,U=A%2,k=0;for(;k<I-$;k+=2){let R=r*k,X=R+r,Z=0;for(;Z<A-U;Z+=2){let P=e[R],v=e[X],N=e[R+1],Q=e[X+1];v=v+(v>=0?b:w)&d,N=N+(N>=0?b:w)&d,Q=Q+(Q>=0?h:y)&m;let me=Q&u;v=v>=0?v-me:v+me,N=N>=0?N-me:N+me;let he=(Q^v^N)&f;P=P>=0?P+me-he:P+(me===0?he:me-he),e[X+1]=P+v+N+Q>>a,e[X]=P+v-N-Q>>a,e[R+1]=P-v+N-Q>>a,e[R]=P-v-N+Q>>a,R+=2,X+=2;}if(U){let P=e[R],v=e[X];v=v+(v>=0?b:w)&d;let N=v&f;P=P>=0?P-N:P+N,e[X]=P+v>>a,e[R]=P-v>>a;}}if($){let R=r*k,X=0;for(;X<A-U;X+=2){let Z=e[R],P=e[R+1];P=P+(P>=0?b:w)&d;let v=P&f;Z=Z>=0?Z-v:Z+v,e[R+1]=Z+P>>a,e[R]=Z-P>>a,R+=2;}U&&(e[R]=e[R]>>a);}l=f,f=u,u>>=1,d=m,m>>=1,b=h,h>>=1,w=y,y=h-1;}}function ao(e,t){let r=e.readByte(),n=e.readByte();if(r!==Qi||n!==eo)throw new O("Invalid HCOMPRESS stream magic");let i=e.readInt32BE(),o=e.readInt32BE(),s=e.readInt32BE(),c=Number(e.readInt64BE()),a=Uint8Array.from([e.readByte(),e.readByte(),e.readByte()]),u=new Int32Array(i*o),f=i+1>>1,l=o+1>>1;if(e.startBitInput(),lt(e,u.subarray(0),o,f,l,a[0]),lt(e,u.subarray(l),o,f,Math.floor(o/2),a[1]),lt(e,u.subarray(o*f),o,Math.floor(i/2),l,a[1]),lt(e,u.subarray(o*f+l),o,Math.floor(i/2),Math.floor(o/2),a[2]),e.inputNybble()!==0)throw new O("Invalid HCOMPRESS bit-plane termination marker");e.startBitInput();for(let m=0;m<u.length;m++)u[m]!==0&&e.inputBit()!==0&&(u[m]=-u[m]);return u[0]=c|0,oo(u,s),so(u,i,o,t,s),{pixels:u,nx:i,ny:o}}function nn(e,t=false){let r=new $t(e);return ao(r,t)}var Wt;function co(e){Wt=e;}function uo(){return Wt}function lo(){let r=1,n=new Float32Array(1e4);for(let i=0;i<1e4;i++){let o=16807*r;r=o-2147483647*Math.floor(o/2147483647),n[i]=r/2147483647;}return n}var Vt=lo();function fo(e,t){let r=m=>e[m-1]??0,n,i;r(3)>0?(n=r(3),i=4):(n=(r(5)<<15)+(r(4)&32767),i=r(2)+1);let o=new Int32Array(t);if(t<=0||n<=0)return o;let s=1,c=s+t-1,a=false,u=1,f=1,l=1;for(let m=i;m<=n;m++){if(a){a=false;continue}let d=r(m),p=Math.trunc(d/4096),h=d&4095;if(p===0||p===4||p===5){let b=f+h-1,g=Math.max(f,s),y=Math.min(b,c),w=y-g+1;if(w>0){let S=u+w-1;if(p===4)for(let I=u;I<=S;I++)o[I-1]=l;else {for(let I=u;I<=S;I++)o[I-1]=0;p===5&&y===b&&(o[S-1]=l);}u=S+1;}f=b+1;}else p===1?(l=(r(m+1)<<12)+h,a=true):p===2?l+=h:p===3?l-=h:(p===6||p===7)&&(l+=p===6?h:-h,f>=s&&f<=c&&(o[u-1]=l,u++),f++);if(f>c)break}for(let m=u;m<=t;m++)o[m-1]=0;return o}function mo(e){if(e instanceof Int16Array)return e;if(e instanceof Uint8Array){if(e.byteLength%2!==0)throw new O("PLIO_1 compressed stream must contain 16-bit words");let t=new Int16Array(e.byteLength/2),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let n=0;n<t.length;n++)t[n]=r.getInt16(n*2,false);return t}if(e instanceof Uint16Array){let t=new Int16Array(e.length);for(let r=0;r<e.length;r++)t[r]=e[r]<<16>>16;return t}throw new O(`PLIO_1 requires Int16Array/Uint16Array/Uint8Array compressed payload, got ${e.constructor.name}`)}function po(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function sn(e,t,r){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t===8){if(e.byteLength<r)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=8");let i=new Int32Array(r);for(let o=0;o<r;o++)i[o]=e[o];return i}if(t===16){if(e.byteLength<r*2)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=16");let i=new Int32Array(r);for(let o=0;o<r;o++)i[o]=n.getInt16(o*2,false);return i}if(t===32){if(e.byteLength<r*4)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=32");let i=new Int32Array(r);for(let o=0;o<r;o++)i[o]=n.getInt32(o*4,false);return i}if(t===64){if(e.byteLength<r*8)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=64");let i=new Float64Array(r);for(let o=0;o<r;o++)i[o]=Number(n.getBigInt64(o*8,false));return i}if(t===-32){if(e.byteLength<r*4)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=-32");let i=new Float32Array(r);for(let o=0;o<r;o++)i[o]=n.getFloat32(o*4,false);return i}if(t===-64){if(e.byteLength<r*8)throw new O("Decoded GZIP tile is smaller than expected for BITPIX=-64");let i=new Float64Array(r);for(let o=0;o<r;o++)i[o]=n.getFloat64(o*8,false);return i}throw new O(`Unsupported ZBITPIX for GZIP_1: ${t}`)}var qe=class extends q{zcmptype;zbitpix;znaxis;zblank;blank;zdither;ztile;width;height;bzero;bscale;algorithmParameters;zquantiz;decoderProvider;currentTilePixelCount;constructor(t,r,n={}){super(t,r),this.zcmptype=t.getString("ZCMPTYPE"),this.zbitpix=t.getNumber("ZBITPIX"),this.znaxis=t.getNumber("ZNAXIS"),this.zblank=t.contains("ZBLANK")?t.getNumber("ZBLANK"):null,this.blank=t.contains("BLANK")?t.getNumber("BLANK"):null,this.zdither=t.getNumber("ZDITHER0"),this.ztile=[];for(let o=1;o<=this.znaxis;o++){let s=t.contains(`ZTILE${o}`)?t.getNumber(`ZTILE${o}`):o===1?t.getNumber("ZNAXIS1"):1;this.ztile.push(s);}this.width=t.getNumber("ZNAXIS1"),this.height=t.getNumber("ZNAXIS2",1),this.algorithmParameters={},this.zcmptype==="RICE_1"&&(this.algorithmParameters.BLOCKSIZE=32,this.algorithmParameters.BYTEPIX=4);let i=1;for(;t.contains(`ZNAME${i}`);){let o=t.getString(`ZNAME${i}`),s=t.getNumber(`ZVAL${i}`);this.algorithmParameters[o]=s,i++;}this.zquantiz=t.getString("ZQUANTIZ","LINEAR_SCALING"),this.bzero=t.getNumber("BZERO"),this.bscale=t.getNumber("BSCALE",1),this.decoderProvider=n.decoderProvider,this.initAccessors(t);}decodeCompressedTile(t,r,n){let i=po(t);if(this.zcmptype==="RICE_1"){let s=this.algorithmParameters.BYTEPIX??4,c=this.algorithmParameters.BLOCKSIZE??32,a=Be[s];if(!a)throw new Error(`No typed array for bytepix: ${s}`);let u=new a(n);return Ht(i,c,s,u,n,ut),u}if(this.zcmptype==="GZIP_1"){let s=fflate.gunzipSync(i);return sn(s,this.zbitpix,n)}if(this.zcmptype==="PLIO_1"){let s=mo(t);return fo(s,n)}if(this.zcmptype==="HCOMPRESS_1"){let s=(this.algorithmParameters.SMOOTH??0)!==0,c=nn(i,s).pixels;if(c.length!==n)throw new O(`HCOMPRESS_1 tile length mismatch (decoded=${c.length}, expected=${n})`);return c}let o=this.decoderProvider??Wt;if(o){let s=o.decodeTile({algorithm:this.zcmptype,compressedBytes:i,compressedData:t,descriptor:r,zbitpix:this.zbitpix,tileSize:n,ztile:this.ztile,algorithmParameters:this.algorithmParameters});if(s!=null)return s}throw new O(`Unsupported compressed image algorithm: ${this.zcmptype}`)}getNominalTileWidth(){return this.ztile?.[0]??this.width}getNominalTileHeight(){return this.ztile?.[1]??1}getDefaultTilePixelCount(){return this.getNominalTileWidth()*this.getNominalTileHeight()}getTilePlacement(t){let r=this.getNominalTileWidth(),n=this.getNominalTileHeight(),i=Math.max(1,Math.ceil(this.width/r)),o=Math.max(0,t-1),s=o%i,c=Math.floor(o/i),a=s*r,u=c*n,f=Math.max(0,Math.min(r,this.width-a)),l=Math.max(0,Math.min(n,this.height-u));return {x:a,y:u,width:f,height:l,pixelCount:f*l}}setAccessors(t){super.setAccessors(t);for(let r=0;r<this.columnTypes.length;r++){let n=this.columnTypes[r],i=this.descriptors[r];n==="COMPRESSED_DATA"?this.accessors[r]=(o,s)=>{let[c,a]=this.getFromHeap(o,s,i),u=this.currentTilePixelCount??this.getDefaultTilePixelCount();return [this.decodeCompressedTile(c,i,u),a]}:n==="GZIP_COMPRESSED_DATA"&&(this.accessors[r]=(o,s)=>{let[c,a]=this.getFromHeap(o,s,i),u=c instanceof Uint8Array?c:new Uint8Array(c.buffer,c.byteOffset,c.byteLength),f=this.currentTilePixelCount??this.getDefaultTilePixelCount(),l=fflate.gunzipSync(u);return [sn(l,this.zbitpix,f),a]});}}_getRows(t,r){let n=new DataView(t),i=0,o=new Float32Array(this.width*this.height),s=0,c=r;for(;c--;){s++;let a=s,u=this.getTilePlacement(a);this.currentTilePixelCount=u.pixelCount;let f={};for(let y=0;y<this.accessors.length;y++){let[w,S]=this.accessors[y](n,i);i=S,this.columns&&(f[this.columns[y]]=w);}let l=f.COMPRESSED_DATA||f.UNCOMPRESSED_DATA||f.GZIP_COMPRESSED_DATA,m=f.ZSCALE||this.bscale,d=f.ZZERO||this.bzero,p=this.zquantiz==="SUBTRACTIVE_DITHER_1"||this.zquantiz==="SUBTRACTIVE_DITHER_2",h=0,b=0;if(p){let w=(a+this.zdither-1-1)%1e4;b=w<0?w+1e4:w,h=Math.floor(Vt[b]*500);}let g=Math.min(l.length,u.pixelCount);for(let y=0;y<g;y++){if(u.width<=0||u.height<=0)continue;let w=y%u.width,S=Math.floor(y/u.width);if(S>=u.height)break;let I=(u.y+S)*this.width+u.x+w,A=l[y];if(A===-2147483647)o[I]=NaN;else if(A===-2147483646)o[I]=0;else if(p){let x=Vt[h];o[I]=(A-x+.5)*m+d;}else o[I]=A*m+d;p&&(h++,h===1e4&&(b=(b+1)%1e4,h=Math.floor(Vt[b]*500)));}this.currentTilePixelCount=void 0;}return o}async getFrame(t=0){if(this.heap)return await this.getRows(0,this.rows);if(!this.blob)throw new Error("No data source available");let r=this.blob.slice(this.length,this.length+this.heapLength);return this.heap=await r.arrayBuffer(),this.getFrame(t)}getExtent(t){let[r,n]=Ke(t);return [Number(r),Number(n)]}getPixel(t,r,n){return Number(Ye(t,r,n,this.width))}};function an(e,t){let r=e.getDataType();if(r)switch(r){case "Image":return new ee(e,t);case "BinaryTable":return new q(e,t);case "Table":return new Ze(e,t);case "CompressedImage":return new qe(e,t);default:return}}function zt(e,t){let r=[],n=e.byteLength,i=0;for(;i<n;){let o=0,s=new Uint8Array(0),c=false;for(;!c&&i+o*2880+2880<=n;){let a=i+o*2880,u=new Uint8Array(e,a,2880),f=new Uint8Array(s.length+2880);f.set(s,0),f.set(u,s.length),s=f;let l=2880/80;for(let y=l-1;y>=0;y--){let w=y*80,S=u[w];if(S!==32){if(S===69&&u[w+1]===78&&u[w+2]===68&&u[w+3]===32){c=true;break}break}}if(o++,!c)continue;let m=je(s),d=new Ue(m,t?.maxHeaderLines,t?.onWarning),p=i+o*2880,h=d.getDataLength(),b=e.slice(p,p+h),g;if(d.hasDataUnit()&&(g=an(d,b)),r.push(new Ne(d,g)),i=p+h+Xt(h),i>=n)break}if(!c)break}return r}async function Gt(e,t){let r=[],n=e.size,i=0;for(;i<n;){let o=0,s=[],c=false;for(;!c&&i+o*2880+2880<=n;){let a=i+o*2880,f=await e.slice(a,a+2880).arrayBuffer(),l=new Uint8Array(f);s.push(l);let m=2880/80;for(let I=m-1;I>=0;I--){let A=I*80,x=l[A];if(x!==32){if(x===69&&l[A+1]===78&&l[A+2]===68&&l[A+3]===32){c=true;break}break}}if(o++,!c)continue;let d=s.reduce((I,A)=>I+A.length,0),p=new Uint8Array(d),h=0;for(let I of s)p.set(I,h),h+=I.length;let b=je(p),g=new Ue(b,t?.maxHeaderLines,t?.onWarning),y=i+o*2880,w=g.getDataLength(),S;if(g.hasDataUnit()){let I=e.slice(y,y+w);S=an(g,I);}if(r.push(new Ne(g,S)),i=y+w+Xt(w),i>=n)break}if(!c)break}return r}var j=class e{hdus;constructor(t){this.hdus=t;}static fromArrayBuffer(t,r){let n=zt(t,r);return new e(n)}static async fromBlob(t,r){let n=await Gt(t,r);return new e(n)}static async fromURL(t,r){let n=await fetch(t,r?.requestInit);if(!n.ok)throw new Error(`Failed to fetch FITS file: ${n.status} ${n.statusText}`);let i=await n.arrayBuffer();return e.fromArrayBuffer(i,r)}static fromNodeBuffer(t,r){let n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return e.fromArrayBuffer(n,r)}getHDU(t){if(t!==void 0)return t>=0&&t<this.hdus.length?this.hdus[t]:void 0;for(let r of this.hdus)if(r.hasData())return r}getHeader(t){return this.getHDU(t)?.header}getDataUnit(t){return this.getHDU(t)?.data}};var ae=class extends se{constructor(t){super(t),this.name="XISFError";}},B=class extends ae{constructor(t){super(t),this.name="XISFParseError";}},F=class extends ae{constructor(t){super(t),this.name="XISFValidationError";}},ce=class extends ae{constructor(t){super(t),this.name="XISFResourceError";}},K=class extends ae{constructor(t){super(t),this.name="XISFCompressionError";}},ge=class extends ae{constructor(t){super(t),this.name="XISFChecksumError";}},ke=class extends ae{constructor(t){super(t),this.name="XISFSignatureError";}},Y=class extends ae{constructor(t){super(t),this.name="XISFConversionError";}};var jt="XISF0100",Je=8,cn=8,un=4,Qe=Je+4+un;function ln(e){return new TextDecoder("ascii").decode(e)}function fn(e){return e.byteLength<Qe?false:ln(new Uint8Array(e,0,Je))===jt}function mn(e){if(e.byteLength<Qe)throw new B("Invalid XISF file: too short");let t=ln(new Uint8Array(e,0,Je));if(t!==jt)throw new B(`Invalid XISF signature: ${t}`);let n=new DataView(e).getUint32(cn,true),i=Qe,o=i+n;if(o>e.byteLength)throw new B("Invalid XISF header length");let s=new Uint8Array(e,i,n),c=new TextDecoder("utf-8").decode(s),a=new Uint8Array(e,Je+4,un),u=new Uint8Array(e,o);return {signature:t,headerLength:n,reserved:a,headerXml:c,payload:u}}function dn(e,t,r){if(t<0||r<0||t+r>e.byteLength)throw new B(`Attachment block out of bounds: position=${t}, size=${r}`);return new Uint8Array(e,t,r)}function pn(e,t){let r=new TextEncoder().encode(e),i=Qe+r.byteLength;for(let c of t){let a=c.position+c.data.byteLength;a>i&&(i=a);}let o=new Uint8Array(i);o.set(new TextEncoder().encode(jt),0);let s=new DataView(o.buffer);s.setUint32(cn,r.byteLength,true),s.setUint32(Je+4,0,true),o.set(r,Qe);for(let c of t)o.set(c.data,c.position);return o}var go="http://www.pixinsight.com/xisf";function Kt(e){let t=e,r=t.localName;if(r&&r.length>0)return r;let n=t.nodeName,i=n.indexOf(":");return i>=0?n.slice(i+1):n}function bo(e){return e.nodeType===1}function gn(e){let t=new xmldom.DOMParser().parseFromString(e,"application/xml"),r=t.getElementsByTagName("parsererror");if(r.length>0)throw new B((r[0]?.textContent??"Invalid XML").trim());let n=t.documentElement;if(!n)throw new B("Empty XML document");if(Kt(n)!=="xisf")throw new F(`Invalid root element: ${n.nodeName}`);let i=n.getAttribute("version");if(i!=="1.0")throw new F(`Unsupported XISF version: ${i??"none"}`);return t}function yo(e){let t=[];for(let r=0;r<e.childNodes.length;r++){let n=e.childNodes.item(r);n&&bo(n)&&t.push(n);}return t}function te(e,t){return yo(e).filter(r=>Kt(r)===t)}function et(e,t){let r=te(e,t);return r.length>0?r[0]:null}function xe(e){return Kt(e)}function ft(e){return new xmldom.XMLSerializer().serializeToString(e)}function Yt(){let e=new xmldom.DOMParser().parseFromString('<?xml version="1.0" encoding="UTF-8"?><xisf version="1.0"/>',"application/xml"),t=e.documentElement;return t.setAttribute("xmlns",go),t.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance"),t.setAttribute("xsi:schemaLocation","http://www.pixinsight.com/xisf http://pixinsight.com/xisf/xisf-1.0.xsd"),e}var So=/^(url|path)\((.*)\)(?::(.*))?$/;function wo(e){if(!e)return;let t=e.trim();if(t.length!==0)return t.startsWith("0x")||t.startsWith("0X"),BigInt(t)}function Zt(e){let t=e.trim();if(t.startsWith("inline:")){let n=t.slice(7);if(n!=="base64"&&n!=="hex")throw new B(`Unsupported inline encoding: ${n}`);return {type:"inline",encoding:n}}if(t==="embedded")return {type:"embedded"};if(t.startsWith("attachment:")||t.startsWith("attached:")){let i=(t.startsWith("attached:")?`attachment:${t.slice(9)}`:t).split(":");if(i.length!==3)throw new B(`Invalid attachment location: ${e}`);let o=Number(i[1]),s=Number(i[2]);if(!Number.isInteger(o)||!Number.isInteger(s)||o<0||s<0)throw new B(`Invalid attachment numbers: ${e}`);return {type:"attachment",position:o,size:s}}let r=So.exec(t);if(r){let n=r[1],i=r[2],o=wo(r[3]);return n==="url"?{type:"url",url:i,indexId:o}:{type:"path",path:i,indexId:o}}throw new B(`Unsupported location syntax: ${e}`)}function qt(e){return e.trim()?e.split(":").map(t=>{let r=t.split(",");if(r.length!==2)throw new B(`Invalid subblocks entry: ${t}`);let n=Number(r[0]),i=Number(r[1]);if(!Number.isInteger(n)||!Number.isInteger(i)||n<0||i<0)throw new B(`Invalid subblocks values: ${t}`);return {compressedSize:n,uncompressedSize:i}}):[]}function bn(e){let t=e.indexOf(":");if(t<=0)throw new B(`Invalid checksum format: ${e}`);return {algorithm:e.slice(0,t).toLowerCase(),digest:e.slice(t+1).toLowerCase()}}function Jt(e){let t=e.split(":");if(t.length<2||t.length>3)throw new B(`Invalid compression format: ${e}`);let r=t[0].toLowerCase(),n=Number(t[1]);if(!Number.isInteger(n)||n<0)throw new B(`Invalid uncompressed size: ${e}`);if(t.length===3){let i=Number(t[2]);if(!Number.isInteger(i)||i<=0)throw new B(`Invalid shuffle item size: ${e}`);return {codec:r,uncompressedSize:n,itemSize:i}}return {codec:r,uncompressedSize:n}}function yn(e,t){if(e.startsWith("@header_dir/")){if(!t)throw new F("Path uses @header_dir but no headerDir was provided");let r=e.slice(12);return /^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//.test(t)?new URL(r,`${t.replace(/\/?$/,"/")}`).toString():`${t.replace(/\\/g,"/").replace(/\/$/,"")}/${r}`}return e}var Io={Boolean:"Boolean",Int8:"Int8",UInt8:"UInt8",Byte:"UInt8",Int16:"Int16",UInt16:"UInt16",Short:"Int16",UShort:"UInt16",Int32:"Int32",UInt32:"UInt32",Int:"Int32",UInt:"UInt32",Int64:"Int64",UInt64:"UInt64",Float32:"Float32",Float:"Float32",Float64:"Float64",Double:"Float64",Complex32:"Complex32",Complex64:"Complex64",String:"String",TimePoint:"TimePoint"},wn={I8Vector:"Int8",UI8Vector:"UInt8",ByteArray:"UInt8",I16Vector:"Int16",UI16Vector:"UInt16",I32Vector:"Int32",UI32Vector:"UInt32",I64Vector:"Int64",UI64Vector:"UInt64",IVector:"Int32",UIVector:"UInt32",F32Vector:"Float32",F64Vector:"Float64",Vector:"Float64",C32Vector:"Complex32",C64Vector:"Complex64"},Ao={I8Matrix:"Int8",UI8Matrix:"UInt8",ByteMatrix:"UInt8",I16Matrix:"Int16",UI16Matrix:"UInt16",I32Matrix:"Int32",UI32Matrix:"UInt32",I64Matrix:"Int64",UI64Matrix:"UInt64",IMatrix:"Int32",UIMatrix:"UInt32",F32Matrix:"Float32",F64Matrix:"Float64",Matrix:"Float64",C32Matrix:"Complex32",C64Matrix:"Complex64"};function Qt(e){return Io[e]}function xo(e){let t=e.toLowerCase();return t==="true"||t==="1"}function Fo(e){let t=e.trim().replace(",",":"),r=t.indexOf(":");return r>0?{real:Number.parseFloat(t.slice(0,r)),imag:Number.parseFloat(t.slice(r+1))}:{real:Number.parseFloat(t),imag:0}}function Sn(e,t){switch(Qt(e)??e){case "Boolean":return xo(t);case "Int8":case "Int16":case "Int32":return Number.parseInt(t,10);case "UInt8":case "UInt16":case "UInt32":return Number.parseInt(t,10);case "Int64":case "UInt64":return BigInt(t);case "Float32":case "Float64":return Number.parseFloat(t);case "Complex32":case "Complex64":return Fo(t);default:return t}}function Eo(e){return e.byteOrder==="big"?"big":"little"}function In(e){switch(e){case "Boolean":case "Int8":case "UInt8":return 1;case "Int16":case "UInt16":return 2;case "Int32":case "UInt32":case "Float32":return 4;case "Int64":case "UInt64":case "Float64":return 8;case "Complex32":return 8;case "Complex64":return 16;case "String":case "TimePoint":return 1}}function To(e,t,r){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=r==="little";if(t.byteLength<In(e))throw new F("Property data block is shorter than required for scalar type");switch(e){case "Boolean":return n.getUint8(0)!==0;case "Int8":return n.getInt8(0);case "UInt8":return n.getUint8(0);case "Int16":return n.getInt16(0,i);case "UInt16":return n.getUint16(0,i);case "Int32":return n.getInt32(0,i);case "UInt32":return n.getUint32(0,i);case "Int64":return n.getBigInt64(0,i);case "UInt64":return n.getBigUint64(0,i);case "Float32":return n.getFloat32(0,i);case "Float64":return n.getFloat64(0,i);case "Complex32":return {real:n.getFloat32(0,i),imag:n.getFloat32(4,i)};case "Complex64":return {real:n.getFloat64(0,i),imag:n.getFloat64(8,i)};case "String":case "TimePoint":return new TextDecoder("utf-8").decode(t)}}function er(e,t,r,n){let i=r==="little",o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=In(e),c=n??Math.floor(t.byteLength/s);switch(e){case "Int8":{let a=new Int8Array(c);for(let u=0;u<c;u++)a[u]=o.getInt8(u);return a}case "UInt8":case "Boolean":{let a=new Uint8Array(c);for(let u=0;u<c;u++)a[u]=o.getUint8(u);return a}case "Int16":{let a=new Int16Array(c);for(let u=0;u<c;u++)a[u]=o.getInt16(u*2,i);return a}case "UInt16":{let a=new Uint16Array(c);for(let u=0;u<c;u++)a[u]=o.getUint16(u*2,i);return a}case "Int32":{let a=new Int32Array(c);for(let u=0;u<c;u++)a[u]=o.getInt32(u*4,i);return a}case "UInt32":{let a=new Uint32Array(c);for(let u=0;u<c;u++)a[u]=o.getUint32(u*4,i);return a}case "Int64":{let a=new BigInt64Array(c);for(let u=0;u<c;u++)a[u]=o.getBigInt64(u*8,i);return a}case "UInt64":{let a=new BigUint64Array(c);for(let u=0;u<c;u++)a[u]=o.getBigUint64(u*8,i);return a}case "Float32":{let a=new Float32Array(c);for(let u=0;u<c;u++)a[u]=o.getFloat32(u*4,i);return a}case "Float64":{let a=new Float64Array(c);for(let u=0;u<c;u++)a[u]=o.getFloat64(u*8,i);return a}case "Complex32":{let a=new Float32Array(c*2);for(let u=0;u<c;u++)a[u*2]=o.getFloat32(u*8,i),a[u*2+1]=o.getFloat32(u*8+4,i);return a}case "Complex64":{let a=new Float64Array(c*2);for(let u=0;u<c;u++)a[u*2]=o.getFloat64(u*16,i),a[u*2+1]=o.getFloat64(u*16+8,i);return a}case "String":case "TimePoint":return new Uint8Array(t)}}function mt(e){let t=e.getAttribute("location");if(!t)return;let r=Zt(t),n=e.getAttribute("checksum"),i=e.getAttribute("compression"),o=e.getAttribute("byteOrder"),s=e.getAttribute("subblocks"),c={location:r,byteOrder:o==="big"?"big":o==="little"?"little":void 0};if(n){let a=bn(n);c.checksum={algorithm:a.algorithm,digest:a.digest};}if(i){let a=Jt(i);c.compression={codec:a.codec,uncompressedSize:a.uncompressedSize,itemSize:a.itemSize,subblocks:s?qt(s):void 0};}if(r.type==="inline")c.inlineData=(e.textContent??"").trim();else if(r.type==="embedded"){let a=et(e,"Data");if(a){let u=a.getAttribute("encoding");if((u==="base64"||u==="hex")&&(r.encoding=u),c.embeddedData=(a.textContent??"").trim(),!c.compression){let f=a.getAttribute("compression");if(f){let l=Jt(f);c.compression={codec:l.codec,uncompressedSize:l.uncompressedSize,itemSize:l.itemSize,subblocks:a.getAttribute("subblocks")?qt(a.getAttribute("subblocks")):void 0};}}}}return c}function Po(e,t,r){let n=wn[e];return n?er(n,t,"little",r):new Uint8Array(t)}async function Fe(e,t,r){let n=r?.strictValidation??true,i=e.getAttribute("id")??r?.defaultId??"",o=e.getAttribute("type")??r?.defaultType??"",s=e.getAttribute("format")??r?.defaultFormat??void 0,c=e.getAttribute("comment")??void 0;if(n&&!o)throw new F(`Property '${i||"<unnamed>"}' is missing type`);let a={id:i,type:o,format:s,comment:c},u=e.hasAttribute("value")?e.getAttribute("value"):null;if(u!==null)return a.value=Sn(o,u),a;let f=e.getAttribute("length"),l=e.getAttribute("rows"),m=e.getAttribute("columns");if(f&&(a.length=Number(f)),l&&(a.rows=Number(l)),m&&(a.columns=Number(m)),n&&a.length!==void 0&&(!Number.isInteger(a.length)||a.length<0))throw new F(`Invalid property length '${f}' for '${i||"<unnamed>"}'`);if(n&&a.rows!==void 0&&(!Number.isInteger(a.rows)||a.rows<0))throw new F(`Invalid property rows '${l}' for '${i||"<unnamed>"}'`);if(n&&a.columns!==void 0&&(!Number.isInteger(a.columns)||a.columns<0))throw new F(`Invalid property columns '${m}' for '${i||"<unnamed>"}'`);let d=mt(e);if(!d)return o==="String"||o==="TimePoint"?a.value=e.textContent??"":Qt(o)&&(e.textContent??"").trim().length>0&&(a.value=Sn(o,(e.textContent??"").trim())),a;a.dataBlock=d;let p=await t(e,d),h=Eo(d);if(o==="String")return a.value=new TextDecoder("utf-8").decode(p),a;if(o==="TimePoint")return a.value=new TextDecoder("utf-8").decode(p),a;let b=Qt(o);if(b&&b!=="String"&&b!=="TimePoint")return a.value=To(b,p,h),a;if(o.endsWith("Vector")||o==="ByteArray"||o==="IVector"||o==="UIVector"||o==="Vector"){let g=wn[o];return g?(a.value=er(g,p,h,a.length),a):(a.value=Po(o,p,a.length),a)}if(o.endsWith("Matrix")){let g=a.rows??0,y=a.columns??0,w=Ao[o];if(!w)return a.value=p,a;let S=g>0&&y>0?g*y:void 0,I=er(w,p,h,S),A=Array.from(I),x=[];for(let E=0;E<g;E++)x.push(A.slice(E*y,(E+1)*y));return a.value={rows:g,columns:y,values:x},a}return a.value=p,a}function Ro(e){return {id:e.getAttribute("id")??"",type:e.getAttribute("type")??"",format:e.getAttribute("format")??void 0,header:e.getAttribute("header")??void 0}}function Co(e,t){let r=e.cloneNode(true);return t?.id&&!r.getAttribute("id")&&r.setAttribute("id",t.id),t?.type&&!r.getAttribute("type")&&r.setAttribute("type",t.type),t?.format&&!r.getAttribute("format")&&r.setAttribute("format",t.format),r}async function Uo(e,t,r,n){let i=te(e,"Cell");return {cells:await Promise.all(i.map((s,c)=>{let a=t[c],u=Co(s,a);return Fe(u,r,{...n,defaultType:a?.type,defaultId:a?.id,defaultFormat:a?.format})}))}}async function dt(e,t,r,n){let i=n?.strictValidation??true,o=e.getAttribute("id")??"",s=e.getAttribute("caption")??void 0,c=e.getAttribute("rows")?Number(e.getAttribute("rows")):void 0,a=e.getAttribute("columns")?Number(e.getAttribute("columns")):void 0,u=e.getAttribute("comment")??void 0;if(i&&c!==void 0&&(!Number.isInteger(c)||c<0))throw new F(`Table '${o||"<unnamed>"}' has invalid rows value`);if(i&&a!==void 0&&(!Number.isInteger(a)||a<0))throw new F(`Table '${o||"<unnamed>"}' has invalid columns value`);let f=et(e,"Structure");if(!f){let p=et(e,"Reference");if(p){let h=p.getAttribute("ref");if(h){let b=t(h);if(b&&b.tagName.toLowerCase().endsWith("structure"))f=b;else if(i)throw new F(`Table '${o||"<unnamed>"}' has invalid Structure reference '${h}'`)}}}let l=f?te(f,"Field").map(Ro):[],m=te(e,"Row"),d=await Promise.all(m.map(p=>Uo(p,l,r,{strictValidation:i})));if(i&&c!==void 0&&c!==d.length)throw new F(`Table '${o||"<unnamed>"}' row count mismatch`);if(i&&a!==void 0){for(let p of d)if(p.cells.length!==a)throw new F(`Table '${o||"<unnamed>"}' column count mismatch`)}if(i&&l.length>0){for(let p of d)if(p.cells.length!==l.length)throw new F(`Table '${o||"<unnamed>"}' field/cell count mismatch`)}return {id:o,caption:s,rows:c,columns:a,comment:u,structure:l,dataRows:d}}var No=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),Bo=new Set(["Gray","RGB","CIELab"]),vo=new Set(["Planar","Normal"]),ko=new Set(["0","flip","90","90;flip","-90","-90;flip","180","180;flip"]),Lo=/^[0RGBWCMY]+$/;function ue(e){return e.split(":").map(t=>Number(t.trim()))}function Do(e){let t=ue(e);if(t.length<2)throw new F(`Invalid geometry: ${e}`);if(t.some(i=>!Number.isFinite(i)||!Number.isInteger(i)||i<=0))throw new F(`Geometry values must be positive integers: ${e}`);let r=t[t.length-1];return {dimensions:t.slice(0,-1),channels:r}}function Oo(e){if(!e)return;let[t,r]=ue(e);if(!(t===void 0||r===void 0))return [t,r]}function Mo(e){let t=e.getAttribute("gamma")??"sRGB",r=ue(e.getAttribute("x")??"0:0:0"),n=ue(e.getAttribute("y")??"0:0:0"),i=ue(e.getAttribute("Y")??"0:0:0");return {gamma:t,x:r,y:n,Y:i,name:e.getAttribute("name")??void 0}}function Xo(e){return {m:ue(e.getAttribute("m")??"0.5:0.5:0.5:0.5"),s:ue(e.getAttribute("s")??"0:0:0:0"),h:ue(e.getAttribute("h")??"1:1:1:1"),l:ue(e.getAttribute("l")??"0:0:0:0"),r:ue(e.getAttribute("r")??"1:1:1:1"),name:e.getAttribute("name")??void 0}}function _o(e,t){let r=Number(e.getAttribute("width")??"0"),n=Number(e.getAttribute("height")??"0"),i=e.getAttribute("pattern")??"";if(t&&(r<=0||n<=0||!Number.isInteger(r)||!Number.isInteger(n)))throw new F("ColorFilterArray width/height must be positive integers");if(t&&!Lo.test(i))throw new F("ColorFilterArray pattern contains invalid symbols");if(t&&i.length!==r*n)throw new F("ColorFilterArray pattern length must equal width*height");return {pattern:i,width:r,height:n,name:e.getAttribute("name")??void 0}}function Ho(e,t){let r=e.getAttribute("unit"),n=Number(e.getAttribute("horizontal")??"72"),i=Number(e.getAttribute("vertical")??"72");if(t&&(!Number.isFinite(n)||!Number.isFinite(i)||n<=0||i<=0))throw new F("Resolution horizontal/vertical must be positive numbers");return {horizontal:n,vertical:i,unit:r==="cm"?"cm":"inch"}}function $o(e){return {name:e.getAttribute("name")??"",value:e.getAttribute("value")??"",comment:e.getAttribute("comment")??""}}async function tr(e,t,r,n,i=true,o=false){let s=e.getAttribute("geometry");if(!s)throw new F("Image element is missing geometry");let c=e.getAttribute("sampleFormat");if(!c)throw new F("Image element is missing sampleFormat");if(!No.has(c))throw new F(`Unsupported image sampleFormat: ${c}`);let{dimensions:a,channels:u}=Do(s),f=mt(e);if(!f)throw new F("Image element is missing location/data block");if(i&&f.location.type==="inline")throw new F("Image element cannot use inline location");let l=e.getAttribute("pixelStorage")||"Planar";if(!vo.has(l))throw new F(`Unsupported pixelStorage: ${l}`);let m=e.getAttribute("colorSpace")||"Gray";if(!Bo.has(m))throw new F(`Unsupported colorSpace: ${m}`);if(i&&(c==="Float32"||c==="Float64")&&!e.getAttribute("bounds"))throw new F("bounds is required for Float32/Float64 images");let d=e.getAttribute("orientation")??void 0;if(d&&!ko.has(d))throw new F(`Unsupported orientation: ${d}`);let p=e.getAttribute("offset"),h=p?Number(p):void 0;if(h!==void 0&&(!Number.isFinite(h)||h<0))throw new F("offset must be a non-negative number");let b=Oo(e.getAttribute("bounds"));if(b&&(!Number.isFinite(b[0])||!Number.isFinite(b[1])||b[0]>=b[1]))throw new F("bounds must contain two finite numbers with lower < upper");if(o&&e.getAttribute("bounds"))throw new F("Thumbnail must not define bounds");if(o&&!["UInt8","UInt16"].includes(c))throw new F("Thumbnail sampleFormat must be UInt8 or UInt16");if(o&&!["Gray","RGB"].includes(m))throw new F("Thumbnail colorSpace must be Gray or RGB");if(o&&a.length!==2)throw new F("Thumbnail must be two-dimensional");let g={id:e.getAttribute("id")??void 0,uuid:e.getAttribute("uuid")??void 0,geometry:a,channelCount:u,sampleFormat:c,bounds:b,imageType:e.getAttribute("imageType")??void 0,pixelStorage:l,colorSpace:m,offset:h,orientation:d,dataBlock:f,properties:[],tables:[],fitsKeywords:[]};n&&(g.data=await r(e,f));let y=te(e,"Reference"),w=I=>{let A=[],x=I.childNodes;for(let E=0;E<x.length;E++){let L=x.item(E);L&&L.nodeType===1&&A.push(L);}return A},S=[];for(let I of w(e)){if(xe(I)==="Reference"){let A=I.getAttribute("ref");if(A){let x=t(A);if(x){if(i&&xe(x)==="Reference")throw new F(`Chained references are not allowed (${A})`);S.push(x);}}continue}S.push(I);}for(let I of y){let A=I.getAttribute("ref");if(!A)continue;let x=t(A);if(i&&x&&xe(x)==="Reference")throw new F(`Chained references are not allowed (${A})`);x&&!S.includes(x)&&S.push(x);}for(let I of S)switch(xe(I)){case "Property":g.properties.push(await Fe(I,r,{strictValidation:i}));break;case "Table":g.tables.push(await dt(I,t,r,{strictValidation:i}));break;case "FITSKeyword":g.fitsKeywords.push($o(I));break;case "ICCProfile":{if(i&&I.hasAttribute("byteOrder"))throw new F("ICCProfile must not define byteOrder");let x=mt(I);x&&(g.iccProfile=await r(I,x));break}case "RGBWorkingSpace":g.rgbWorkingSpace=Mo(I);break;case "DisplayFunction":g.displayFunction=Xo(I);break;case "ColorFilterArray":if(o)throw new F("Thumbnail must not contain ColorFilterArray");g.colorFilterArray=_o(I,i);break;case "Resolution":g.resolution=Ho(I,i);break;case "Thumbnail":if(o)throw new F("Nested Thumbnail elements are not allowed");g.thumbnail=await tr(I,t,r,n,i,true);break;}return g}var Le="+sh",Ko=new Set([0,1,2,3,4,5,6,7,8,9]),rr=new Set(["lz4","lz4hc"]),nr=new Set(["zstd"]);function Yo(e){let t=e.byteLength,r=t>=15?Math.floor((t-15)/255)+1:0,n=new Uint8Array(1+r+t);n[0]=Math.min(15,t)<<4;let i=1;if(t>=15){let o=t-15;for(;o>=255;)n[i++]=255,o-=255;n[i++]=o;}return n.set(e,i),n}function Zo(e){let t=new Uint8Array(lz4js.compressBound(e.byteLength)),r=new Uint32Array(65536),n=lz4js.compressBlock(e,t,0,e.byteLength,r);return n>0?t.slice(0,n):Yo(e)}function qo(e,t){if(!t||t<=0)throw new K("LZ4 codecs require uncompressedSize in XISF compression spec");let r=new Uint8Array(t),n=lz4js.decompressBlock(e,r,0,e.byteLength,0),i=typeof n=="number"?n:r.byteLength;if(i!==r.byteLength)throw new K(`Decoded LZ4 block length mismatch: expected ${r.byteLength}, got ${i}`);return r}var pt={supports(e){let t=e.toLowerCase(),r=t.endsWith(Le)?t.slice(0,-Le.length):t;return r==="zlib"||rr.has(r)||nr.has(r)},compress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new K(`Unsupported codec in default provider: ${e}`);if(rr.has(n))return Zo(t);if(nr.has(n))throw new K("Default provider supports zstd decompression only; provide a custom codecProvider for zstd encoding");let i=r!==void 0&&Ko.has(r)?r:void 0;return fflate.zlibSync(t,{level:i})},decompress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new K(`Unsupported codec in default provider: ${e}`);if(rr.has(n))return qo(t,r);if(nr.has(n)){let i=r&&r>0?new Uint8Array(r):void 0,o=i?fzstd.decompress(t,i):fzstd.decompress(t);if(i&&o.byteLength!==i.byteLength)throw new K(`Decoded zstd block length mismatch: expected ${i.byteLength}, got ${o.byteLength}`);return o}return fflate.unzlibSync(t)}};function Jo(e,t){if(t<=1||e.byteLength===0)return e.slice();let r=Math.floor(e.byteLength/t),n=e.byteLength%t,i=new Uint8Array(e.byteLength),o=0;for(let s=0;s<t;s++)for(let c=0;c<r;c++)i[o++]=e[c*t+s];return n>0&&i.set(e.slice(r*t),o),i}function Qo(e,t){if(t<=1||e.byteLength===0)return e.slice();let r=Math.floor(e.byteLength/t),n=e.byteLength%t,i=new Uint8Array(e.byteLength),o=0;for(let s=0;s<t;s++)for(let c=0;c<r;c++)i[c*t+s]=e[o++];return n>0&&i.set(e.slice(o),r*t),i}function es(e,t){let r=[],n=0;for(let i of t){let o=n+i.compressedSize;if(o>e.byteLength)throw new K("Compressed subblocks exceed block length");r.push(e.slice(n,o)),n=o;}if(n!==e.byteLength)throw new K("Compressed subblocks length mismatch");return r}function xn(e,t,r){let n=t.codec.toLowerCase(),i=n.endsWith(Le),o=i?n.slice(0,-Le.length):n,s=f=>{let l=r.decompress(o,f,t.uncompressedSize);if(!i)return l;if(!t.itemSize||t.itemSize<=0)throw new K(`Shuffle codec ${n} requires itemSize`);return Qo(l,t.itemSize)};if(!t.subblocks||t.subblocks.length===0)return s(e);let c=es(e,t.subblocks),a=new Uint8Array(t.uncompressedSize),u=0;for(let f=0;f<c.length;f++){let l=s(c[f]),m=t.subblocks[f].uncompressedSize;if(l.byteLength!==m)throw new K("Decoded subblock size mismatch");a.set(l,u),u+=l.byteLength;}if(u!==t.uncompressedSize)throw new K("Decoded uncompressed size mismatch");return a}function Fn(e,t,r,n,i){let o=t.toLowerCase(),s=o.endsWith(Le),c=s?o.slice(0,-Le.length):o,a=s?Jo(e,i??1):e;return {data:r.compress(c,a,n),spec:{codec:o,uncompressedSize:e.byteLength,itemSize:s?i??1:void 0}}}function ts(e){return import(e)}function rs(){return typeof process<"u"&&typeof process=="object"}function En(){return typeof navigator<"u"&&navigator.product==="ReactNative"}function De(){if(!rs()||En())return false;let e=process.versions;return typeof e?.node=="string"&&e.node.length>0}function ir(){return De()?"node":En()?"react-native":typeof window<"u"?"browser":"unknown"}async function W(e,t,r){if(!De()){let i=r?` ${r}`:"";throw new Error(`${t} requires Node.js runtime. Current runtime: ${ir()}.${i}`)}let n=e.startsWith("node:")?e:`node:${e}`;try{return await ts(n)}catch(i){throw new Error(`${t} failed to load ${n}: ${i.message}`)}}function ns(e){return new Uint8Array(e)}async function is(e){try{let r=await(await W("fs/promises","XISF path(...) resource resolution","Provide a custom resourceResolver.resolvePath in browser/React Native.")).readFile(e);return new Uint8Array(r)}catch(t){throw new ce(`Failed to read path "${e}": ${t.message}`)}}var Tn={async resolveURL(e){let t=await fetch(e);if(!t.ok)throw new ce(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);return ns(await t.arrayBuffer())},async resolvePath(e){if(!De())throw new ce(`Path-based distributed XISF access requires Node.js or a custom resourceResolver.resolvePath (runtime=${ir()}): ${e}`);return is(e)}};var Pn="XISB0100";function os(e){return new TextDecoder("ascii").decode(e)}function or(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new F(`${t} exceeds Number.MAX_SAFE_INTEGER`);return Number(e)}function Rn(e){let t=new Uint8Array(e);if(t.byteLength<16)throw new B("Invalid XISB file: too short");let r=os(t.slice(0,8));if(r!==Pn)throw new B(`Invalid XISB signature: ${r}`);let n=new DataView(e),i=[],o=16,s=new Set;for(;o!==0;){if(s.has(o))throw new B("Invalid XISB index: cyclic block index list");if(s.add(o),o+16>t.byteLength)throw new B("Invalid XISB index node offset");let a=n.getUint32(o,true),u=n.getBigUint64(o+8,true),f=o+16;for(let l=0;l<a;l++){if(f+40>t.byteLength)throw new B("Invalid XISB index element offset");let m=n.getBigUint64(f,true),d=n.getBigUint64(f+8,true),p=n.getBigUint64(f+16,true),h=n.getBigUint64(f+24,true);i.push({uniqueId:m,blockPosition:d,blockLength:p,uncompressedBlockLength:h}),f+=40;}o=or(u,"nextNode");}let c=new Map;for(let a of i)c.set(a.uniqueId,a);return {elements:i,byId:c}}function Cn(e,t){if(t.blockPosition===BigInt(0)||t.blockLength===BigInt(0))throw new F("Cannot read free XISB index element");let r=or(t.blockPosition,"blockPosition"),n=or(t.blockLength,"blockLength"),i=new Uint8Array(e);if(r+n>i.byteLength)throw new B("XISB block out of bounds");return i.slice(r,r+n)}function Un(e){let t=e.map((m,d)=>BigInt(d+1)),r=16,n=16,i=40,o=n+e.length*i,s=r+o,c=e.map((m,d)=>{let p=BigInt(s);return s+=m.byteLength,{uniqueId:t[d],blockPosition:p,blockLength:BigInt(m.byteLength),uncompressedBlockLength:BigInt(0)}}),a=s,u=new Uint8Array(a);u.set(new TextEncoder().encode(Pn),0);let f=new DataView(u.buffer),l=r;f.setUint32(l,c.length,true),f.setUint32(l+4,0,true),f.setBigUint64(l+8,BigInt(0),true),l+=n;for(let m of c)f.setBigUint64(l,m.uniqueId,true),f.setBigUint64(l+8,m.blockPosition,true),f.setBigUint64(l+16,m.blockLength,true),f.setBigUint64(l+24,m.uncompressedBlockLength,true),f.setBigUint64(l+32,BigInt(0),true),l+=i;for(let m=0;m<e.length;m++){let d=e[m],p=Number(c[m].blockPosition);u.set(d,p);}return {bytes:u,ids:t}}var ss=Nn__default.default.sha3_256,as=Nn__default.default.sha3_512;function cs(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++)r+=t[n].toString(16).padStart(2,"0");return r}async function sr(e,t){if(typeof crypto<"u"&&crypto.subtle){let i=new Uint8Array(t.byteLength);i.set(t);let o=await crypto.subtle.digest(e,i);return cs(o)}let n=(await W("crypto",`XISF checksum ${e} without WebCrypto`,"Enable WebCrypto or run in Node.js for checksum verification.")).createHash(e.toLowerCase().replace("-",""));return n.update(t),n.digest("hex")}async function ar(e,t){switch(t.toLowerCase()){case "sha1":case "sha-1":return sr("SHA-1",e);case "sha256":case "sha-256":return sr("SHA-256",e);case "sha512":case "sha-512":return sr("SHA-512",e);case "sha3-256":return ss(e);case "sha3-512":return as(e);default:throw new ge(`Unsupported checksum algorithm: ${t}`)}}async function Bn(e,t){return (await ar(e,t.algorithm)).toLowerCase()===t.digest.toLowerCase()}var Oe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",cr=new Int16Array(128).fill(-1);for(let e=0;e<Oe.length;e++)cr[Oe.charCodeAt(e)]=e;function us(e){let t="";for(let n=0;n<e.length;n+=32768){let i=e.subarray(n,Math.min(n+32768,e.length));t+=String.fromCharCode(...i);}return t}function ls(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t}function ht(e){return e<0||e>=cr.length?-1:cr[e]??-1}function gt(e){let t=e.replace(/\s+/gu,"").replace(/-/gu,"+").replace(/_/gu,"/"),r=t.length%4;return r!==0&&(t=t.padEnd(t.length+(4-r),"=")),t}function fs(e){let t="";for(let r=0;r<e.length;r+=3){let n=e[r],i=r+1<e.length?e[r+1]:0,o=r+2<e.length?e[r+2]:0,s=n<<16|i<<8|o;t+=Oe[s>>18&63],t+=Oe[s>>12&63],t+=r+1<e.length?Oe[s>>6&63]:"=",t+=r+2<e.length?Oe[s&63]:"=";}return t}function ms(e){let t=gt(e);if(t.length%4!==0)throw new Error("Invalid base64 payload length");let r=t.endsWith("==")?2:t.endsWith("=")?1:0,n=new Uint8Array(t.length/4*3-r),i=0;for(let o=0;o<t.length;o+=4){let s=t.charCodeAt(o),c=t.charCodeAt(o+1),a=t.charCodeAt(o+2),u=t.charCodeAt(o+3),f=s<128?ht(s):-1,l=c<128?ht(c):-1,m=a===61?-2:a<128?ht(a):-1,d=u===61?-2:u<128?ht(u):-1;if(f<0||l<0||m===-1||d===-1)throw new Error("Invalid base64 payload characters");let p=m<0?0:m,h=d<0?0:d,b=f<<18|l<<12|p<<6|h;n[i++]=b>>16&255,m>=0&&(n[i++]=b>>8&255),d>=0&&(n[i++]=b&255);}return n}function Me(e){return typeof btoa=="function"?btoa(us(e)):fs(e)}function Ee(e){let t=gt(e);return typeof atob=="function"?ls(atob(t)):ms(t)}var M="http://www.w3.org/2000/09/xmldsig#",dr="http://www.w3.org/TR/2001/REC-xml-c14n-20010315",ds="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments",ps="http://www.w3.org/2006/12/xml-c14n11",hs="http://www.w3.org/2006/12/xml-c14n11#WithComments",gs="http://www.w3.org/2001/10/xml-exc-c14n#",bs="http://www.w3.org/2001/10/xml-exc-c14n#WithComments",ys="http://www.w3.org/2000/09/xmldsig#enveloped-signature",Ss="http://www.w3.org/2000/09/xmldsig#base64";function Xe(e){let t=e.localName;if(t&&t.length>0)return t;let r=e.nodeName,n=r.indexOf(":");return n>=0?r.slice(n+1):r}function tt(e){return !!e&&e.nodeType===1}function ws(e){return !!e&&e.nodeType===8}function Is(e){return !!e&&(e.nodeType===3||e.nodeType===4)}function pr(e,t,r){let n=[];for(let i=0;i<e.childNodes.length;i++){let o=e.childNodes.item(i);tt(o)&&Xe(o)===t&&((o.namespaceURI??"")!==r||n.push(o));}return n}function V(e,t,r){let n=pr(e,t,r);return n.length>0?n[0]:null}function Dn(e){let t=e.documentElement;if(!t)return null;for(let r=0;r<t.childNodes.length;r++){let n=t.childNodes.item(r);if(tt(n)&&Xe(n)==="Signature"&&(n.namespaceURI??"")===M)return n}return null}function On(e){return Dn(e)!==null}function As(e){return gt(e)}function bt(e){return Me(e).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/gu,"")}async function be(e){return Ee(As(e))}function lr(e){return new TextEncoder().encode(e)}function fr(e){if(e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer)return e.buffer;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function xs(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll("\r","&#xD;")}function ur(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll('"',"&quot;").replaceAll(" ","&#x9;").replaceAll(`
3
+ `,"&#xA;").replaceAll("\r","&#xD;")}function vn(e){let t=e.prefix,r=Xe(e);return t?`${t}:${r}`:r}function Fs(e){let t=new Map;for(let r=0;r<e.attributes.length;r++){let n=e.attributes.item(r);n&&(n.name==="xmlns"?t.set("",n.value):n.name.startsWith("xmlns:")&&t.set(n.name.slice(6),n.value));}return t}function Es(e){return new Map(e.entries())}function Ts(e){let t=e.cloneNode(true),r=n=>{for(let i=n.childNodes.length-1;i>=0;i--){let o=n.childNodes.item(i);if(o){if(tt(o)&&Xe(o)==="Signature"&&(o.namespaceURI??"")===M){n.removeChild(o);continue}r(o);}}};return r(t),t}function hr(e){switch(e){case dr:case ps:return {withComments:false,exclusive:false};case ds:case hs:return {withComments:true,exclusive:false};case gs:return {withComments:false,exclusive:true};case bs:return {withComments:true,exclusive:true};default:return null}}function Ps(e){return e.prefix??""}function kn(e){let t=e.prefix;return !t||t==="xmlns"?"":t}function Rs(e,t,r){let n=Ps(e),i=e.namespaceURI??"",o=Fs(e),s=Es(t);for(let[p,h]of o.entries())s.set(p,h);let c=new Map;if(r.exclusive){let p=new Set;p.add(n);for(let h=0;h<e.attributes.length;h++){let b=e.attributes.item(h);if(!b||b.name==="xmlns"||b.name.startsWith("xmlns:"))continue;let g=kn(b);g&&p.add(g);}for(let h of p){let b=t.get(h)??"",g=h===n?i:s.get(h)??"";g!==b&&c.set(h,g);}}else {for(let[h,b]of o.entries()){let g=t.get(h)??"";b!==g&&c.set(h,b);}let p=t.get("")??"";n===""&&i!==p&&c.set("",i);for(let h=0;h<e.attributes.length;h++){let b=e.attributes.item(h);if(!b||b.name==="xmlns"||b.name.startsWith("xmlns:"))continue;let g=kn(b);if(!g)continue;let y=t.get(g)??"",w=s.get(g)??"";w!==y&&c.set(g,w);}}let a=[...c.entries()].sort(([p],[h])=>p.localeCompare(h)).map(([p,h])=>p===""?` xmlns="${ur(h)}"`:` xmlns:${p}="${ur(h)}"`),u=[];for(let p=0;p<e.attributes.length;p++){let h=e.attributes.item(p);h&&(h.name==="xmlns"||h.name.startsWith("xmlns:")||u.push(h));}u.sort((p,h)=>{let b=p.namespaceURI??"",g=h.namespaceURI??"";return b===g?Xe(p).localeCompare(Xe(h)):b.localeCompare(g)});let f=u.map(p=>` ${p.name}="${ur(p.value)}"`).join(""),l=`<${vn(e)}${a.join("")}${f}>`,m="";for(let p=0;p<e.childNodes.length;p++){let h=e.childNodes.item(p);h&&(m+=gr(h,s,r));}let d=`</${vn(e)}>`;return `${l}${m}${d}`}function gr(e,t,r){if(e.nodeType===9){let n=e,i="";for(let o=0;o<n.childNodes.length;o++){let s=n.childNodes.item(o);s&&(i+=gr(s,t,r));}return i}if(tt(e))return Rs(e,t,r);if(Is(e))return xs(e.data);if(ws(e))return r.withComments?`<!--${e.data}-->`:"";if(e.nodeType===7){let n=e;return `<?${n.target}${n.data?` ${n.data}`:""}?>`}return ""}function mr(e,t){let r=hr(t);if(!r)throw new Error(`Unsupported canonicalization algorithm: ${t}`);return gr(e,new Map,r)}function Cs(e){let t=V(e,"Transforms",M);if(!t)return [];let r=[];for(let n of pr(t,"Transform",M)){let i=n.getAttribute("Algorithm");i&&r.push(i);}return r}function Us(e,t){let r=[e.documentElement];for(;r.length>0;){let n=r.pop();if(!n||!tt(n))continue;if((n.getAttribute("Id")??n.getAttribute("ID")??n.getAttribute("id")??n.getAttribute("xml:id")??n.getAttribute("uid"))===t)return n;for(let o=n.childNodes.length-1;o>=0;o--){let s=n.childNodes.item(o);s&&r.push(s);}}return null}function Ns(e,t){if(!t||t==="")return {kind:"node",node:e.documentElement};if(!t.startsWith("#"))throw new Error(`Unsupported detached reference URI: ${t}`);let r=decodeURIComponent(t.slice(1)),n=Us(e,r);if(!n)throw new Error(`Unable to resolve signature reference URI: ${t}`);return {kind:"node",node:n}}function ye(e){return (e.textContent??"").trim()}function Bs(e){switch(e){case "http://www.w3.org/2000/09/xmldsig#sha1":return "SHA-1";case "http://www.w3.org/2001/04/xmlenc#sha256":return "SHA-256";case "http://www.w3.org/2001/04/xmldsig-more#sha384":return "SHA-384";case "http://www.w3.org/2001/04/xmlenc#sha512":return "SHA-512";default:throw new Error(`Unsupported digest algorithm: ${e}`)}}async function vs(e,t){let r=Bs(e);if(typeof crypto<"u"&&crypto.subtle){let s=await crypto.subtle.digest(r,fr(t));return new Uint8Array(s)}let n=await W("crypto",`XISF signature digest ${r} without WebCrypto`,"Enable WebCrypto or run in Node.js for detached-signature verification."),i=r.toLowerCase().replace("-",""),o=n.createHash(i);return o.update(t),new Uint8Array(o.digest())}function ks(e){switch(e){case "http://www.w3.org/2000/09/xmldsig#rsa-sha1":return {name:e,kind:"rsa-pkcs1",hash:"SHA-1"};case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":return {name:e,kind:"rsa-pkcs1",hash:"SHA-256"};case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384":return {name:e,kind:"rsa-pkcs1",hash:"SHA-384"};case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512":return {name:e,kind:"rsa-pkcs1",hash:"SHA-512"};case "http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1":return {name:e,kind:"rsa-pss",hash:"SHA-256"};case "http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1":return {name:e,kind:"rsa-pss",hash:"SHA-384"};case "http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1":return {name:e,kind:"rsa-pss",hash:"SHA-512"};case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256":return {name:e,kind:"ecdsa",hash:"SHA-256"};case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384":return {name:e,kind:"ecdsa",hash:"SHA-384"};case "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512":return {name:e,kind:"ecdsa",hash:"SHA-512"};default:throw new Error(`Unsupported signature method: ${e}`)}}function yt(e){let t=0;for(;t<e.length-1&&e[t]===0;)t++;return e.subarray(t)}async function Ls(e){let t=await W("crypto","XISF signature key loading from KeyInfo","Enable WebCrypto-compatible KeyInfo or run in Node.js for detached-signature verification."),r=V(e,"X509Data",M);if(r){let i=V(r,"X509Certificate",M);if(i){let o=await be(ye(i));return new t.X509Certificate(o).publicKey}}let n=V(e,"KeyValue",M);if(n){let i=V(n,"RSAKeyValue",M);if(i){let o=V(i,"Modulus",M),s=V(i,"Exponent",M);if(!o||!s)throw new Error("Invalid RSAKeyValue: missing Modulus/Exponent");let c=yt(await be(ye(o))),a=yt(await be(ye(s))),u={kty:"RSA",n:bt(c),e:bt(a)};return t.createPublicKey({key:u,format:"jwk"})}}throw new Error("Unsupported KeyInfo content")}async function Ds(e,t){if(t.kind==="ecdsa")throw new Error("ECDSA KeyInfo import is not yet supported without SPKI");let r=V(e,"KeyValue",M);if(!r)throw new Error("No RSA KeyValue in KeyInfo");let n=V(r,"RSAKeyValue",M);if(!n)throw new Error("Only RSAKeyValue is supported for WebCrypto verification");let i=V(n,"Modulus",M),o=V(n,"Exponent",M);if(!i||!o)throw new Error("Invalid RSAKeyValue: missing Modulus/Exponent");let s=yt(await be(ye(i))),c=yt(await be(ye(o))),a={kty:"RSA",n:bt(s),e:bt(c),ext:true},u=t.kind==="rsa-pss"?{name:"RSA-PSS",hash:t.hash}:{name:"RSASSA-PKCS1-v1_5",hash:t.hash};return crypto.subtle.importKey("jwk",a,u,false,["verify"])}async function Os(e,t){let r=V(e,"KeyInfo",M);if(!r)throw new Error("Missing ds:KeyInfo in signature");try{return {kind:"node",key:await Ls(r)}}catch(n){if(typeof crypto<"u"&&crypto.subtle)try{return {kind:"webcrypto",key:await Ds(r,t)}}catch(i){throw new Error(`Unable to load signature public key (node=${n.message}; web=${i.message})`)}throw n}}function Ms(e){return e.toLowerCase().replace("-","")}function Ln(e){switch(e){case "SHA-1":return 20;case "SHA-256":return 32;case "SHA-384":return 48;case "SHA-512":return 64}}async function Xs(e,t,r,n){if(n.kind==="node"){let o=await W("crypto",`XISF detached signature verification (${r.name})`,"Enable WebCrypto or run in Node.js for detached-signature verification."),s=o.createVerify(Ms(r.hash));return s.update(e),s.end(),r.kind==="rsa-pss"?s.verify({key:n.key,padding:o.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ln(r.hash)},t):s.verify(n.key,t)}let i;return r.kind==="rsa-pss"?i={name:"RSA-PSS",saltLength:Ln(r.hash)}:r.kind==="ecdsa"?i={name:"ECDSA",hash:r.hash}:i={name:"RSASSA-PKCS1-v1_5",hash:r.hash},crypto.subtle.verify(i,n.key,fr(t),fr(e))}async function _s(e,t){let r=t.getAttribute("URI"),n=Ns(e,r),i=Cs(t);for(let o of i){if(o===ys){if(n.kind!=="node")throw new Error("Enveloped-signature transform requires XML node input");n={kind:"node",node:Ts(n.node)};continue}if(o===Ss){let s=n.kind==="node"?ye(n.node):new TextDecoder("ascii").decode(n.bytes);n={kind:"bytes",bytes:await be(s)};continue}if(hr(o)){if(n.kind!=="node")throw new Error("Canonicalization transform requires XML node input");n={kind:"bytes",bytes:lr(mr(n.node,o))};continue}throw new Error(`Unsupported signature transform: ${o}`)}return n.kind==="bytes"?n.bytes:lr(mr(n.node,dr))}async function Hs(e,t){let r=pr(t,"Reference",M);if(r.length===0)throw new Error("SignedInfo has no Reference elements");for(let n of r){let i=n.getAttribute("URI")??"",o=V(n,"DigestMethod",M),s=V(n,"DigestValue",M);if(!o||!s)throw new Error(`Reference ${i} missing DigestMethod or DigestValue`);let c=o.getAttribute("Algorithm");if(!c)throw new Error(`Reference ${i} missing DigestMethod Algorithm`);let a=await be(ye(s)),u=await _s(e,n),f=await vs(c,u);if(a.length!==f.length)throw new Error(`Reference digest length mismatch for URI ${i}`);for(let l=0;l<a.length;l++)if(a[l]!==f[l])throw new Error(`Reference digest mismatch for URI ${i}`)}}function re(e,t){return {present:true,verified:false,algorithm:e,reason:t}}async function Mn(e){let t=Dn(e);if(!t)return {present:false,verified:true};let r=V(t,"SignedInfo",M);if(!r)return re(void 0,"Signature is missing SignedInfo");let n=V(r,"CanonicalizationMethod",M);if(!n)return re(void 0,"SignedInfo is missing CanonicalizationMethod");let i=n.getAttribute("Algorithm")??dr;if(!hr(i))return re(void 0,`Unsupported canonicalization algorithm: ${i}`);let o=V(r,"SignatureMethod",M);if(!o)return re(void 0,"SignedInfo is missing SignatureMethod");let s=o.getAttribute("Algorithm")??void 0;if(!s)return re(void 0,"SignatureMethod is missing Algorithm");let c=V(t,"SignatureValue",M);if(!c)return re(s,"SignatureValue is missing");let a;try{a=ks(s);}catch(d){return re(s,d.message)}try{await Hs(e,r);}catch(d){return re(s,`Digest verification failed: ${d.message}`)}let u=lr(mr(r,i)),f=await be(ye(c)),l;try{l=await Os(t,a);}catch(d){return re(s,`Key loading failed: ${d.message}`)}let m=false;try{m=await Xs(u,f,a,l);}catch(d){return re(s,`Signature verification failed: ${d.message}`)}return m?{present:true,verified:true,algorithm:a.name}:re(s,"SignatureValue does not match SignedInfo")}function $s(e){return {strictValidation:e?.strictValidation??true,verifyChecksums:e?.verifyChecksums??true,verifySignatures:e?.verifySignatures??true,signaturePolicy:e?.signaturePolicy??"require",decodeImageData:e?.decodeImageData??true,baseUrl:e?.baseUrl??"",headerDir:e?.headerDir??"",onWarning:e?.onWarning??(()=>{}),codecProvider:e?.codecProvider??pt,resourceResolver:e?.resourceResolver??Tn}}function Xn(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function _n(e,t){let r=t.replace(/\s+/g,"");let n=new Uint8Array(r.length/2);for(let i=0;i<n.length;i++)n[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return n}function Hn(e){return Ee(e)}function $n(e,t){e.onWarning(t);}function br(e,t,r){if(e.strictValidation)throw t;$n(e,{code:r,message:t.message});}async function Vs(e){if(e.location.type==="inline")return e.location.encoding==="base64"?Hn(e.inlineData??""):_n("hex",e.inlineData??"");if(e.location.type==="embedded")return (e.location.encoding??"base64")==="base64"?Hn(e.embeddedData??""):_n("hex",e.embeddedData??"");throw new B("decodeInlineOrEmbedded called on non-inline block")}var J=class e{unit;constructor(t){this.unit=t;}static async fromArrayBuffer(t,r){let n=$s(r);if(!n.verifySignatures&&n.signaturePolicy==="require")throw new ke("signaturePolicy=require requires verifySignatures=true");let i="",o;fn(t)?(i=mn(t).headerXml,o=t):i=new TextDecoder("utf-8").decode(new Uint8Array(t));let s=gn(i),c=On(s),a=s.documentElement,u=c&&n.verifySignatures&&n.signaturePolicy!=="ignore",f=new Map;for(let w=0;w<a.childNodes.length;w++){let S=a.childNodes.item(w);if(!S||S.nodeType!==1)continue;let I=S,A=I.getAttribute("uid");A&&f.set(A,I);}let l=w=>f.get(w)??null,m=async(w,S)=>{let I,A=S.location;if(A.type==="inline"||A.type==="embedded")I=await Vs(S);else if(A.type==="attachment"){if(!o)throw new ce("Attachment location found but no monolithic XISF payload exists");I=dn(o,A.position,A.size);}else I=await e.resolveExternalLocation(A,n);let x=A.type==="attachment"||A.type==="url"||A.type==="path";if(u&&x&&!S.checksum&&br(n,new ge(`Checksum is required for signed block in ${w.tagName}`),"checksum_required_for_signed_block"),S.checksum&&(n.verifyChecksums||u)&&(await Bn(I,S.checksum)||br(n,new ge(`Checksum mismatch for ${w.tagName}`),"checksum_mismatch")),S.compression)try{I=xn(I,S.compression,n.codecProvider);}catch(E){br(n,E,"decompression_failed");}return I},d=[],p=[],h=[],b=te(a,"Metadata")[0];if(b){let w=te(b,"Property");for(let S of w)d.push(await Fe(S,m,{strictValidation:n.strictValidation}));}let g=[];for(let w of te(a,"Image")){let S=await tr(w,l,m,n.decodeImageData,n.strictValidation);g.push(S);}for(let w=0;w<a.childNodes.length;w++){let S=a.childNodes.item(w);if(!S||S.nodeType!==1)continue;let I=S,A=xe(I);A==="Property"?p.push(await Fe(I,m,{strictValidation:n.strictValidation})):A==="Table"&&h.push(await dt(I,l,m,{strictValidation:n.strictValidation}));}let y={present:false,verified:true};if(c&&n.signaturePolicy==="ignore")y={present:true,verified:false,reason:"Signature verification skipped by signaturePolicy=ignore"};else if(n.verifySignatures&&(y=await Mn(s),y.present&&!y.verified)){if(n.signaturePolicy==="require")throw new ke(y.reason??"Signature verification failed");$n(n,{code:"signature_verification_failed",message:y.reason??"Signature verification failed"});}return new e({metadata:d,images:g,standaloneProperties:p,standaloneTables:h,version:a.getAttribute("version")??"1.0",signature:y})}static async fromBlob(t,r){let n=await t.arrayBuffer();return e.fromArrayBuffer(n,r)}static async fromURL(t,r){let n=await fetch(t);if(!n.ok)throw new ce(`Failed to fetch XISF file: ${n.status} ${n.statusText}`);let i=await n.arrayBuffer(),o=r?.headerDir??e.deriveHeaderDirFromURL(t);return e.fromArrayBuffer(i,{...r,baseUrl:r?.baseUrl??t,headerDir:o})}static fromNodeBuffer(t,r){let n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return e.fromArrayBuffer(n,r)}getImage(t=0){return this.unit.images[t]}getMetadata(){return this.unit.metadata}static async resolveExternalLocation(t,r){if(t.type==="url"){let o=await r.resourceResolver.resolveURL(t.url);return t.indexId?e.sliceIndexedBlock(Xn(o),t.indexId):o}let n=yn(t.path,r.headerDir||void 0),i=await r.resourceResolver.resolvePath(n);return t.indexId?e.sliceIndexedBlock(Xn(i),t.indexId):i}static sliceIndexedBlock(t,r){let i=Rn(t).byId.get(r);if(!i)throw new F(`Missing XISB block for indexId ${r.toString(16)}`);return Cn(t,i)}static deriveHeaderDirFromURL(t){try{let r=new URL(t),n=r.pathname,i=n.lastIndexOf("/");if(i<0)return "";let o=n.slice(0,i);return `${r.protocol}//${r.host}${o}`}catch{return ""}}};var At={I8Vector:"Int8",UI8Vector:"UInt8",ByteArray:"UInt8",I16Vector:"Int16",UI16Vector:"UInt16",I32Vector:"Int32",UI32Vector:"UInt32",I64Vector:"Int64",UI64Vector:"UInt64",IVector:"Int32",UIVector:"UInt32",F32Vector:"Float32",F64Vector:"Float64",Vector:"Float64",C32Vector:"Complex32",C64Vector:"Complex64"},Kn={I8Matrix:"Int8",UI8Matrix:"UInt8",ByteMatrix:"UInt8",I16Matrix:"Int16",UI16Matrix:"UInt16",I32Matrix:"Int32",UI32Matrix:"UInt32",I64Matrix:"Int64",UI64Matrix:"UInt64",IMatrix:"Int32",UIMatrix:"UInt32",F32Matrix:"Float32",F64Matrix:"Float64",Matrix:"Float64",C32Matrix:"Complex32",C64Matrix:"Complex64"},Ws=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),zs=new Set(["Gray","RGB","CIELab"]),Gs=new Set(["Planar","Normal"]);function Vn(e){return {strictValidation:e?.strictValidation??true,blockAlignment:e?.blockAlignment??4096,maxInlineBlockSize:e?.maxInlineBlockSize??3072,compression:e?.compression??null,compressionLevel:e?.compressionLevel??0,checksumAlgorithm:e?.checksumAlgorithm??"sha1",codecProvider:e?.codecProvider??pt}}function Yn(e){return typeof e=="boolean"?e?"true":"false":typeof e=="bigint"?e.toString(10):String(e)}function yr(e){switch(e){case "Boolean":case "Int8":case "UInt8":return 1;case "Int16":case "UInt16":return 2;case "Int32":case "UInt32":case "Float32":return 4;case "Int64":case "UInt64":case "Float64":return 8;case "Complex32":return 8;case "Complex64":return 16}}function St(e){switch(e){case "UInt8":return 1;case "UInt16":return 2;case "UInt32":case "Float32":return 4;case "UInt64":case "Float64":return 8;case "Complex32":return 8;case "Complex64":return 16}}function wt(e){let t=At[e]??Kn[e];return t?yr(t)>1:false}function js(e,t,r,n,i){switch(t){case "Boolean":case "UInt8":e.setUint8(r,Number(n));break;case "Int8":e.setInt8(r,Number(n));break;case "Int16":e.setInt16(r,Number(n),i);break;case "UInt16":e.setUint16(r,Number(n),i);break;case "Int32":e.setInt32(r,Number(n),i);break;case "UInt32":e.setUint32(r,Number(n),i);break;case "Int64":e.setBigInt64(r,BigInt(n),i);break;case "UInt64":e.setBigUint64(r,BigInt(n),i);break;case "Float32":e.setFloat32(r,Number(n),i);break;case "Float64":e.setFloat64(r,Number(n),i);break;}}function Ks(e){if(Array.isArray(e)&&e.length>=2)return {real:Number(e[0]),imag:Number(e[1])};if(e&&typeof e=="object"){let t=e;return {real:Number(t.real??0),imag:Number(t.imag??0)}}return {real:Number(e??0),imag:0}}function Wn(e){return ArrayBuffer.isView(e)?Array.from(e):Array.isArray(e)?e.length>0&&Array.isArray(e[0])?e.flat():e:[]}function Zn(e){let r=(e.dataBlock?.byteOrder==="big"?"big":"little")==="little",n=(s,c)=>{if(s==="Complex32"||s==="Complex64"){let l=s==="Complex32"?4:8,m=new Uint8Array(c.length*l*2),d=new DataView(m.buffer);for(let p=0;p<c.length;p++){let h=Ks(c[p]),b=p*l*2;s==="Complex32"?(d.setFloat32(b,h.real,r),d.setFloat32(b+4,h.imag,r)):(d.setFloat64(b,h.real,r),d.setFloat64(b+8,h.imag,r));}return m}let a=new Uint8Array(c.length*yr(s)),u=new DataView(a.buffer),f=yr(s);for(let l=0;l<c.length;l++)js(u,s,l*f,c[l],r);return a},i=At[e.type];if(i){let s=Wn(e.value);return {bytes:n(i,s),itemCount:s.length}}let o=Kn[e.type];if(o){let s=e.value,c=e.rows??s?.rows,a=e.columns??s?.columns,u=s?.values??e.value,f=Wn(u);return {bytes:n(o,f),itemCount:f.length,rows:c,columns:a}}}function zn(e,t){if(!Ws.has(e.sampleFormat))throw new F(`Unsupported image sampleFormat: ${e.sampleFormat}`);if(!zs.has(e.colorSpace??"Gray"))throw new F(`Unsupported image colorSpace: ${e.colorSpace}`);if(!Gs.has(e.pixelStorage??"Planar"))throw new F(`Unsupported image pixelStorage: ${e.pixelStorage}`);if(e.geometry.length===0||e.geometry.some(r=>!Number.isInteger(r)||r<=0))throw new F("Image geometry must contain positive integers");if(!Number.isInteger(e.channelCount)||e.channelCount<=0)throw new F("Image channelCount must be a positive integer");if(t&&(e.sampleFormat==="Float32"||e.sampleFormat==="Float64")&&!e.bounds)throw new F("bounds is required for Float32/Float64 images")}async function Gn(e,t,r,n){let i=e;if(r.compression){let o=Fn(i,r.compression,r.codecProvider,r.compressionLevel,n);i=o.data;let s=o.spec,c=s.itemSize?`${s.codec}:${s.uncompressedSize}:${s.itemSize}`:`${s.codec}:${s.uncompressedSize}`;t.setAttribute("compression",c);}if(r.checksumAlgorithm){let o=await ar(i,r.checksumAlgorithm);t.setAttribute("checksum",`${r.checksumAlgorithm}:${o}`);}return i}function rt(e,t,r,n,i){let o=e.createElement("Property");o.setAttribute("id",r.id),o.setAttribute("type",r.type),r.format&&o.setAttribute("format",r.format),r.comment&&o.setAttribute("comment",r.comment);let s=r.value;if(s!=null)if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="bigint")if(r.type==="String"&&typeof s=="string"&&s.length>i){let c=new TextEncoder().encode(String(s));o.setAttribute("location",`attachment:0:${c.byteLength}`),n.push({element:o,data:c});}else r.type==="String"&&!r.dataBlock?o.appendChild(e.createTextNode(String(s))):o.setAttribute("value",Yn(s));else if(ArrayBuffer.isView(s)){let c=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);c.byteLength<=i?(o.setAttribute("length",String(s.length??c.byteLength)),o.setAttribute("location","inline:base64"),o.appendChild(e.createTextNode(It(c)))):(o.setAttribute("length",String(s.length??c.byteLength)),o.setAttribute("location",`attachment:0:${c.byteLength}`),n.push({element:o,data:c})),wt(r.type)&&r.dataBlock?.byteOrder&&o.setAttribute("byteOrder",r.dataBlock.byteOrder);}else {let c=Zn(r);c&&(c.rows!==void 0&&o.setAttribute("rows",String(c.rows)),c.columns!==void 0&&o.setAttribute("columns",String(c.columns)),r.type in At&&o.setAttribute("length",String(c.itemCount)),c.bytes.byteLength<=i?(o.setAttribute("location","inline:base64"),o.appendChild(e.createTextNode(It(c.bytes)))):(o.setAttribute("location",`attachment:0:${c.bytes.byteLength}`),n.push({element:o,data:c.bytes})),wt(r.type)&&r.dataBlock?.byteOrder&&o.setAttribute("byteOrder",r.dataBlock.byteOrder));}r.rows!==void 0&&o.setAttribute("rows",String(r.rows)),r.columns!==void 0&&o.setAttribute("columns",String(r.columns)),t.appendChild(o);}function Sr(e,t,r,n,i){let o=e.createElement("Table");o.setAttribute("id",r.id),r.caption&&o.setAttribute("caption",r.caption),r.comment&&o.setAttribute("comment",r.comment),o.setAttribute("rows",String(r.dataRows.length)),o.setAttribute("columns",String(r.structure.length));let s=e.createElement("Structure");for(let c of r.structure){let a=e.createElement("Field");a.setAttribute("id",c.id),a.setAttribute("type",c.type),c.format&&a.setAttribute("format",c.format),c.header&&a.setAttribute("header",c.header),s.appendChild(a);}o.appendChild(s);for(let c of r.dataRows){let a=e.createElement("Row");for(let u=0;u<c.cells.length;u++){let f=c.cells[u],l=r.structure[u],m=e.createElement("Cell"),d=f.type||l?.type;if(d&&m.setAttribute("type",d),(f.id||l?.id)&&m.setAttribute("id",f.id||l.id),(f.format||l?.format)&&m.setAttribute("format",f.format||l.format),f.comment&&m.setAttribute("comment",f.comment),f.value!==void 0&&f.value!==null){if(typeof f.value=="string"||typeof f.value=="number"||typeof f.value=="boolean"||typeof f.value=="bigint")m.setAttribute("value",Yn(f.value));else if(ArrayBuffer.isView(f.value)){let p=new Uint8Array(f.value.buffer,f.value.byteOffset,f.value.byteLength);p.byteLength<=i?(m.setAttribute("location","inline:base64"),m.appendChild(e.createTextNode(It(p)))):(m.setAttribute("location",`attachment:0:${p.byteLength}`),n.push({element:m,data:p})),d&&wt(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder);}else if(d){let p=Zn({...f,type:d});p&&(p.rows!==void 0&&m.setAttribute("rows",String(p.rows)),p.columns!==void 0&&m.setAttribute("columns",String(p.columns)),d in At&&m.setAttribute("length",String(p.itemCount)),p.bytes.byteLength<=i?(m.setAttribute("location","inline:base64"),m.appendChild(e.createTextNode(It(p.bytes)))):(m.setAttribute("location",`attachment:0:${p.bytes.byteLength}`),n.push({element:m,data:p.bytes})),wt(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder));}}a.appendChild(m);}o.appendChild(a);}t.appendChild(o);}function jn(e,t,r,n,i){for(let o of r.fitsKeywords){let s=e.createElement("FITSKeyword");s.setAttribute("name",o.name),s.setAttribute("value",o.value),s.setAttribute("comment",o.comment),t.appendChild(s);}for(let o of r.properties)rt(e,t,o,n,i);for(let o of r.tables)Sr(e,t,o,n,i);if(r.iccProfile){let o=e.createElement("ICCProfile");o.setAttribute("location",`attachment:0:${r.iccProfile.byteLength}`),n.push({element:o,data:r.iccProfile}),t.appendChild(o);}if(r.rgbWorkingSpace){let o=e.createElement("RGBWorkingSpace");o.setAttribute("gamma",r.rgbWorkingSpace.gamma),o.setAttribute("x",r.rgbWorkingSpace.x.join(":")),o.setAttribute("y",r.rgbWorkingSpace.y.join(":")),o.setAttribute("Y",r.rgbWorkingSpace.Y.join(":")),r.rgbWorkingSpace.name&&o.setAttribute("name",r.rgbWorkingSpace.name),t.appendChild(o);}if(r.displayFunction){let o=e.createElement("DisplayFunction");o.setAttribute("m",r.displayFunction.m.join(":")),o.setAttribute("s",r.displayFunction.s.join(":")),o.setAttribute("h",r.displayFunction.h.join(":")),o.setAttribute("l",r.displayFunction.l.join(":")),o.setAttribute("r",r.displayFunction.r.join(":")),r.displayFunction.name&&o.setAttribute("name",r.displayFunction.name),t.appendChild(o);}if(r.colorFilterArray){let o=e.createElement("ColorFilterArray");o.setAttribute("pattern",r.colorFilterArray.pattern),o.setAttribute("width",String(r.colorFilterArray.width)),o.setAttribute("height",String(r.colorFilterArray.height)),r.colorFilterArray.name&&o.setAttribute("name",r.colorFilterArray.name),t.appendChild(o);}if(r.resolution){let o=e.createElement("Resolution");o.setAttribute("horizontal",String(r.resolution.horizontal)),o.setAttribute("vertical",String(r.resolution.vertical)),r.resolution.unit&&o.setAttribute("unit",r.resolution.unit),t.appendChild(o);}}function It(e){try{return Me(e)}catch(t){throw new F(`No base64 encoder available in this environment: ${t.message}`)}}async function Ys(e,t,r){let n=-1,i="",o=0;for(;o!==n;){let c=t.ownerDocument;if(i=ft(c),o=new TextEncoder().encode(i).byteLength,o===n)break;n=o;let u=16+o,f=l=>e.blockAlignment>1?Math.ceil(l/e.blockAlignment)*e.blockAlignment:l;u=f(u);for(let l of r)l.element.setAttribute("location",`attachment:${u}:${l.data.byteLength}`),u=f(u+l.data.byteLength);}let s=[];for(let c of r){let a=c.element.getAttribute("location");if(!a)continue;let u=a.split(":"),f=Number(u[1]);s.push({position:f,data:c.data});}return s}var ne=class{static async toMonolithic(t,r){let n=Vn(r),i=Yt(),o=i.documentElement,s=i.createElement("Metadata"),c=[];for(let l of t.metadata)rt(i,s,l,c,n.maxInlineBlockSize);o.appendChild(s);for(let l of t.standaloneProperties)rt(i,o,l,c,n.maxInlineBlockSize);for(let l of t.standaloneTables)Sr(i,o,l,c,n.maxInlineBlockSize);for(let l of t.images){if(zn(l,n.strictValidation),!l.data)throw new F("Image data is required for monolithic writing");let m=i.createElement("Image");m.setAttribute("geometry",[...l.geometry,l.channelCount].join(":")),m.setAttribute("sampleFormat",l.sampleFormat),m.setAttribute("colorSpace",l.colorSpace??"Gray"),m.setAttribute("pixelStorage",l.pixelStorage??"Planar"),l.bounds&&m.setAttribute("bounds",`${l.bounds[0]}:${l.bounds[1]}`),l.id&&m.setAttribute("id",l.id),l.uuid&&m.setAttribute("uuid",l.uuid),l.imageType&&m.setAttribute("imageType",l.imageType),l.offset!==void 0&&m.setAttribute("offset",String(l.offset)),l.orientation&&m.setAttribute("orientation",l.orientation),l.dataBlock.byteOrder&&St(l.sampleFormat)>1&&m.setAttribute("byteOrder",l.dataBlock.byteOrder);let d=St(l.sampleFormat),p=await Gn(l.data,m,n,Math.max(1,d));m.setAttribute("location",`attachment:0:${p.byteLength}`),c.push({element:m,data:p}),jn(i,m,l,c,n.maxInlineBlockSize),o.appendChild(m);}let a=await Ys(n,o,c),u=ft(i);return pn(u,a).slice().buffer}static async toDistributed(t,r){let n=Vn(r),i=Yt(),o=i.documentElement,s=[],c=[],a=i.createElement("Metadata");o.appendChild(a);let u=(d,p)=>{s.push({element:d,data:p});};for(let d of t.metadata)rt(i,a,d,c,n.maxInlineBlockSize);for(let d of t.standaloneProperties)rt(i,o,d,c,n.maxInlineBlockSize);for(let d of t.standaloneTables)Sr(i,o,d,c,n.maxInlineBlockSize);for(let d of t.images){if(zn(d,n.strictValidation),!d.data)throw new F("Image data is required for distributed writing");let p=i.createElement("Image");p.setAttribute("geometry",[...d.geometry,d.channelCount].join(":")),p.setAttribute("sampleFormat",d.sampleFormat),p.setAttribute("colorSpace",d.colorSpace??"Gray"),p.setAttribute("pixelStorage",d.pixelStorage??"Planar"),d.bounds&&p.setAttribute("bounds",`${d.bounds[0]}:${d.bounds[1]}`),d.id&&p.setAttribute("id",d.id),d.uuid&&p.setAttribute("uuid",d.uuid),d.imageType&&p.setAttribute("imageType",d.imageType),d.offset!==void 0&&p.setAttribute("offset",String(d.offset)),d.orientation&&p.setAttribute("orientation",d.orientation),d.dataBlock.byteOrder&&St(d.sampleFormat)>1&&p.setAttribute("byteOrder",d.dataBlock.byteOrder);let h=St(d.sampleFormat),b=await Gn(d.data,p,n,Math.max(1,h));p.setAttribute("location",`attachment:0:${b.byteLength}`),c.push({element:p,data:b}),jn(i,p,d,c,n.maxInlineBlockSize),o.appendChild(p);}for(let d of c)u(d.element,d.data);let{bytes:f,ids:l}=Un(s.map(d=>d.data));for(let d=0;d<s.length;d++){let p=l[d];s[d].element.setAttribute("location",`path(@header_dir/blocks.xisb):0x${p.toString(16)}`);}return {header:new TextEncoder().encode(ft(i)),blocks:{"blocks.xisb":f}}}};function xt(e){return e.padEnd(80," ").slice(0,80)}function Zs(e){return e==null?"":typeof e=="string"?`'${e.replaceAll("'","''")}'`:typeof e=="boolean"?e?"T":"F":typeof e=="bigint"?e.toString(10):Number.isFinite(e)?Number.isInteger(e)?e.toString(10):e.toExponential().replace("e","E"):String(e)}function qs(e){let t=e.key.toUpperCase().slice(0,8).padEnd(8," ");if(e.key==="END")return xt("END");if(e.value===void 0)return xt(`${t} ${e.comment??""}`);let r=Zs(e.value),n=`${t}= ${r}`;return e.comment?xt(`${n} / ${e.comment}`):xt(n)}function qn(e){return e+(2880-e%2880)%2880}function Js(e){let t=[...e];t.some(i=>i.key==="END")||t.push({key:"END"});let r=t.map(qs).join(""),n=r.padEnd(qn(r.length)," ");return new TextEncoder().encode(n)}function ie(e){let t=e.map(s=>Js(s.cards)),r=e.map(s=>{let c=s.data??new Uint8Array(0),a=qn(c.byteLength),u=new Uint8Array(a);return u.set(c),u}),n=t.reduce((s,c)=>s+c.byteLength,0)+r.reduce((s,c)=>s+c.byteLength,0),i=new Uint8Array(n),o=0;for(let s=0;s<e.length;s++){let c=t[s],a=r[s];i.set(c,o),o+=c.byteLength,i.set(a,o),o+=a.byteLength;}return i.buffer}function G(e,t){let r=Math.abs(t)/8,n=new Uint8Array(e.length*r),i=new DataView(n.buffer);for(let o=0;o<e.length;o++){let s=e[o],c=o*r;switch(t){case 8:i.setUint8(c,Number(s));break;case 16:i.setInt16(c,Number(s),false);break;case 32:i.setInt32(c,Number(s),false);break;case 64:i.setBigInt64(c,BigInt(s),false);break;case -32:i.setFloat32(c,Number(s),false);break;case -64:i.setFloat64(c,Number(s),false);break}}return n}function oe(e){let t=e.depth&&e.depth>1?3:2,r=[];return e.primary!==false?r.push({key:"SIMPLE",value:true,comment:"Standard FITS"}):r.push({key:"XTENSION",value:e.extensionType??"IMAGE",comment:"Image extension"}),r.push({key:"BITPIX",value:e.bitpix,comment:"Bits per pixel"}),r.push({key:"NAXIS",value:t,comment:"Number of axes"}),r.push({key:"NAXIS1",value:e.width}),r.push({key:"NAXIS2",value:e.height}),t===3&&r.push({key:"NAXIS3",value:e.depth??1}),e.primary!==false?r.push({key:"EXTEND",value:true}):(r.push({key:"PCOUNT",value:0}),r.push({key:"GCOUNT",value:1})),e.bscale!==void 0&&r.push({key:"BSCALE",value:e.bscale}),e.bzero!==void 0&&r.push({key:"BZERO",value:e.bzero}),e.extname&&r.push({key:"EXTNAME",value:e.extname}),e.additionalCards&&r.push(...e.additionalCards),{cards:r,data:e.data}}var Ir=32768,Ar=2147483648,Ft=9223372036854775808n,Qn="FITS:PreservedHDULayout";function Qs(e){return e.reduce((t,r)=>t*r,1)}function wr(e,t,r,n){switch(r){case "UInt8":return e.getUint8(t);case "UInt16":return e.getUint16(t,n);case "UInt32":return e.getUint32(t,n);case "UInt64":return e.getBigUint64(t,n);case "Float32":return e.getFloat32(t,n);case "Float64":return e.getFloat64(t,n);default:return e.getFloat32(t,n)}}function xr(e){switch(e){case "UInt8":return 1;case "UInt16":return 2;case "UInt32":case "Float32":return 4;case "UInt64":case "Float64":return 8;case "Complex32":return 8;case "Complex64":return 16}}function ea(e){if(!e.data)throw new Y("XISF image data was not decoded");let t=xr(e.sampleFormat),r=new DataView(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=e.data.byteLength/t,i=e.dataBlock.byteOrder!=="big";if(e.sampleFormat==="Complex32"||e.sampleFormat==="Complex64"){let s=e.sampleFormat==="Complex32"?"Float32":"Float64",c=xr(s),a=new Array(n*t/c),u=0;for(let f=0;f<n;f++){let l=f*t;a[u++]=Number(wr(r,l,s,i)),a[u++]=Number(wr(r,l+c,s,i));}return a}let o=new Array(n);for(let s=0;s<n;s++)o[s]=wr(r,s*t,e.sampleFormat,i);if(e.pixelStorage==="Normal"&&e.channelCount>1){let s=n/e.channelCount,c=new Array(n),a=0;for(let u=0;u<e.channelCount;u++)for(let f=0;f<s;f++)c[a++]=o[f*e.channelCount+u];return c}return o}function ta(e,t){let r=xr(t),n=new Uint8Array(e.length*r),i=new DataView(n.buffer);for(let o=0;o<e.length;o++){let s=e[o],c=o*r;switch(t){case "UInt8":i.setUint8(c,Number(s));break;case "UInt16":i.setUint16(c,Number(s),true);break;case "UInt32":i.setUint32(c,Number(s),true);break;case "UInt64":i.setBigUint64(c,BigInt(s),true);break;case "Float32":i.setFloat32(c,Number(s),true);break;case "Float64":i.setFloat64(c,Number(s),true);break;}}return n}function ra(e,t){let r=t==="Complex32"?4:8,n=new Uint8Array(e.length*r),i=new DataView(n.buffer);for(let o=0;o<e.length;o++){let s=e[o],c=o*r;t==="Complex32"?i.setFloat32(c,s,true):i.setFloat64(c,s,true);}return n}function ei(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function na(e){return Me(e)}async function ia(e){return Ee(e)}function oa(e){return JSON.stringify({metadata:e.unit.metadata,standaloneProperties:e.unit.standaloneProperties,standaloneTables:e.unit.standaloneTables},null,0)}function sa(e){if(e.geometry.length===1)return {width:e.geometry[0],height:1,depth:e.channelCount};if(e.geometry.length===2)return {width:e.geometry[0],height:e.geometry[1],depth:e.channelCount};let t=e.geometry[0],r=e.geometry[1],n=Qs(e.geometry.slice(2));return {width:t,height:r,depth:e.channelCount*n}}function ti(e){return e?.strictValidation??e?.relaxed!==true}function aa(e,t){let r=e.get(t);return r===true||r==="T"||r==="true"||r===1}function ca(e){if(e.trimStart().startsWith("'")){let r=e.indexOf("'"),n=-1,i=r+1;for(;i<e.length;){let o=e.indexOf("'",i);if(o===-1)break;if(o+1<e.length&&e[o+1]==="'"){i=o+2;continue}n=o;break}return n===-1?e.trim():e.slice(0,n+1).trim()}let t=e.indexOf(" /");return (t===-1?e:e.slice(0,t)).trim()}function Jn(e,t){let n=e.block;for(let i=0;i+80<=n.length;i+=80){let o=n.slice(i,i+80);if(o.slice(0,8).trim()===t)return o.slice(8,10)!=="= "?null:ca(o.slice(10))}return null}function ua(e){if(!e)return null;let t=e.trim();if(!/^[-+]?\d+$/u.test(t))return null;try{return BigInt(t)}catch{return null}}function la(e,t){if(t.bitpix!==64)return false;let r=Jn(e,"BSCALE"),n=Jn(e,"BZERO");return (r?Number(r):1)!==1?false:ua(n)===Ft}function fa(e){return e===true?"T":e===false?"F":e==null?"":String(e)}function ma(e,t,r){let n=e.filter(i=>i.id!==t);return n.push({id:t,type:"String",value:r}),n}function da(e){let t=e.find(r=>r.id===Qn);if(!t||typeof t.value!="string")return null;try{let r=JSON.parse(t.value);return !Array.isArray(r.imageSourceIndices)||!Array.isArray(r.nonImageHDUs)?null:r}catch{return null}}function pa(e,t){return {cards:e.cards.map(r=>({key:r.key,value:r.value,comment:r.comment})),data:t}}async function ha(e,t){let r=e.header.getCards().map(i=>({key:i.key,value:typeof i.value=="bigint"?Number(i.value):i.value,comment:i.comment||void 0})),n=new Uint8Array(0);return e.data?.buffer?n=new Uint8Array(e.data.buffer):e.data?.blob&&(n=new Uint8Array(await e.data.blob.arrayBuffer())),{index:t,cards:r,dataBase64:await na(n)}}async function Fr(e,t){let r=ti(t),n=e instanceof J?e:await J.fromArrayBuffer(await ei(e),{strictValidation:r}),i=[];for(let u=0;u<n.unit.images.length;u++){let f=n.unit.images[u],l=ea(f),{width:m,height:d,depth:p}=sa(f),h=f.fitsKeywords.map(w=>({key:w.name,value:w.value,comment:w.comment}));if(f.sampleFormat==="Complex32"||f.sampleFormat==="Complex64"){let w=G(l,f.sampleFormat==="Complex32"?-32:-64),S=f.sampleFormat==="Complex32"?8:16,I=m*d*p;i.push({cards:[{key:"XTENSION",value:"BINTABLE",comment:"Binary table extension"},{key:"BITPIX",value:8,comment:"8-bit bytes"},{key:"NAXIS",value:2,comment:"Table axes"},{key:"NAXIS1",value:S,comment:"Bytes per row"},{key:"NAXIS2",value:I,comment:"Rows"},{key:"PCOUNT",value:0},{key:"GCOUNT",value:1},{key:"TFIELDS",value:1},{key:"TTYPE1",value:"XISFCPLX"},{key:"TFORM1",value:f.sampleFormat==="Complex32"?"1C":"1M"},{key:"EXTNAME",value:u===0?"XISF_COMPLEX":`XISF_COMPLEX_${u}`},{key:"XISFCPLX",value:true},{key:"XISFSFMT",value:f.sampleFormat},{key:"XISFWID",value:m},{key:"XISFHEI",value:d},{key:"XISFDEP",value:p},{key:"XISFCHN",value:f.channelCount},...h],data:w});continue}let b,g,y;switch(f.sampleFormat){case "UInt8":b=8,y=G(l,8);break;case "UInt16":{b=16,g=Ir;let w=Array.from(l,S=>Number(S)-Ir);y=G(w,16);break}case "UInt32":{b=32,g=Ar;let w=Array.from(l,S=>Number(S)-Ar);y=G(w,32);break}case "UInt64":{b=64,g=Ft;let w=Array.from(l,S=>BigInt(S)-Ft);y=G(w,64);break}case "Float32":b=-32,y=G(l,-32);break;case "Float64":b=-64,y=G(l,-64);break;default:throw new Y(`Unsupported sample format: ${f.sampleFormat}`)}i.push(oe({primary:u===0,extensionType:"IMAGE",width:m,height:d,depth:p,bitpix:b,data:y,bzero:g,bscale:1,extname:u===0?void 0:f.id??`IMAGE_${u}`,additionalCards:h}));}let o=da(n.unit.metadata),s=[];if(o)for(let u of o.nonImageHDUs)s.push({index:u.index,hdu:pa(u,await ia(u.dataBase64))});if(n.unit.images.length===0){if(s.length===0)throw new Y("No images or preserved FITS HDUs found in XISF unit");let u=o?s.sort((f,l)=>f.index-l.index).map(f=>f.hdu):s.map(f=>f.hdu);return ie(u)}let c=i;if(o&&o.imageSourceIndices.length===i.length){let u=new Map;for(let m=0;m<i.length;m++)u.set(o.imageSourceIndices[m],i[m]);for(let m of s)u.set(m.index,m.hdu);let f=Math.max(...u.keys()),l=[];for(let m=0;m<=f;m++){let d=u.get(m);d&&l.push(d);}c=l;}else s.length>0&&(c=[...i,...s.sort((u,f)=>u.index-f.index).map(u=>u.hdu)]);if(t?.includeXisfMetaExtension??true){let u=new TextEncoder().encode(oa(n));c.push(oe({primary:false,extensionType:"IMAGE",width:u.byteLength,height:1,bitpix:8,data:u,extname:"XISF_META"}));}return ie(c)}async function ga(e){let t=[],r=e.depth;for(let n=0;n<r;n++){let i=await e.getFrame(n);for(let o=0;o<i.length;o++){let s=i[o];t.push(typeof s=="bigint"?s:Number(s));}}return t}async function ba(e){let t=[];for(let r=0;r<e.depth;r++){let n=e.frameOffsets[r],i=n.buffers?.[0];if(!i){if(e.buffer)i=e.buffer.slice(n.begin,n.begin+e.frameLength);else if(e.blob)i=await e.blob.slice(n.begin,n.begin+e.frameLength).arrayBuffer();else throw new Y("Image data source is unavailable for UInt64 conversion");n.buffers=[i];}let o=new DataView(i),s=i.byteLength/8;for(let c=0;c<s;c++)t.push(o.getBigInt64(c*8,false)+Ft);}return t}function ya(e,t){let r=t.bzero;return t.bitpix===8?"UInt8":t.bitpix===16&&r===Ir?"UInt16":t.bitpix===32&&r===Ar?"UInt32":la(e,t)?"UInt64":t.bitpix===-32?"Float32":(t.bitpix===-64,"Float64")}async function Er(e,t){let r=ti(t),n=t?.writeOptions,i=e instanceof j?e:j.fromArrayBuffer(await ei(e),{onWarning:r?void 0:()=>{}}),o=[],s=[],c=[],a={};for(let l=0;l<i.hdus.length;l++){let m=i.hdus[l],d=m.header,p=d.getString("EXTNAME","");if(m.data&&m.data instanceof q&&aa(d,"XISFCPLX")){let S=d.getString("XISFSFMT","Complex32")==="Complex64"?"Complex64":"Complex32",I=d.getNumber("XISFWID"),A=d.getNumber("XISFHEI",1),x=d.getNumber("XISFDEP",1),E=d.getNumber("XISFCHN",1),C=await m.data.getRows(0,m.data.rows),$=m.data.columns?.[0]??"XISFCPLX",U=[];for(let k of C){let R=k[$];if(!Array.isArray(R)||R.length!==2)throw new Y("Invalid complex payload in BINTABLE extension");U.push(Number(R[0]),Number(R[1]));}o.push({id:p||(l===0?"PRIMARY":`IMAGE_${l}`),geometry:x>1?[I,A,x]:[I,A],channelCount:E,sampleFormat:S,pixelStorage:"Planar",colorSpace:"Gray",dataBlock:{location:{type:"attachment",position:0,size:U.length*(S==="Complex32"?4:8)},byteOrder:"little"},data:ra(U,S),properties:[],tables:[],fitsKeywords:[]}),s.push(l);continue}if(!m.data||!(m.data instanceof ee)){c.push(await ha(m,l));continue}if(p==="XISF_META"){let S=await m.data.getFrame(0),I=new Uint8Array(S.length);for(let A=0;A<S.length;A++)I[A]=Number(S[A])&255;try{a=JSON.parse(new TextDecoder("utf-8").decode(I));}catch{}continue}let h=ya(d,m.data);if(r&&m.data.bitpix===64&&h!=="UInt64")throw new Y("FITS BITPIX=64 without canonical UInt64 BZERO cannot be converted losslessly");let b=h==="UInt64"?await ba(m.data):await ga(m.data),g=ta(b,h),y=d.getCards().map(S=>({name:S.key,value:fa(S.value),comment:S.comment})),w=[m.data.width,m.data.height];m.data.depth>1&&w.push(m.data.depth),o.push({id:p||(l===0?"PRIMARY":`IMAGE_${l}`),geometry:w,channelCount:1,sampleFormat:h,bounds:h.startsWith("Float")?[0,1]:void 0,pixelStorage:"Planar",colorSpace:"Gray",dataBlock:{location:{type:"attachment",position:0,size:g.byteLength},byteOrder:"little"},data:g,properties:[],tables:[],fitsKeywords:y}),s.push(l);}if(o.length===0&&c.length===0)throw new Y("No convertible FITS image HDUs found");let u=a.metadata??[{id:"XISF:CreatorApplication",type:"String",value:"fitsjs-ng conversion"},{id:"XISF:CreationTime",type:"TimePoint",value:new Date().toISOString()}];c.length>0&&(u=ma(u,Qn,JSON.stringify({imageSourceIndices:s,nonImageHDUs:c})));let f={metadata:u,images:o,standaloneProperties:a.standaloneProperties??[],standaloneTables:a.standaloneTables??[],version:"1.0",signature:{present:false,verified:true}};return t?.distributed?ne.toDistributed(f,n):ne.toMonolithic(f,n)}var _e=class extends se{constructor(t){super(t),this.name="SERError";}},de=class extends _e{constructor(t){super(t),this.name="SERParseError";}},D=class extends _e{constructor(t){super(t),this.name="SERValidationError";}},H=class extends _e{constructor(t){super(t),this.name="SERConversionError";}};var nt="LUCAM-RECORDER",ri=[0,8,9,10,11,16,17,18,19,100,101],Te={0:1,8:1,9:1,10:1,11:1,16:1,17:1,18:1,19:1,100:3,101:3},He={8:"RGGB",9:"GRBG",10:"GBRG",11:"BGGR",16:"CYYM",17:"YCMY",18:"YMCY",19:"MYYC"},ni=621355968000000000n;var Sa=e=>{};function wa(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??Sa}}function $e(e,t,r){e.onWarning({code:t,message:r});}function Et(e){let t=e.length;for(let r=0;r<e.length;r++)if(e[r]===0){t=r;break}return new TextDecoder("ascii").decode(e.slice(0,t)).trim()}function ii(e){return ri.includes(e)}function Ia(e,t,r){if(t==="spec")return e!==0?"little":"big";if(t==="compat")return e===0?"little":"big";let n=e===0?"little":"big",i=e!==0?"little":"big";if(!r||r.byteLength<4)return n;let o=a=>{let u=new DataView(r.buffer,r.byteOffset,r.byteLength),f=a==="little",l=Math.min(4096,Math.floor(r.byteLength/2));if(l<=0)return 0;let m=0,d=u.getUint16(0,f),p=0,h=new Set;for(let w=0;w<l;w++){let S=u.getUint16(w*2,f);S%256===0&&m++,h.add(S&255),p+=Math.abs(S-d),d=S;}let b=h.size/256,g=1-m/l,y=1/(1+p/l);return g*.5+b*.4+y*.1},s=o(n),c=o(i);return s>=c?n:i}function Aa(e,t,r){if(r<=0||e<=0)return 0;let n=Math.floor(t/r),i=Math.floor(t/(r+8));return Math.max(0,Math.min(e,Math.max(i,1),n))}function oi(e,t,r){let n=wa(t),i=new Uint8Array(e);if(i.byteLength<178)throw new de(`SER buffer is too short: expected at least ${178} bytes, got ${i.byteLength}`);let o=new DataView(e),s=Et(i.slice(0,14));if(s!==nt)throw new de(`Invalid SER FileID: expected "${nt}", got "${s}"`);let c=o.getInt32(14,true),a=o.getInt32(18,true),u=o.getInt32(22,true),f=o.getInt32(26,true),l=o.getInt32(30,true),m=o.getInt32(34,true),d=o.getInt32(38,true),p=Et(i.slice(42,82)),h=Et(i.slice(82,122)),b=Et(i.slice(122,162)),g=o.getBigUint64(162,true),y=o.getBigUint64(170,true);if(!Number.isInteger(f)||f<=0)throw new D(`Invalid SER width: ${f}`);if(!Number.isInteger(l)||l<=0)throw new D(`Invalid SER height: ${l}`);if(!Number.isInteger(m)||m<1||m>16)throw new D(`Invalid SER pixel depth: ${m}`);if(!Number.isInteger(d)||d<0)throw new D(`Invalid SER frame count: ${d}`);if(!ii(a)){let P=`Unsupported SER color ID: ${a}`;if(n.strictValidation)throw new D(P);$e(n,"unsupported_color_id",`${P}; falling back to monochrome (0)`);}let w=ii(a)?a:0,S=Te[w],I=m<=8?1:2,A=f*l*S*I;if(!Number.isSafeInteger(A)||A<=0)throw new D(`Invalid SER frame byte length: ${A}`);let x=i.byteLength-178,E=d;if(E*A>x){let P=`SER frame count exceeds payload capacity (declared=${E}, frameBytes=${A}, payload=${x})`;if(n.strictValidation)throw new D(P);let v=Aa(E,x,A);$e(n,"frame_count_adjusted",`${P}; adjusted to ${v}`),E=v;}E===0&&$e(n,"empty_sequence","SER sequence has zero frames");let L=E>0?i.slice(178,178+Math.min(A,8192)):null,C=Ia(u,n.endiannessPolicy,L),$=E*A,U=178+$,k=i.byteLength-U,R=false,X=[];if(E>0&&k>=E*8){R=true;let P=new DataView(e,U,E*8);for(let N=0;N<E;N++)X.push(P.getBigUint64(N*8,true));let v=true;for(let N=1;N<X.length;N++)if(X[N]<X[N-1]){v=false;break}if(v||$e(n,"timestamps_not_ordered","SER frame timestamps are not in ascending order"),k!==E*8){let N=`SER trailer contains extra bytes (${k-E*8}) beyond timestamps`;if(n.strictValidation)throw new D(N);$e(n,"extra_trailer_bytes",N);}}else if(k>0){let P=`SER trailer has ${k} bytes but expected 0 or ${E*8}`;if(n.strictValidation)throw new D(P);$e(n,"truncated_timestamps",P);}let Z=[];for(let P=0;P<E;P++)Z.push({index:P,offset:178+P*A,byteLength:A,timestamp:X[P]});return {header:{fileId:s,luId:c,colorId:w,littleEndianFlag:u,byteOrder:C,width:f,height:l,pixelDepth:m,frameCount:E,observer:p,instrument:h,telescope:b,startTime:g,startTimeUtc:y,channelCount:S,bytesPerSample:I,frameByteLength:A},frameInfos:Z,timestamps:X,timestampsPresent:R,buffer:e,blob:r}}function Tr(e,t){return oi(e,t)}async function Pr(e,t){let r=await e.arrayBuffer();return oi(r,t,e)}function xa(e,t,r){if(t===1)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new Uint16Array(e.byteLength/2),o=r==="little";for(let s=0;s<i.length;s++)i[s]=n.getUint16(s*2,o);return i}function Fa(e){return He[e]}function it(e,t,r,n){return Number(e[r*n+t]??0)}function si(e){switch(e){case "R":return [true,false,false];case "G":return [false,true,false];case "B":return [false,false,true];case "C":return [false,true,true];case "M":return [true,false,true];case "Y":return [true,true,false];case "W":return [true,true,true];default:return [false,false,false]}}function Ea(e,t,r,n,i){let o=i===1?new Uint8Array(t*r*3):new Uint16Array(t*r*3),s=(a,u)=>n[u%2*2+a%2]??"R",c=(a,u,f)=>{for(let m=0;m<=3;m++){let d=Math.max(0,a-m),p=Math.min(t-1,a+m),h=Math.max(0,u-m),b=Math.min(r-1,u+m);for(let g=h;g<=b;g++)for(let y=d;y<=p;y++){let[w,S,I]=si(s(y,g));if(f===0?w:f===1?S:I)return it(e,y,g,t)}}return it(e,a,u,t)};for(let a=0;a<r;a++)for(let u=0;u<t;u++){let f=(a*t+u)*3,l=s(u,a),[m,d,p]=si(l);o[f]=m?it(e,u,a,t):c(u,a,0),o[f+1]=d?it(e,u,a,t):c(u,a,1),o[f+2]=p?it(e,u,a,t):c(u,a,2);}return o}var Pe=class e{parsed;constructor(t){this.parsed=t;}static fromArrayBuffer(t,r){return new e(Tr(t,r))}static async fromBlob(t,r){return new e(await Pr(t,r))}static async fromURL(t,r){let n=await fetch(t,r?.requestInit);if(!n.ok)throw new de(`Failed to fetch SER file: ${n.status} ${n.statusText}`);let i=await n.arrayBuffer();return e.fromArrayBuffer(i,r)}static fromNodeBuffer(t,r){let n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return e.fromArrayBuffer(n,r)}getHeader(){return this.parsed.header}getFrameCount(){return this.parsed.header.frameCount}getFrameInfo(t){let r=this.parsed.frameInfos[t];if(!r)throw new D(`Frame index out of range: ${t}`);return r}getTimestamp(t){return this.getFrameInfo(t).timestamp}getTimestampDate(t){let r=this.getTimestamp(t);if(r===void 0)return;let n=r-ni,i=Number(n/10000n);return new Date(i)}getDurationTicks(){if(this.parsed.timestamps.length<2)return;let t=this.parsed.timestamps[0],r=this.parsed.timestamps[this.parsed.timestamps.length-1];if(!(r<t))return r-t}getDurationSeconds(){let t=this.getDurationTicks();if(t!==void 0)return Number(t)/1e7}getEstimatedFPS(){let t=this.getDurationSeconds(),r=this.getFrameCount();if(!(!t||t<=0||r<2))return (r-1)/t}readFrameRawBytes(t){if(!this.parsed.buffer)throw new de("SER source buffer is unavailable");return new Uint8Array(this.parsed.buffer.slice(t.offset,t.offset+t.byteLength))}samplesToRGB(t,r){let{width:n,height:i,bytesPerSample:o}=this.parsed.header,s=n*i;if(r===100||r===101){let a=o===1?new Uint8Array(s*3):new Uint16Array(s*3);for(let u=0;u<s;u++){let f=u*3;r===100?(a[f]=t[f]??0,a[f+1]=t[f+1]??0,a[f+2]=t[f+2]??0):(a[f]=t[f+2]??0,a[f+1]=t[f+1]??0,a[f+2]=t[f]??0);}return a}if(r===0){let a=o===1?new Uint8Array(s*3):new Uint16Array(s*3);for(let u=0;u<s;u++){let f=Number(t[u]??0),l=u*3;a[l]=f,a[l+1]=f,a[l+2]=f;}return a}let c=Fa(r);if(!c)throw new D(`No RGB decode helper available for color ID ${r}`);return Ea(t,n,i,c,o)}getFrame(t,r){let n=this.getFrameInfo(t),i=this.readFrameRawBytes(n),o=xa(i,this.parsed.header.bytesPerSample,this.parsed.header.byteOrder),s=r?.asRGB?this.samplesToRGB(o,this.parsed.header.colorId):o,c=r?.asRGB?3:this.parsed.header.channelCount;return {info:n,raw:i,samples:s,width:this.parsed.header.width,height:this.parsed.header.height,channelCount:c,interleaved:c>1,colorId:this.parsed.header.colorId,pixelDepth:this.parsed.header.pixelDepth,byteOrder:this.parsed.header.byteOrder}}getFrameRGB(t){let r=this.getFrame(t);return this.samplesToRGB(r.samples,this.parsed.header.colorId)}getFrames(t,r,n){let i=[];for(let o=0;o<r;o++)i.push(this.getFrame(t+o,n));return i}async*[Symbol.asyncIterator](){for(let t=0;t<this.parsed.header.frameCount;t++)yield this.getFrame(t);}};var Ta=e=>{};function Pa(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??Ta}}function Cr(e,t,r){e.onWarning({code:t,message:r});}function Tt(e,t,r,n){let o=new TextEncoder().encode(n);for(let s=0;s<r;s++)e[t+s]=o[s]??0;}function Rr(e,t){return e===void 0?t:typeof e=="bigint"?e:BigInt(Math.trunc(e))}function Ra(e,t){return t==="spec"?e?1:0:e?0:1}function Ca(e,t,r,n){if(e.byteLength===t)return e;let i=`Frame ${n} byte length mismatch: expected ${t}, got ${e.byteLength}`;if(r.strictValidation)throw new D(i);Cr(r,"frame_length_adjusted",`${i}; applying truncation/padding`);let o=new Uint8Array(t);return o.set(e.subarray(0,Math.min(e.byteLength,t))),o}function Pt(e,t){let r=Pa(t),n=e.header,i=n.frameCount??e.frames.length;if(!Number.isInteger(i)||i<0)throw new D(`Invalid SER frame count: ${i}`);if(!Number.isInteger(n.width)||n.width<=0)throw new D(`Invalid SER width: ${n.width}`);if(!Number.isInteger(n.height)||n.height<=0)throw new D(`Invalid SER height: ${n.height}`);if(!Number.isInteger(n.pixelDepth)||n.pixelDepth<1||n.pixelDepth>16)throw new D(`Invalid SER pixel depth: ${n.pixelDepth}`);let o=Te[n.colorId];if(!o)throw new D(`Unsupported SER color ID: ${n.colorId}`);if(e.frames.length!==i){let g=`SER frame array length mismatch: header frameCount=${i}, frames=${e.frames.length}`;if(r.strictValidation)throw new D(g);Cr(r,"frame_count_mismatch",g);}let s=n.pixelDepth<=8?1:2,c=n.width*n.height*o*s;if(!Number.isSafeInteger(c)||c<=0)throw new D(`Invalid computed frame length: ${c}`);let a=[];for(let g=0;g<i;g++){let y=e.frames[g]??new Uint8Array(0);a.push(Ca(y,c,r,g));}let u;if(e.timestamps){if(e.timestamps.length!==i){let g=`Timestamp count mismatch: expected ${i}, got ${e.timestamps.length}`;if(r.strictValidation)throw new D(g);Cr(r,"timestamp_count_mismatch",g);}u=new Array(i);for(let g=0;g<i;g++)u[g]=Rr(e.timestamps[g],0n);}let f=i*c,l=u?i*8:0,m=178+f+l,d=new Uint8Array(m),p=new DataView(d.buffer);Tt(d,0,14,nt),p.setInt32(14,n.luId??0,true),p.setInt32(18,n.colorId,true);let h=n.littleEndian??true;p.setInt32(22,Ra(h,r.endiannessPolicy),true),p.setInt32(26,n.width,true),p.setInt32(30,n.height,true),p.setInt32(34,n.pixelDepth,true),p.setInt32(38,i,true),Tt(d,42,40,n.observer??""),Tt(d,82,40,n.instrument??""),Tt(d,122,40,n.telescope??""),p.setBigUint64(162,Rr(n.startTime,0n),true),p.setBigUint64(170,Rr(n.startTimeUtc,0n),true);let b=178;for(let g of a)d.set(g,b),b+=c;if(u)for(let g=0;g<u.length;g++)p.setBigUint64(b+g*8,u[g],true);return d.buffer}var fi="SERCOLOR",mi="SERPDEP",Nr="SERFRMS",di="SERCHANS",Ua="SERCHORD",pi="SERLUID",hi="SERBYORD",gi="SEROBS",bi="SERINST",yi="SERTEL",Si="SERSTRT",wi="SERSTUTC",Na="SERCFAP",Ii="SERFRAME",Ai="SER_TSTP",xi=32768;function Ut(e){return e?.strictValidation??e?.relaxed!==true}function Fi(e){return e instanceof ArrayBuffer?Promise.resolve(e):e.arrayBuffer()}function Ei(e,t){return e instanceof Pe?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(Pe.fromArrayBuffer(e,{strictValidation:Ut(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})):Pe.fromBlob(e,{strictValidation:Ut(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})}function Ba(e){return e instanceof j?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(j.fromArrayBuffer(e)):Fi(e).then(t=>j.fromArrayBuffer(t))}function Se(e){if(typeof e=="bigint")return e;if(typeof e=="number"&&Number.isFinite(e))return BigInt(Math.trunc(e));if(typeof e=="string"){let t=e.trim();if(!t)return null;try{return BigInt(t)}catch{return null}}return null}function va(e,t){return e.metadata.find(r=>r.id===t)}function ka(e,t){return e.properties.find(r=>r.id===t)}function fe(e,t,r){let n=ka(t,r);return n?.value!==void 0?n.value:va(e,r)?.value}function La(e,t,r){let n=fe(e,t,r);if(!n)return [];if(ArrayBuffer.isView(n)){let i=n,o=[];for(let s=0;s<i.length;s++)o.push(BigInt(i[s]));return o}return Array.isArray(n)?n.map(i=>Se(i)).filter(i=>i!==null):[]}function Br(e,t,r){e?.onWarning?.({code:t,message:r});}function Da(e,t){let r=t.getHeader(),n=[...e];n.push({id:"SER:ColorID",type:"Int32",value:r.colorId}),n.push({id:"SER:PixelDepth",type:"Int32",value:r.pixelDepth}),n.push({id:"SER:FrameCount",type:"Int32",value:r.frameCount}),n.push({id:"SER:ChannelCount",type:"Int32",value:r.channelCount}),n.push({id:"SER:LittleEndian",type:"Boolean",value:r.byteOrder==="little"}),n.push({id:"SER:LuID",type:"Int32",value:r.luId}),n.push({id:"SER:Observer",type:"String",value:r.observer}),n.push({id:"SER:Instrument",type:"String",value:r.instrument}),n.push({id:"SER:Telescope",type:"String",value:r.telescope}),n.push({id:"SER:StartTime",type:"String",value:r.startTime.toString()}),n.push({id:"SER:StartTimeUTC",type:"String",value:r.startTimeUtc.toString()});let i=t.parsed.timestamps;if(i.length>0){let o=new BigUint64Array(i.length);for(let s=0;s<i.length;s++)o[s]=i[s];n.push({id:"SER:FrameTimestamps",type:"UI64Vector",value:o,dataBlock:{location:{type:"attachment",position:0,size:o.byteLength},byteOrder:"little"}});}return n}function Oa(e){if(e.samples instanceof Uint8Array)return e.samples;let t=new Uint8Array(e.samples.length);for(let r=0;r<e.samples.length;r++)t[r]=Number(e.samples[r]??0)&255;return t}function Ma(e){if(e.samples instanceof Uint16Array)return e.samples;let t=new Uint16Array(e.samples.length);for(let r=0;r<e.samples.length;r++)t[r]=Number(e.samples[r]??0);return t}function Xa(e){let t=new Uint8Array(e.length*8),r=new DataView(t.buffer);for(let n=0;n<e.length;n++)r.setBigInt64(n*8,BigInt(e[n]),false);return {cards:[{key:"XTENSION",value:"BINTABLE",comment:"Binary table extension"},{key:"BITPIX",value:8,comment:"8-bit bytes"},{key:"NAXIS",value:2,comment:"Table axes"},{key:"NAXIS1",value:8,comment:"Bytes per row"},{key:"NAXIS2",value:e.length,comment:"Rows"},{key:"PCOUNT",value:0},{key:"GCOUNT",value:1},{key:"TFIELDS",value:1},{key:"TTYPE1",value:"TIMESTAMP"},{key:"TFORM1",value:"1K"},{key:"EXTNAME",value:Ai}],data:t}}function _a(e){if(e.channelCount===3)return 100;let t=e.colorFilterArray?.pattern;if(!t)return 0;let r=Object.entries(He).find(([,n])=>n===t);return r?Number(r[0]):0}function ai(e,t){let r=e.get(t);return Se(r)??void 0}function Rt(e,t){let r=e.get(t);if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"&&r.trim()!==""){let n=Number(r);if(Number.isFinite(n))return n}}function Ct(e,t){let r=e.get(t);return typeof r=="string"?r:void 0}function Ha(e){let t=e.getHeader(),r=He[t.colorId];return [{key:fi,value:t.colorId},{key:mi,value:t.pixelDepth},{key:Nr,value:t.frameCount},{key:di,value:t.channelCount},{key:Ua,value:t.colorId===101?"BGR":"RGB"},{key:pi,value:t.luId},{key:hi,value:t.byteOrder},{key:gi,value:t.observer},{key:bi,value:t.instrument},{key:yi,value:t.telescope},{key:Si,value:t.startTime.toString()},{key:wi,value:t.startTimeUtc.toString()},...r?[{key:Na,value:r}]:[]]}function ci(e){let t=[];if(e.channelCount===1){for(let n=0;n<e.samples.length;n++)t.push(Number(e.samples[n]??0));return t}let r=e.width*e.height;for(let n=0;n<3;n++)for(let i=0;i<r;i++)t.push(Number(e.samples[i*3+n]??0));return t}function ui(e){return e.map(t=>t-xi)}function $a(e){return e.hdus.filter(t=>t.data instanceof ee).map(t=>({header:t.header,image:t.data}))}function Va(e,t,r){if(e?.sourceLayout==="cube"||e?.sourceLayout==="multi-hdu")return e.sourceLayout;if(t.length<=1)return "cube";if(t.some(({header:s})=>{let c=s.getString("EXTNAME","").trim().toUpperCase();return s.contains(Ii)||c.startsWith("SER_FRAME_")||c==="SER_FRAME"})||r!==void 0&&(t.length===r||t.length===r*3))return "multi-hdu";let i=t[0];return t.every(s=>s.image.width===i.image.width&&s.image.height===i.image.height&&s.image.bitpix===i.image.bitpix)?"multi-hdu":"cube"}function Wa(e,t,r){let n=e[0]?.image;if(!n)return e;let i=e.filter((o,s)=>{if(o.image.width===n.width&&o.image.height===n.height&&o.image.bitpix===n.bitpix)return true;let a=`Skipping incompatible image HDU #${s} (${o.image.width}x${o.image.height}, BITPIX=${o.image.bitpix}); expected ${n.width}x${n.height}, BITPIX=${n.bitpix}`;if(t)throw new H(a);return Br(r,"fits_multi_hdu_incompatible",a),false});if(i.length===0)throw new H("No compatible image HDUs available for multi-HDU FITS conversion");return i}async function Ur(e,t,r,n){let i=e.width*e.height,o=new Uint8Array(i*r),s=await e.getFrame(t);if(r===1){for(let a=0;a<i;a++)o[a]=Number(s[a]??0)&255;return o}let c=new DataView(o.buffer);for(let a=0;a<i;a++)c.setUint16(a*2,Number(s[a]??0),n);return o}async function li(e,t,r,n){let i=e.width*e.height,o=new Uint8Array(i*3*r),s=await Promise.all([e.getFrame(t*3),e.getFrame(t*3+1),e.getFrame(t*3+2)]);if(r===1){for(let a=0;a<i;a++)o[a*3]=Number(s[0][a]??0)&255,o[a*3+1]=Number(s[1][a]??0)&255,o[a*3+2]=Number(s[2][a]??0)&255;return o}let c=new DataView(o.buffer);for(let a=0;a<i;a++)c.setUint16(a*6,Number(s[0][a]??0),n),c.setUint16(a*6+2,Number(s[1][a]??0),n),c.setUint16(a*6+4,Number(s[2][a]??0),n);return o}async function za(e,t,r,n,i){let o=e.width*e.height,s=new Uint8Array(o*3*n),[c,a,u]=await Promise.all([e.getFrame(0),t.getFrame(0),r.getFrame(0)]);if(n===1){for(let l=0;l<o;l++)s[l*3]=Number(c[l]??0)&255,s[l*3+1]=Number(a[l]??0)&255,s[l*3+2]=Number(u[l]??0)&255;return s}let f=new DataView(s.buffer);for(let l=0;l<o;l++)f.setUint16(l*6,Number(c[l]??0),i),f.setUint16(l*6+2,Number(a[l]??0),i),f.setUint16(l*6+4,Number(u[l]??0),i);return s}async function Ga(e,t){let r=await Ei(e,t),n=r.getHeader(),i=n.frameCount,o=Ha(r),s=t?.layout??"cube",c=n.bytesPerSample===1?8:16,a=c===16?xi:void 0,u=[];if(s==="multi-hdu")for(let f=0;f<i;f++){let l=r.getFrame(f),m=ci(l),d=c===16?ui(m):m,p=G(d,c);u.push(oe({primary:f===0,extensionType:"IMAGE",width:n.width,height:n.height,depth:n.channelCount===3?3:void 0,bitpix:c,bzero:a,bscale:a!==void 0?1:void 0,data:p,extname:f===0?void 0:`SER_FRAME_${f}`,additionalCards:f===0?o:[{key:Ii,value:f},{key:Nr,value:i},{key:di,value:n.channelCount}]}));}else {let f=n.channelCount===1?i:i*3,l=[];for(let d=0;d<i;d++){let p=r.getFrame(d),h=ci(p),b=c===16?ui(h):h;l.push(...b);}let m=G(l,c);u.push(oe({width:n.width,height:n.height,depth:f,bitpix:c,bzero:a,bscale:a!==void 0?1:void 0,data:m,additionalCards:o}));}return (t?.includeTimestampExtension??true)&&r.parsed.timestamps.length===i&&u.push(Xa(r.parsed.timestamps)),ie(u)}async function ja(e,t){let r=Ut(t),n=await Ba(e),i=$a(n),o=i[0];if(!o)throw new H("No FITS image HDU found for SER conversion");let s=o.header,c=o.image,a=Rt(s,fi)??0,u=Te[a]??1,f=Rt(s,mi);if(!f)if(c.bitpix===8)f=8;else if(c.bitpix===16)f=16;else throw new H(`Cannot infer SER pixel depth from FITS BITPIX=${c.bitpix}; metadata is missing`);let l=Rt(s,Nr),m=Va(t,i,l),d=f<=8?1:2,p=m==="multi-hdu"?Wa(i,r,t):i,h=(Ct(s,hi)??"little")!=="big",b=Ct(s,gi)??"",g=Ct(s,bi)??"",y=Ct(s,yi)??"",w=Rt(s,pi)??0,S=ai(s,Si)??0n,I=ai(s,wi)??S,A=[],x=l??0;if(m==="cube")if(u===1){x=l??c.depth;for(let C=0;C<x;C++)A.push(await Ur(c,C,d,h));}else {if(x=l??c.depth,!l)if(c.depth%3!==0){if(r)throw new H(`FITS depth ${c.depth} is not divisible by 3 for RGB/BGR SER reconstruction`);x=Math.floor(c.depth/3);}else x=c.depth/3;for(let C=0;C<x;C++)A.push(await li(c,C,d,h));}else {if(u===1)for(let C of p)if(C.image.depth>1)for(let $=0;$<C.image.depth;$++)A.push(await Ur(C.image,$,d,h));else A.push(await Ur(C.image,0,d,h));else {let C=p.every(U=>U.image.depth===3),$=p.every(U=>U.image.depth===1);if(C)for(let U of p)A.push(await li(U.image,0,d,h));else if($){let U=p.length;if(U%3!==0){let k=`RGB/BGR multi-HDU layout has ${U} channels; expected multiple of 3`;if(r)throw new H(k);Br(t,"fits_multi_hdu_rgb_tail_drop",k),U-=U%3;}for(let k=0;k+2<U;k+=3)A.push(await za(p[k].image,p[k+1].image,p[k+2].image,d,h));}else throw new H("Cannot decode RGB/BGR sequence from multi-HDU FITS layout; expected depth=3 per HDU or HDU triplets")}x=A.length;}let E,L=n.hdus.find(C=>C.data instanceof q&&C.header.getString("EXTNAME","").trim().toUpperCase()===Ai);if(L&&L.data instanceof q){let C=L.data.columns?.[0];if(C&&(E=(await L.data.getColumn(C)).map(U=>Se(U)).filter(U=>U!==null),E.length!==x)){if(r)throw new H(`SER timestamp extension row count mismatch: expected ${x}, got ${E.length}`);E=E.slice(0,x);}}return Pt({header:{colorId:a,width:c.width,height:c.height,pixelDepth:f,frameCount:x,littleEndian:h,luId:w,observer:b,instrument:g,telescope:y,startTime:S,startTimeUtc:I},frames:A,timestamps:E},{strictValidation:r,endiannessPolicy:t?.endiannessPolicy==="spec"?"spec":"compat",onWarning:t?.onWarning})}function Ka(e){return e===1?"UInt8":"UInt16"}function Ya(e){let t=e.getHeader(),r=t.frameCount,i=t.width*t.height*t.channelCount*r;if(t.bytesPerSample===1){let a=new Uint8Array(i),u=0;for(let f=0;f<r;f++){let l=e.getFrame(f),m=Oa(l);a.set(m,u),u+=m.length;}return a}let o=new Uint8Array(i*2),s=new DataView(o.buffer),c=0;for(let a=0;a<r;a++){let u=e.getFrame(a),f=Ma(u);for(let l=0;l<f.length;l++)s.setUint16(c*2,f[l],true),c++;}return o}async function Za(e,t){let r=await Ei(e,t),n=r.getHeader(),i=Ya(r),o={id:"SER_SEQUENCE",geometry:[n.width,n.height,n.frameCount],channelCount:n.channelCount,sampleFormat:Ka(n.bytesPerSample),pixelStorage:n.channelCount===3?"Normal":"Planar",colorSpace:n.channelCount===3?"RGB":"Gray",dataBlock:{location:{type:"attachment",position:0,size:i.byteLength},byteOrder:"little"},data:i,properties:[],tables:[],fitsKeywords:[]},s=He[n.colorId];s&&(o.colorFilterArray={pattern:s,width:2,height:2});let c=[{id:"XISF:CreatorApplication",type:"String",value:"fitsjs-ng SER conversion"},{id:"XISF:CreationTime",type:"TimePoint",value:new Date().toISOString()}];c=Da(c,r);let a={metadata:c,images:[o],standaloneProperties:[],standaloneTables:[],version:"1.0",signature:{present:false,verified:true}};return t?.distributed?ne.toDistributed(a,t.writeOptions):ne.toMonolithic(a,t?.writeOptions)}function qa(e){if(!e.data)throw new H("XISF image data is not decoded");return e.data}function Ja(e,t,r,n){let i=e.geometry[0]??0,o=e.geometry[1]??0,s=i*o,c=e.sampleFormat==="UInt16"?2:1,a=s*r*c,u=qa(e),f=s*r*t*c;if(u.byteLength<f)throw new H(`XISF image payload too short for SER conversion: expected at least ${f} bytes, got ${u.byteLength}`);let l=new DataView(u.buffer,u.byteOffset,u.byteLength),m=e.dataBlock.byteOrder!=="big",d=[];if(c===1){if(r===1)for(let h=0;h<t;h++){let b=new Uint8Array(a),g=h*s;b.set(u.subarray(g,g+s)),d.push(b);}else if(e.pixelStorage==="Normal")for(let h=0;h<t;h++){let b=new Uint8Array(a),g=h*s*r;b.set(u.subarray(g,g+s*r)),d.push(b);}else {let h=s*t;for(let b=0;b<t;b++){let g=new Uint8Array(a);for(let y=0;y<s;y++)g[y*3]=u[b*s+y]??0,g[y*3+1]=u[h+b*s+y]??0,g[y*3+2]=u[h*2+b*s+y]??0;d.push(g);}}return d}if(r===1){for(let h=0;h<t;h++){let b=new Uint8Array(a),g=new DataView(b.buffer);for(let y=0;y<s;y++){let w=l.getUint16((h*s+y)*2,m);g.setUint16(y*2,w,n);}d.push(b);}return d}if(e.pixelStorage==="Normal"){for(let h=0;h<t;h++){let b=new Uint8Array(a),g=new DataView(b.buffer);for(let y=0;y<s;y++){let w=(h*s*r+y*r)*2,S=y*r*2;g.setUint16(S,l.getUint16(w,m),n),g.setUint16(S+2,l.getUint16(w+2,m),n),g.setUint16(S+4,l.getUint16(w+4,m),n);}d.push(b);}return d}let p=s*t;for(let h=0;h<t;h++){let b=new Uint8Array(a),g=new DataView(b.buffer);for(let y=0;y<s;y++){let w=l.getUint16((h*s+y)*2,m),S=l.getUint16((p+h*s+y)*2,m),I=l.getUint16((p*2+h*s+y)*2,m),A=y*6;g.setUint16(A,w,n),g.setUint16(A+2,S,n),g.setUint16(A+4,I,n);}d.push(b);}return d}async function Qa(e,t){let r=Ut(t),n=e instanceof J?e:await J.fromArrayBuffer(await Fi(e),{strictValidation:r,decodeImageData:true}),i=t?.imageIndex??0;if(!Number.isInteger(i)||i<0)throw new H(`XISF image index must be a non-negative integer, got ${i}`);let o=n.unit.images[i];if(!o)throw new H(`No XISF image available at index ${i}`);if(o.sampleFormat!=="UInt8"&&o.sampleFormat!=="UInt16")throw new H(`Unsupported XISF sample format for SER conversion: ${o.sampleFormat}`);let s=o.geometry[0]??0,c=o.geometry[1]??0;if(!s||!c)throw new H("XISF image must have width and height geometry");let a=fe(n.unit,o,"SER:ColorID"),u=Se(a)??BigInt(_a(o)),f=Number(u),l=Te[f]??(o.channelCount===3?3:1),m=o.geometry[2]??1,d=fe(n.unit,o,"SER:PixelDepth"),p=Number(Se(d)??(o.sampleFormat==="UInt8"?8n:16n))||8,h=fe(n.unit,o,"SER:LittleEndian"),b=typeof h=="boolean"?h:String(h??"true").toLowerCase()!=="false",g=Ja(o,m,l,b),y=La(n.unit,o,"SER:FrameTimestamps");if(y.length>0&&y.length!==m){if(r)throw new H(`XISF SER:FrameTimestamps length mismatch: expected ${m}, got ${y.length}`);Br(t,"xisf_timestamp_length_mismatch",`SER:FrameTimestamps length mismatch: expected ${m}, got ${y.length}; truncating`),y=y.slice(0,m);}let w=Number(Se(fe(n.unit,o,"SER:LuID"))??0n),S=String(fe(n.unit,o,"SER:Observer")??""),I=String(fe(n.unit,o,"SER:Instrument")??""),A=String(fe(n.unit,o,"SER:Telescope")??""),x=Se(fe(n.unit,o,"SER:StartTime"))??0n,E=Se(fe(n.unit,o,"SER:StartTimeUTC"))??x;return Pt({header:{colorId:f,width:s,height:c,pixelDepth:p,frameCount:m,littleEndian:b,luId:w,observer:S,instrument:I,telescope:A,startTime:x,startTimeUtc:E},frames:g,timestamps:y.length>0?y:void 0},{strictValidation:r,endiannessPolicy:t?.endiannessPolicy==="spec"?"spec":"compat",onWarning:t?.onWarning})}var ec={fits:"fits",png:"png",jpeg:"jpg"};function vr(e){return ec[e]}function Ti(e){let t=e.toLowerCase();return t==="fits"?"fits":t==="png"?"png":t==="jpg"||t==="jpeg"?"jpeg":null}function Pi(e){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid ipix: ${e}`);return Math.floor(e/1e4)*1e4}function Nt(e){if(e.spectralOrder!==void 0||e.spectralIndex!==void 0){let t=e.spectralOrder??0,r=e.spectralIndex??0,n=`${Pi(e.ipix)}_${Math.floor(r/10)*10}`;return `Norder${e.order}_${t}/Dir${n}/Npix${e.ipix}_${r}.${vr(e.format)}`}return `Norder${e.order}/Dir${Pi(e.ipix)}/Npix${e.ipix}.${vr(e.format)}`}function Bt(e){return `Norder3/Allsky.${vr(e)}`}function kr(e){let t=e.replaceAll("\\","/"),r=/^Norder(\d+)_(\d+)\/Dir(\d+)_(\d+)\/Npix(\d+)_(\d+)\.(\w+)$/i.exec(t);if(r){let o=Ti(r[7]);return o?{order:Number(r[1]),spectralOrder:Number(r[2]),ipix:Number(r[5]),spectralIndex:Number(r[6]),frame:"equatorial",format:o}:null}let n=/^Norder(\d+)\/Dir(\d+)\/Npix(\d+)\.(\w+)$/i.exec(t);if(!n)return null;let i=Ti(n[4]);return i?{order:Number(n[1]),ipix:Number(n[3]),frame:"equatorial",format:i}:null}var tc=["creator_did","obs_title","dataproduct_type","hips_version","hips_frame","hips_order","hips_tile_width","hips_tile_format"],rc=["hips_cube_depth","hips_cube_firstframe"],nc=new Set(["equatorial","galactic","ecliptic"]),ic=new Set(["image","cube"]),oc=new Set(["fits","png","jpeg"]);function Ri(e){return e.trim()}var Ve=class e{data=new Map;constructor(t){if(t)for(let[r,n]of Object.entries(t))this.data.set(r.trim(),Ri(n));}static parse(t){let r={};for(let n of t.split(/\r?\n/u)){let i=n.trim();if(!i||i.startsWith("#"))continue;let o=i.indexOf("=");if(o<=0)continue;let s=i.slice(0,o).trim(),c=i.slice(o+1).trim();r[s]=c;}return new e(r)}static fromObject(t){let r={};for(let[n,i]of Object.entries(t))r[n]=typeof i=="string"?i:String(i);return new e(r)}get(t){return this.data.get(t)}set(t,r){return this.data.set(t,typeof r=="string"?Ri(r):String(r)),this}has(t){return this.data.has(t)}delete(t){return this.data.delete(t)}keys(){return [...this.data.keys()]}toObject(){return Object.fromEntries(this.data.entries())}merge(t){for(let[r,n]of Object.entries(t))this.set(r,n);return this}toString(){return [...this.data.entries()].sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${r.padEnd(20," ")} = ${n}`).join(`
4
+ `)+`
5
+ `}validate(){let t=tc.filter(l=>!this.data.has(l)),r=[],n=[],i=this.get("hips_frame");i&&!nc.has(i)&&r.push(`hips_frame=${i}`);let o=this.get("dataproduct_type");o&&!ic.has(o)&&r.push(`dataproduct_type=${o}`);let s=this.get("hips_tile_format");if(s){let l=s.split(/[,\s]+/u).map(m=>m.trim().toLowerCase()).filter(Boolean);(l.length===0||l.some(m=>!oc.has(m)))&&r.push(`hips_tile_format=${s}`),l.includes("jpg")&&n.push("hips_tile_format contains jpg alias; prefer jpeg");}let c=Number(this.get("hips_order"));this.has("hips_order")&&(!Number.isInteger(c)||c<0)&&r.push(`hips_order=${this.get("hips_order")}`);let a=Number(this.get("hips_tile_width"));this.has("hips_tile_width")&&(!Number.isInteger(a)||a<=0)?r.push(`hips_tile_width=${this.get("hips_tile_width")}`):this.has("hips_tile_width")&&Number.isInteger(a)&&(a&a-1)!==0&&n.push(`hips_tile_width=${a} is not a power of two`);let u=this.get("hips_order_min");if(u!==void 0){let l=Number(u);!Number.isInteger(l)||l<0?r.push(`hips_order_min=${u}`):Number.isInteger(c)&&l>c&&r.push(`hips_order_min=${u} exceeds hips_order=${c}`);}let f=this.get("hips_version");if(f&&!/^\d+(\.\d+){0,2}$/u.test(f)&&n.push(`hips_version=${f} is not in expected numeric dotted form`),o==="cube"){for(let d of rc)this.has(d)||t.push(d);let l=Number(this.get("hips_cube_depth"));this.has("hips_cube_depth")&&(!Number.isInteger(l)||l<=0)&&r.push(`hips_cube_depth=${this.get("hips_cube_depth")}`);let m=Number(this.get("hips_cube_firstframe"));this.has("hips_cube_firstframe")&&(!Number.isInteger(m)||m<0)&&r.push(`hips_cube_firstframe=${this.get("hips_cube_firstframe")}`);}else this.has("hips_cube_depth")&&n.push("hips_cube_depth is set but dataproduct_type is not cube"),this.has("hips_cube_firstframe")&&n.push("hips_cube_firstframe is set but dataproduct_type is not cube");return {ok:t.length===0&&r.length===0,missing:[...t],invalid:r,warnings:n}}withCompatibilityFields(){let t=this.get("hips_frame"),r=this.get("hips_order"),n=this.get("hips_tile_format");return t&&this.set("coordsys",t),r&&this.set("maxOrder",r),n&&this.set("format",n),this}};function Ci(e){let t=Ve.fromObject({creator_did:e.creatorDid,obs_title:e.obsTitle,dataproduct_type:e.dataproductType??"image",hips_version:e.version??"1.4",hips_frame:e.frame??"equatorial",hips_order:e.order,hips_tile_width:e.tileWidth,hips_tile_format:e.formats.join(" ")});return e.extras&&t.merge(e.extras),t.withCompatibilityFields(),t}function uc(e){let t=e%360;return t<0?t+360:t}function lc(e,t,r){return Math.max(t,Math.min(r,e))}function fc(e){return e==="galactic"?{ctype1:"GLON-HPX",ctype2:"GLAT-HPX"}:e==="ecliptic"?{ctype1:"ELON-HPX",ctype2:"ELAT-HPX"}:{ctype1:"RA---HPX",ctype2:"DEC--HPX"}}function vt(e){let t=e.crpix1,r=e.crpix2,n=e.crval1,i=e.crval2,o=e.cd11,s=e.cd12,c=e.cd21,a=e.cd22;if(![o,s,c,a].every(h=>typeof h=="number"&&Number.isFinite(h))){let h=Number.isFinite(e.cdelt1)?e.cdelt1:-1,b=Number.isFinite(e.cdelt2)?e.cdelt2:1,g=(e.crota2??0)*Math.PI/180,y=Math.cos(g),w=Math.sin(g);o=h*y,s=-b*w,c=h*w,a=b*y;}let f=o*a-s*c;if(Math.abs(f)<1e-16)throw new Error("WCS matrix is singular");let l=a/f,m=-s/f,d=-c/f,p=o/f;return {definition:e,pixelToWorld(h,b){let g=h+1-t,y=b+1-r;return {lon:uc(n+o*g+s*y),lat:lc(i+c*g+a*y,-90,90)}},worldToPixel(h,b){let g=(h-n+540)%360-180,y=b-i,w=l*g+m*y,S=d*g+p*y;return {x:w+t-1,y:S+r-1}}}}function Ui(e){return vt({ctype1:e.getString("CTYPE1","RA---CAR"),ctype2:e.getString("CTYPE2","DEC--CAR"),crpix1:e.getNumber("CRPIX1",1),crpix2:e.getNumber("CRPIX2",1),crval1:e.getNumber("CRVAL1",0),crval2:e.getNumber("CRVAL2",0),cd11:e.getNumber("CD1_1",Number.NaN),cd12:e.getNumber("CD1_2",Number.NaN),cd21:e.getNumber("CD2_1",Number.NaN),cd22:e.getNumber("CD2_2",Number.NaN),cdelt1:e.getNumber("CDELT1",Number.NaN),cdelt2:e.getNumber("CDELT2",Number.NaN),crota2:e.getNumber("CROTA2",0)})}function Ni(e){let t=(n,i)=>{let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""){let s=Number(o);if(Number.isFinite(s))return s}return i},r=(n,i)=>{let o=e[n];return typeof o=="string"?o:i};return vt({ctype1:r("CTYPE1","RA---TAN"),ctype2:r("CTYPE2","DEC--TAN"),crpix1:t("CRPIX1",1),crpix2:t("CRPIX2",1),crval1:t("CRVAL1",0),crval2:t("CRVAL2",0),cd11:t("CD1_1",Number.NaN),cd12:t("CD1_2",Number.NaN),cd21:t("CD2_1",Number.NaN),cd22:t("CD2_2",Number.NaN),cdelt1:t("CDELT1",Number.NaN),cdelt2:t("CDELT2",Number.NaN),crota2:t("CROTA2",0)})}function Bi(e,t,r){let n=Math.max(e,t),i=Math.max(0,Math.ceil(Math.log2(Math.max(1,n/r))));return Math.min(i,13)}function vi(e,t,r,n){let i=healpix.order2nside(e.order),o=(t+.5)/n,s=(r+.5)/n,[c,a,u]=healpix.pixcoord2vec_nest(i,e.ipix,o,s),{theta:f,phi:l}=healpix.vec2ang([c,a,u]);return {lon:l*180/Math.PI,lat:90-f*180/Math.PI}}function mc(e){let t=healpix.order2nside(e.order),{theta:r,phi:n}=healpix.pix2ang_nest(t,e.ipix);return {lon:n*180/Math.PI,lat:90-r*180/Math.PI}}function ki(e,t,r=1){let n=healpix.order2nside(e.order),{ctype1:i,ctype2:o}=fc(e.frame),s=45/t/n,c=mc(e),a=[{key:"CTYPE1",value:i},{key:"CTYPE2",value:o},{key:"CRPIX1",value:t/2+.5},{key:"CRPIX2",value:t/2+.5},{key:"CRVAL1",value:c.lon},{key:"CRVAL2",value:c.lat},{key:"CD1_1",value:-s},{key:"CD1_2",value:0},{key:"CD2_1",value:0},{key:"CD2_2",value:s},{key:"ORDER",value:e.order},{key:"NPIX",value:e.ipix},{key:"NSIDE",value:n},{key:"ORDERING",value:"NESTED"}];return e.spectralOrder!==void 0&&a.push({key:"FORDER",value:e.spectralOrder}),e.spectralIndex!==void 0&&a.push({key:"FPIX",value:e.spectralIndex}),r>1&&a.push({key:"NAXIS3",value:r}),a}function bc(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let i=e[n];Number.isFinite(i)&&(i<t&&(t=i),i>r&&(r=i));}return !Number.isFinite(t)||!Number.isFinite(r)?[0,1]:t===r?[t,t+1]:[t,r]}function yc(e){let[t,r]=bc(e),n=r===t?0:255/(r-t),i=new Uint8Array(e.length);for(let o=0;o<e.length;o++){let s=e[o];if(!Number.isFinite(s)){i[o]=0;continue}let c=Math.max(0,Math.min(255,Math.round((s-t)*n)));i[o]=c;}return i}function Sc(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function wc(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function Li(e,t,r,n){let i=new Float32Array(t*r);if(n===1){for(let o=0;o<i.length;o++)i[o]=e[o]??0;return i}for(let o=0;o<i.length;o++){let s=o*n,c=e[s]??0,a=e[s+1]??c,u=e[s+2]??c;i[o]=.299*c+.587*a+.114*u;}return i}async function Di(e,t){let r=Sc(t);if(e.format==="fits"){let s=j.fromArrayBuffer(wc(r)).getDataUnit();if(!(s instanceof ee))throw new Error("FITS tile does not contain image data");let c=[],a=s.depth;for(let l=0;l<a;l++)c.push(await s.getFrame(l));let u=s.width*s.height,f=new Float32Array(u*a);for(let l=0;l<a;l++){let m=c[l];for(let d=0;d<u;d++)f[l*u+d]=Number(m[d]??Number.NaN);}return {meta:e,width:s.width,height:s.height,depth:a,data:f}}if(e.format==="png"){let o=fastPng.decode(r),s=Li(o.data,o.width,o.height,o.channels);return {meta:e,width:o.width,height:o.height,depth:1,data:s}}let n=jpegJs.decode(r,{useTArray:true,formatAsRGBA:true}),i=Li(n.data,n.width,n.height,4);return {meta:e,width:n.width,height:n.height,depth:1,data:i}}function ot(e,t,r,n){let i=r*r;if(t.length!==i*n)throw new Error(`Tile pixel length mismatch: got=${t.length} expected=${i*n}`);if(e.format==="fits"){let a=G(t,-32),u=ki(e,r,n),f=oe({primary:true,width:r,height:r,depth:n,bitpix:-32,data:a,additionalCards:u});return new Uint8Array(ie([f]))}let o=yc(t.subarray(0,i));if(e.format==="png")return fastPng.encode({width:r,height:r,depth:8,channels:1,data:o});let s=new Uint8Array(r*r*4);for(let a=0;a<o.length;a++){let u=o[a],f=a*4;s[f]=u,s[f+1]=u,s[f+2]=u,s[f+3]=255;}let c=jpegJs.encode({width:r,height:r,data:s},90);return new Uint8Array(c.data)}function kt(e){return /^https?:\/\//iu.test(e)}async function Lt(){let[e,t]=await Promise.all([W("fs/promises","HiPS local-path access","Use URL-based HiPS input or provide a custom HiPSExportTarget in browser/React Native."),W("path","HiPS local-path access","Use URL-based HiPS input or provide a custom HiPSExportTarget in browser/React Native.")]);return {fs:e,path:t}}var pe=class e{cachedProperties;source;constructor(t){this.source=t;}static async open(t){let r=new e(t);return await r.getProperties(),r}async readText(t){if(typeof this.source=="object"&&this.source!==null){if("readText"in this.source&&typeof this.source.readText=="function")return this.source.readText(t);if("root"in this.source){let r=this.source.root;if(kt(r)){let o=await fetch(new URL(t,`${r.replace(/\/+$/u,"")}/`).toString());if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status}`);return o.text()}let{fs:n,path:i}=await Lt();return n.readFile(i.join(r,t),"utf8")}}if(typeof this.source=="string"){if(kt(this.source)){let i=await fetch(new URL(t,`${this.source.replace(/\/+$/u,"")}/`).toString());if(!i.ok)throw new Error(`Failed to fetch ${t}: ${i.status}`);return i.text()}let{fs:r,path:n}=await Lt();return r.readFile(n.join(this.source,t),"utf8")}if(this.source instanceof URL){let r=await fetch(new URL(t,`${this.source.toString().replace(/\/+$/u,"")}/`).toString());if(!r.ok)throw new Error(`Failed to fetch ${t}: ${r.status}`);return r.text()}throw new Error("Unsupported HiPS source for text read")}async readBinary(t){if(typeof this.source=="object"&&this.source!==null){if("readBinary"in this.source&&typeof this.source.readBinary=="function")return this.source.readBinary(t);if("root"in this.source){let r=this.source.root;if(kt(r)){let s=await fetch(new URL(t,`${r.replace(/\/+$/u,"")}/`).toString());if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status}`);return new Uint8Array(await s.arrayBuffer())}let{fs:n,path:i}=await Lt(),o=await n.readFile(i.join(r,t));return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}}if(typeof this.source=="string"){if(kt(this.source)){let o=await fetch(new URL(t,`${this.source.replace(/\/+$/u,"")}/`).toString());if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status}`);return new Uint8Array(await o.arrayBuffer())}let{fs:r,path:n}=await Lt(),i=await r.readFile(n.join(this.source,t));return new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}if(this.source instanceof URL){let r=await fetch(new URL(t,`${this.source.toString().replace(/\/+$/u,"")}/`).toString());if(!r.ok)throw new Error(`Failed to fetch ${t}: ${r.status}`);return new Uint8Array(await r.arrayBuffer())}throw new Error("Unsupported HiPS source for binary read")}async getProperties(){if(!this.cachedProperties){let t=typeof this.source=="object"&&this.source!==null&&"propertiesPath"in this.source?this.source.propertiesPath??"properties":"properties",r=await this.readText(t);this.cachedProperties=Ve.parse(r);}return this.cachedProperties}async tileFormats(){let n=((await this.getProperties()).get("hips_tile_format")??"fits").split(/\s+/u).map(o=>o.trim().toLowerCase()).filter(Boolean),i=[];for(let o of n)(o==="fits"||o==="png"||o==="jpeg"||o==="jpg")&&i.push(o==="jpg"?"jpeg":o);return i.length>0?i:["fits"]}async readTile(t){let r=await this.getProperties(),n=t.frame??r.get("hips_frame")??"equatorial",i=t.format?[t.format]:await this.tileFormats(),o;for(let s of i)try{let c={...t,frame:n,format:s},a=await this.readBinary(Nt(c));return Di(c,a)}catch(c){o=c;}throw new Error(`Unable to read HiPS tile order=${t.order} ipix=${t.ipix}: ${String(o)}`)}async readAllsky(t){let r=t?[t]:await this.tileFormats(),n;for(let i of r)try{return await this.readBinary(Bt(i))}catch(o){n=o;}throw new Error(`Allsky not found: ${String(n)}`)}async exportProperties(t){await t.writeText("properties",(await this.getProperties()).toString());}};function We(e,t,r,n,i,o){return n<0||i<0||n>=t||i>=r?o:e[i*t+n]??o}function Ic(e,t,r,n,i,o){return We(e,t,r,Math.round(n),Math.round(i),o)}function Mi(e,t,r,n,i,o){let s=Math.floor(n),c=Math.floor(i),a=s+1,u=c+1,f=n-s,l=i-c,m=We(e,t,r,s,c,Number.NaN),d=We(e,t,r,a,c,Number.NaN),p=We(e,t,r,s,u,Number.NaN),h=We(e,t,r,a,u,Number.NaN),b=0,g=0,y=[[m,(1-f)*(1-l)],[d,f*(1-l)],[p,(1-f)*l],[h,f*l]];for(let[w,S]of y)Number.isFinite(w)&&(b+=w*S,g+=S);return g===0?o:b/g}function Oi(e,t,r,n,i){let o=-0.5*e+1.5*t-1.5*r+.5*n,s=e-2.5*t+2*r-.5*n,c=-0.5*e+.5*r;return ((o*i+s)*i+c)*i+t}function Ac(e,t,r,n,i,o){let s=Math.floor(n),c=Math.floor(i),a=n-s,u=i-c,f=new Float64Array(4);for(let l=-1;l<=2;l++){let m=new Float64Array(4);for(let d=-1;d<=2;d++)m[d+1]=We(e,t,r,s+d,c+l,Number.NaN);if([m[0],m[1],m[2],m[3]].some(d=>!Number.isFinite(d)))return Mi(e,t,r,n,i,o);f[l+1]=Oi(m[0],m[1],m[2],m[3],a);}return Oi(f[0],f[1],f[2],f[3],u)}function Dr(e,t,r,n,i,o,s){return o==="nearest"?Ic(e,t,r,n,i,s):o==="bicubic"?Ac(e,t,r,n,i,s):Mi(e,t,r,n,i,s)}function Xi(e,t,r,n={}){let i=n.blankValue??e.blankValue??Number.NaN,o=n.interpolation??"bilinear",s=r*r,c=new Float32Array(s*e.depth);for(let a=0;a<r;a++)for(let u=0;u<r;u++){let{lon:f,lat:l}=vi(t,u,a,r),m=e.wcs.worldToPixel(f,l);for(let d=0;d<e.depth;d++){let p=e.planes[d],h=Dr(p,e.width,e.height,m.x,m.y,o,i);c[d*s+a*r+u]=h;}}return c}function _i(e,t,r,n="mean"){let i=Math.max(1,Math.floor(t/2)),o=new Float32Array(i*i*r),s=t*t,c=i*i;for(let a=0;a<r;a++){let u=a*s,f=a*c;for(let l=0;l<i;l++)for(let m=0;m<i;m++){let d=m*2,p=l*2;if(n==="nearest"){o[f+l*i+m]=e[u+p*t+d]??Number.NaN;continue}let h=0,b=0;for(let g=0;g<2;g++)for(let y=0;y<2;y++){let w=e[u+(p+g)*t+(d+y)];w!==void 0&&Number.isFinite(w)&&(h+=w,b++);}o[f+l*i+m]=b>0?h/b:Number.NaN;}}return o}function Re(e){return e*Math.PI/180}function Pc(e,t,r,n){let i=Re(e),o=Re(t),s=Re(r),c=Re(n),a=Math.sin(o)*Math.sin(c)+Math.cos(o)*Math.cos(c)*Math.cos(i-s),u=Math.max(-1,Math.min(1,a));return Math.acos(u)*180/Math.PI}function Rc(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function Cc(e){return e instanceof j?e:j.fromArrayBuffer(await Rc(e))}function Uc(e){return {title:e.title??"fitsjs-ng HiPS dataset",creatorDid:e.creatorDid??"ivo://fitsjs-ng/generated",hipsOrder:e.hipsOrder??0,minOrder:e.minOrder??0,tileWidth:e.tileWidth??512,frame:e.frame??"equatorial",formats:e.formats&&e.formats.length>0?e.formats:["fits"],includeCompatibilityFields:e.includeCompatibilityFields??true,includeMoc:e.includeMoc??true,includeAllsky:e.includeAllsky??true,includeIndexHtml:e.includeIndexHtml??true,includeTreeTiles:e.includeTreeTiles??true,interpolation:e.interpolation??"bilinear",blankValue:e.blankValue??Number.NaN,maxTilesPerOrder:e.maxTilesPerOrder??2e5,propertiesOverrides:e.propertiesOverrides}}function Nc(e){if(e instanceof Float64Array)return e;let t=new Float64Array(e.length);for(let r=0;r<e.length;r++)t[r]=Number(e[r]??Number.NaN);return t}function Bc(e,t,r,n=64){if(t<=n)return e;let i=e,o=t;for(;o>n;)i=_i(i,o,r,"mean"),o=Math.max(1,Math.floor(o/2));return i}async function vc(e,t){if(e.length===0)return new Uint8Array;try{return (await import('@fxpineau/moc-wasm')).MOC.fromCoo(Math.min(29,t),new Float64Array(e)).toFits(!0)}catch{return new Uint8Array}}function kc(e){return `<!doctype html>
6
+ <html lang="en">
7
+ <head>
8
+ <meta charset="utf-8" />
9
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
10
+ <title>${e}</title>
11
+ </head>
12
+ <body>
13
+ <script src="https://aladin.cds.unistra.fr/hips-templates/hips-landing-page.js"></script>
14
+ <script>buildLandingPage({alScriptURL:'https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js'})</script>
15
+ </body>
16
+ </html>
17
+ `}function Lc(e){if(!e||typeof e!="object"||!("width"in e)||!("height"in e)||!("getFrame"in e))throw new Error("FITS input does not contain an image data unit")}async function Dc(e,t){let r=Uc(t),i=(await Cc(e)).getHDU();if(!i?.data)throw new Error("No image HDU found in FITS input");Lc(i.data);let o=i.data,s=Ui(i.header),c=o.depth,a=[];for(let S=0;S<c;S++)a.push(Nc(await o.getFrame(S)));let u=Bi(o.width,o.height,r.tileWidth),f=r.hipsOrder>0?r.hipsOrder:u,l=Math.max(0,Math.min(r.minOrder,f)),m=r.includeTreeTiles?l:f,d=s.pixelToWorld((o.width-1)/2,(o.height-1)/2),p=[s.pixelToWorld(0,0),s.pixelToWorld(o.width-1,0),s.pixelToWorld(0,o.height-1),s.pixelToWorld(o.width-1,o.height-1)],h=0;for(let S of p)h=Math.max(h,Pc(d.lon,d.lat,S.lon,S.lat));let b=[],g=new Map,y=0;for(let S=m;S<=f;S++){let I=healpix.order2nside(S),A=Math.min(Math.PI,Re(h)+healpix.max_pixrad(I)),x=healpix.ang2vec(Re(90-d.lat),Re(d.lon)),E=[];if(healpix.query_disc_inclusive_nest(I,x,A,L=>{E.push(L);}),E.length>r.maxTilesPerOrder)throw new Error(`Order ${S} would generate ${E.length} tiles, above maxTilesPerOrder=${r.maxTilesPerOrder}`);for(let L of E){let C={order:S,ipix:L,frame:r.frame},$=Xi({width:o.width,height:o.height,depth:c,planes:a,wcs:s,blankValue:r.blankValue},{...C},r.tileWidth,{interpolation:r.interpolation,blankValue:r.blankValue});for(let U of r.formats){if(c>1&&U!=="fits")continue;let k=ot({...C,format:U},$,r.tileWidth,c);await t.output.writeBinary(Nt({...C,format:U}),k);}if(y++,S===f&&r.includeMoc){let{theta:U,phi:k}=healpix.pix2ang_nest(I,L);b.push(k*180/Math.PI,90-U*180/Math.PI);}S===3&&r.includeAllsky&&g.set(L,Bc($,r.tileWidth,c,64));}}let w=Ci({creatorDid:r.creatorDid,obsTitle:r.title,dataproductType:c>1?"cube":"image",frame:r.frame,order:f,tileWidth:r.tileWidth,formats:r.formats,extras:r.propertiesOverrides});if(w.set("hips_order_min",l),r.includeCompatibilityFields&&w.withCompatibilityFields(),c>1&&w.set("hips_cube_depth",c).set("hips_cube_firstframe",0).set("hips_allsky_restriction","non-fits allsky not generated for cube dataproduct"),await t.output.writeText("properties",w.toString()),r.includeAllsky&&g.size>0){let A=healpix.order2nside(3),x=12*A*A,E=Math.ceil(Math.sqrt(x)),L=Math.ceil(x/E),C=E*64,$=L*64,U=C*$,k=new Float32Array(U*c);k.fill(Number.NaN);for(let[R,X]of g.entries()){let Z=Math.floor(R/E),P=R%E,v=4096;for(let N=0;N<c;N++){let Q=N*v,me=N*U;for(let he=0;he<64;he++){let Gi=Z*64+he;for(let st=0;st<64;st++){let ji=P*64+st;k[me+Gi*C+ji]=X[Q+he*64+st]??Number.NaN;}}}}for(let R of r.formats){if(c>1&&R!=="fits")continue;let X=ot({order:3,ipix:0,frame:r.frame,format:R},k,C,c);await t.output.writeBinary(Bt(R),X);}}if(r.includeMoc){let S=await vc(b,f);S.byteLength>0&&await t.output.writeBinary("Moc.fits",S);}return r.includeIndexHtml&&await t.output.writeText("index.html",kc(r.title)),{properties:w,maxOrder:f,minOrder:l,generatedTiles:y}}async function Or(e,t){return Dc(e,t)}var Oc="https://alasky.cds.unistra.fr/hips-image-services/hips2fits",Mc="https://alaskybis.cds.unistra.fr/hips-image-services/hips2fits";function Xc(e,t,r){e.searchParams.set("hips",t),e.searchParams.set("width",String(r.width)),e.searchParams.set("height",String(r.height)),e.searchParams.set("format",r.format??"fits"),r.wcs?e.searchParams.set("wcs",JSON.stringify(r.wcs)):(e.searchParams.set("projection",r.projection??"TAN"),r.fov!==void 0&&e.searchParams.set("fov",String(r.fov)),r.ra!==void 0&&e.searchParams.set("ra",String(r.ra)),r.dec!==void 0&&e.searchParams.set("dec",String(r.dec)),r.coordsys&&e.searchParams.set("coordsys",r.coordsys),r.rotationAngle!==void 0&&e.searchParams.set("rotation_angle",String(r.rotationAngle)));}async function _c(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),t);try{return await fetch(e,{method:"GET",signal:r.signal,headers:{Accept:"application/fits,application/octet-stream,*/*"}})}finally{clearTimeout(n);}}async function Mr(e,t,r={}){let n=r.timeoutMs??25e3,i=[r.endpoint??Oc,r.endpointFallback??Mc],o;for(let s of i)try{let c=new URL(s);Xc(c,e,t);let a=await _c(c,n);if(!a.ok)throw new Error(`hips2fits request failed (${a.status} ${a.statusText})`);return await a.arrayBuffer()}catch(c){o=c;}throw new Error(`hips2fits unavailable: ${String(o)}`)}function zc(e){return e==="galactic"?"G":e==="ecliptic"?"E":"C"}function $i(e,t){return e<0?t- -e%t:e%t}function Vi(e,t,r){return e<t?t:e>r?r:e}function Gc(e,t,r,n){let i=(90-n)*Math.PI/180,o=$i(r*Math.PI/180,2*Math.PI),s=Math.cos(i),{t:c,u:a}=healpix.za2tu(s,o),u=Math.PI/4,f=c/u,l=a/u;f=$i(f,8),f-=4,l+=5;let m=Vi((l+f)/2,0,5),d=Math.floor(m),p=Vi((l-f)/2,3-d,6-d),h=Math.floor(p),b=5-(d+h),g=d-h+4,y=4*b+(g>>1)%4,w=m-d,S=p-h,I=healpix.order2nside(e),A=I*w,x=I*S,E=Math.max(0,Math.min(I-1,Math.floor(A))),L=Math.max(0,Math.min(I-1,Math.floor(x)));return {ipix:y*I*I+healpix.bit_combine(E,L),x:(A-E)*t,y:(x-L)*t}}function jc(e){if(e.wcs)return Ni(Object.fromEntries(Object.entries(e.wcs).map(([o,s])=>[o.toUpperCase(),s])));let t=(e.projection??"TAN").toUpperCase(),r=Math.max(e.width,e.height),i=(e.fov??1)/r;return vt({ctype1:`RA---${t}`,ctype2:`DEC--${t}`,crpix1:e.width/2+.5,crpix2:e.height/2+.5,crval1:e.ra??0,crval2:e.dec??0,cdelt1:-i,cdelt2:i,crota2:e.rotationAngle??0})}async function Kc(e,t){let n=(await e.getProperties()).get("hips_frame")??"equatorial",i=await e.readTile({order:t.order,ipix:t.ipix,frame:n,format:t.format}),o=qc(i.data);return ot({order:t.order,ipix:t.ipix,frame:n,format:"fits"},o,i.width,i.depth).slice().buffer}function Yc(e){let t=new Uint8Array(e.length*4),r=new DataView(t.buffer);for(let n=0;n<e.length;n++)r.setFloat32(n*4,e[n]??Number.NaN,false);return t}function Zc(){return {cards:[{key:"SIMPLE",value:true,comment:"Standard FITS"},{key:"BITPIX",value:8,comment:"Character data"},{key:"NAXIS",value:0,comment:"No data in primary HDU"},{key:"EXTEND",value:true,comment:"Extensions may be present"}]}}function qc(e){if(e instanceof Float32Array)return e;let t=new Float32Array(e.length);for(let r=0;r<e.length;r++)t[r]=Number(e[r]??Number.NaN);return t}function Jc(e){if(e instanceof Float64Array)return e;let t=new Float64Array(e.length);for(let r=0;r<e.length;r++)t[r]=Number(e[r]??Number.NaN);return t}async function Qc(e,t){let r=await e.getProperties(),n=t.order??Number(r.get("hips_order")??0),i=t.frame??r.get("hips_frame")??"equatorial",o=t.ordering??"NESTED",s=healpix.order2nside(n),c=healpix.nside2npix(s),a=new Float32Array(c);a.fill(Number.NaN);for(let l=0;l<c;l++)try{let d=(await e.readTile({order:n,ipix:l,frame:i})).data,p=0,h=0;for(let g=0;g<d.length;g++){let y=Number(d[g]??Number.NaN);Number.isFinite(y)&&(p+=y,h++);}let b=o==="RING"?healpix.nest2ring(s,l):l;a[b]=h>0?p/h:Number.NaN;}catch{continue}let u=Yc(a),f={cards:[{key:"XTENSION",value:"BINTABLE",comment:"HEALPix map table"},{key:"BITPIX",value:8},{key:"NAXIS",value:2},{key:"NAXIS1",value:4},{key:"NAXIS2",value:c},{key:"PCOUNT",value:0},{key:"GCOUNT",value:1},{key:"TFIELDS",value:1},{key:"TTYPE1",value:t.columnName??"SIGNAL"},{key:"TFORM1",value:"E"},{key:"ORDERING",value:o},{key:"INDXSCHM",value:"IMPLICIT"},{key:"NSIDE",value:s},{key:"FIRSTPIX",value:0},{key:"LASTPIX",value:c-1},{key:"COORDSYS",value:zc(i)}],data:u};return {fits:ie([Zc(),f]),map:{order:n,nside:s,ordering:o,values:a}}}async function eu(e,t,r,n,i,o,s,c){let a=Gc(n,i,t,r),u=a.ipix,f=c.get(u);if(!f){let l=await e.readTile({order:n,ipix:u,frame:o});f=Jc(l.data),c.set(u,f);}return Dr(f,i,i,a.x,a.y,s,Number.NaN)}async function Wi(e,t){let r=await e.getProperties(),n=r.get("hips_frame")??"equatorial",i=Number(r.get("hips_order")??0),o=Number(r.get("hips_tile_width")??512),s=jc(t),c=new Float32Array(t.width*t.height),a=new Map,u=t.interpolation??"bilinear";for(let m=0;m<t.height;m++)for(let d=0;d<t.width;d++){let p=s.pixelToWorld(d,m);c[m*t.width+d]=await eu(e,p.lon,p.lat,i,o,n,u,a);}let f=[{key:"CTYPE1",value:s.definition.ctype1},{key:"CTYPE2",value:s.definition.ctype2},{key:"CRPIX1",value:s.definition.crpix1},{key:"CRPIX2",value:s.definition.crpix2},{key:"CRVAL1",value:s.definition.crval1},{key:"CRVAL2",value:s.definition.crval2},{key:"CDELT1",value:s.definition.cdelt1??-1},{key:"CDELT2",value:s.definition.cdelt2??1},{key:"HIPSORD",value:i},{key:"HIPSFWID",value:o}],l=oe({primary:true,width:t.width,height:t.height,bitpix:-32,data:G(c,-32),additionalCards:f});return ie([l])}async function Xr(e,t={}){let r=e instanceof pe?e:new pe(e),n=t.backend??"local",i;if(t.tile)i=await Kc(r,t.tile);else if(t.map)i=(await Qc(r,t.map)).fits;else {let o=t.cutout??{width:512,height:512,projection:"TAN",ra:0,dec:0,fov:1,backend:n};if(n==="remote"){if(!t.cutout?.hipsId&&!t.hipsId)throw new Error("hipsId is required when backend=remote");i=await Mr(t.cutout?.hipsId??t.hipsId,o,t);}else if(n==="auto")try{i=await Wi(r,o);}catch(s){let c=t.cutout?.hipsId??t.hipsId;if(!c)throw s;i=await Mr(c,o,t);}else i=await Wi(r,o);}return t.output&&await t.output.writeBinary("output.fits",new Uint8Array(i)),i}function tu(e){return {...e,geometry:[...e.geometry],bounds:e.bounds?[e.bounds[0],e.bounds[1]]:void 0,properties:e.properties.map(t=>({...t})),tables:e.tables.map(t=>({...t,structure:t.structure.map(r=>({...r})),dataRows:t.dataRows.map(r=>({cells:r.cells.map(n=>({...n}))}))})),fitsKeywords:e.fitsKeywords.map(t=>({...t})),dataBlock:{...e.dataBlock,location:{...e.dataBlock.location}},data:e.data?new Uint8Array(e.data):void 0}}async function ru(e,t){if(e instanceof J)return e;let r=e instanceof ArrayBuffer?e:await e.arrayBuffer();return J.fromArrayBuffer(r,{...t,decodeImageData:true})}async function nu(e,t){let{imageIndex:r=0,xisfReadOptions:n,...i}=t,o=await ru(e,n),s=o.unit.images[r];if(!s)throw new Y(`XISF imageIndex ${r} is out of range (images=${o.unit.images.length})`);if(s.sampleFormat==="Complex32"||s.sampleFormat==="Complex64")throw new Y("Complex XISF images cannot be converted to HiPS image/cube");if(!s.data)throw new Y("Selected XISF image has no decoded data");let c={metadata:o.unit.metadata.map(f=>({...f})),images:[tu(s)],standaloneProperties:o.unit.standaloneProperties.map(f=>({...f})),standaloneTables:o.unit.standaloneTables.map(f=>({...f,structure:f.structure.map(l=>({...l})),dataRows:f.dataRows.map(l=>({cells:l.cells.map(m=>({...m}))}))})),version:o.unit.version,signature:{...o.unit.signature}},a=await ne.toMonolithic(c),u=await Fr(a,{strictValidation:n?.strictValidation,includeXisfMetaExtension:false});return Or(u,i)}async function iu(e,t={}){let{distributed:r,writeOptions:n,conversionOptions:i,...o}=t,s=await Xr(e,o);return Er(s,{...i??{},distributed:r,writeOptions:n})}function Vr(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Ge(e){return e.replaceAll("\\","/").replace(/^\/+/u,"")}async function ze(){let[e,t]=await Promise.all([W("fs/promises","NodeFSTarget filesystem access","Use BrowserZipTarget or a custom HiPSExportTarget in browser/React Native."),W("path","NodeFSTarget filesystem access","Use BrowserZipTarget or a custom HiPSExportTarget in browser/React Native.")]);return {fs:e,path:t}}var _r=class{constructor(t){this.root=t;}async absolute(t){let{path:r}=await ze();return r.join(this.root,Ge(t))}async writeBinary(t,r){let{fs:n,path:i}=await ze(),o=await this.absolute(t);await n.mkdir(i.dirname(o),{recursive:true}),await n.writeFile(o,Vr(r));}async writeText(t,r){let{fs:n,path:i}=await ze(),o=await this.absolute(t);await n.mkdir(i.dirname(o),{recursive:true}),await n.writeFile(o,r,"utf8");}async readBinary(t){let{fs:r}=await ze(),n=await this.absolute(t),i=await r.readFile(n);return new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}async readText(t){let{fs:r}=await ze(),n=await this.absolute(t);return r.readFile(n,"utf8")}async exists(t){let{fs:r}=await ze();try{return await r.access(await this.absolute(t)),!0}catch{return false}}},Hr=class{entries=new Map;async writeBinary(t,r){this.entries.set(Ge(t),Vr(r));}async writeText(t,r){this.entries.set(Ge(t),new TextEncoder().encode(r));}async readBinary(t){let r=this.entries.get(Ge(t));if(!r)throw new Error(`Missing ZIP entry: ${t}`);return r}async readText(t){let r=await this.readBinary(t);return new TextDecoder().decode(r)}async exists(t){return this.entries.has(Ge(t))}async finalize(){let t={};for(let[n,i]of this.entries.entries())t[n]=i;let r=fflate.zipSync(t,{level:6});if(typeof Blob<"u"){let n=new Uint8Array(r.byteLength);return n.set(r),new Blob([n.buffer],{type:"application/zip"})}return r}};function su(){return typeof navigator<"u"&&!!navigator.storage?.getDirectory}var $r=class{constructor(t="fitsjs-hips"){this.baseDir=t;}rootHandlePromise;async rootHandle(){if(!su())throw new Error("OPFS is not available in this environment");return this.rootHandlePromise||(this.rootHandlePromise=(async()=>(await navigator.storage.getDirectory()).getDirectoryHandle(this.baseDir,{create:true}))()),this.rootHandlePromise}async walk(t,r){let n=Ge(t).split("/").filter(Boolean);if(n.length===0)throw new Error("Path must not be empty");let i=n.pop(),o=await this.rootHandle();for(let s of n)o=await o.getDirectoryHandle(s,{create:r});return {dir:o,filename:i}}async writeBinary(t,r){let{dir:n,filename:i}=await this.walk(t,true),s=await(await n.getFileHandle(i,{create:true})).createWritable();await s.write(Vr(r)),await s.close();}async writeText(t,r){let{dir:n,filename:i}=await this.walk(t,true),s=await(await n.getFileHandle(i,{create:true})).createWritable();await s.write(r),await s.close();}async readBinary(t){let{dir:r,filename:n}=await this.walk(t,false),o=await(await r.getFileHandle(n)).getFile();return new Uint8Array(await o.arrayBuffer())}async readText(t){let r=await this.readBinary(t);return new TextDecoder().decode(r)}async exists(t){try{return await this.readBinary(t),!0}catch{return false}}};function Wr(e){return /^https?:\/\//iu.test(e)}async function zr(e){let[t,r]=await Promise.all([W("fs/promises",e,"Use URL-based HiPS linting or run lintHiPS local-path checks in Node.js."),W("path",e,"Use URL-based HiPS linting or run lintHiPS local-path checks in Node.js.")]);return {fs:t,pathApi:r}}async function au(e){let t=[],{fs:r,pathApi:n}=await zr("HiPS local structure lint"),i=async o=>{let s=await r.readdir(o,{withFileTypes:true});for(let c of s){let a=n.join(o,c.name),u=n.relative(e,a).replaceAll("\\","/");if(c.isDirectory()){await i(a);continue}u==="properties"||u==="Moc.fits"||u==="index.html"||/^Norder\d+\/Allsky\.(fits|png|jpg)$/iu.test(u)||u.startsWith("Norder")&&(kr(u)||t.push({level:"warning",code:"UNRECOGNIZED_TILE_NAME",message:`Unrecognized tile file path pattern: ${u}`,path:u}));}};return await i(e),t}async function cu(e,t){let r=[],{fs:n,pathApi:i}=await zr("HiPS local structure lint"),o=t.get("hips_order"),s=o!==void 0?Number(o):void 0,c=t.get("dataproduct_type"),a=new Set((t.get("hips_tile_format")??"fits").split(/[,\s]+/u).map(l=>l.trim().toLowerCase()).filter(Boolean).map(l=>l==="jpg"?"jpeg":l)),u=0,f=async l=>{let m=await n.readdir(l,{withFileTypes:true});for(let d of m){let p=i.join(l,d.name),h=i.relative(e,p).replaceAll("\\","/");if(d.isDirectory()){await f(p);continue}if(h==="properties"||h==="Moc.fits"||h==="index.html")continue;let b=/^Norder(\d+)\/Allsky\.(fits|png|jpg)$/iu.exec(h);if(b){let g=Number(b[1]),y=b[2]?.toLowerCase()==="jpg"?"jpeg":b[2]?.toLowerCase();g!==3&&r.push({level:"warning",code:"ALLSKY_ORDER_UNEXPECTED",message:`Allsky should be generated at Norder3, found Norder${g}`,path:h}),y&&a.size>0&&!a.has(y)&&r.push({level:"warning",code:"ALLSKY_FORMAT_UNDECLARED",message:`Allsky format ${y} is not listed in hips_tile_format`,path:h});continue}if(h.startsWith("Norder")){let g=kr(h);g?(u++,Number.isInteger(s)&&g.order>s&&r.push({level:"warning",code:"TILE_ORDER_EXCEEDS_MAX",message:`Tile order ${g.order} exceeds hips_order=${s}`,path:h}),a.size>0&&!a.has(g.format)&&r.push({level:"warning",code:"TILE_FORMAT_UNDECLARED",message:`Tile format ${g.format} is not listed in hips_tile_format`,path:h}),c==="cube"&&g.spectralOrder===void 0&&r.push({level:"warning",code:"CUBE_TILE_PATTERN_EXPECTED",message:"Cube dataproduct expects spectral tile naming pattern",path:h}),c!=="cube"&&g.spectralOrder!==void 0&&r.push({level:"warning",code:"UNEXPECTED_CUBE_TILE_PATTERN",message:"Found spectral tile naming in non-cube dataset",path:h})):r.push({level:"warning",code:"UNRECOGNIZED_TILE_NAME",message:`Unrecognized tile file path pattern: ${h}`,path:h});}}};return await f(e),u===0&&r.push({level:"warning",code:"NO_TILES_FOUND",message:"No valid HiPS tile files were discovered"}),r}async function uu(e){let t=new pe(e),r=[];try{let i=(await t.getProperties()).validate();for(let s of i.missing)r.push({level:"error",code:"MISSING_PROPERTY",message:`Required property is missing: ${s}`,path:"properties"});for(let s of i.invalid)r.push({level:"error",code:"INVALID_PROPERTY",message:`Invalid property value: ${s}`,path:"properties"});for(let s of i.warnings)r.push({level:"warning",code:"PROPERTY_WARNING",message:s,path:"properties"});await t.readAllsky().then(()=>!0).catch(()=>!1)||r.push({level:"warning",code:"ALLSKY_MISSING",message:"No Allsky file found in declared formats"});let o=!1;if(typeof e=="object"&&e!==null&&"exists"in e)o=await e.exists("Moc.fits");else if(typeof e=="string"&&!Wr(e))try{let{fs:s,pathApi:c}=await zr("HiPS local Moc.fits check");await s.access(c.join(e,"Moc.fits")),o=!0;}catch{o=!1;}else if(typeof e=="string"&&Wr(e))try{o=(await fetch(new URL("Moc.fits",`${e.replace(/\/+$/u,"")}/`).toString(),{method:"HEAD"})).ok;}catch{o=!1;}o||r.push({level:"warning",code:"MOC_MISSING",message:"Moc.fits not found"});}catch(n){r.push({level:"error",code:"PROPERTIES_READ_FAILED",message:`Unable to read properties: ${String(n)}`,path:"properties"});}if(typeof e=="string"&&!Wr(e)&&De())try{let n=await new pe(e).getProperties();r.push(...await cu(e,n));}catch{r.push(...await au(e));}return {ok:r.every(n=>n.level!=="error"),issues:r}}
18
+ exports.BLOCK_LENGTH=_;exports.BinaryTable=q;exports.BrowserOPFSTarget=$r;exports.BrowserZipTarget=Hr;exports.CompressedImage=qe;exports.DEFAULT_MAX_HEADER_LINES=Gr;exports.DataError=Dt;exports.DataUnit=Ae;exports.DecompressionError=O;exports.FITS=j;exports.FITSError=se;exports.HDU=Ne;exports.Header=Ue;exports.HeaderError=z;exports.HiPS=pe;exports.HiPSProperties=Ve;exports.Image=ee;exports.LINES_PER_BLOCK=Ki;exports.LINE_WIDTH=we;exports.NULL_VALUE=jr;exports.N_RANDOM=Ie;exports.NodeFSTarget=_r;exports.RiceSetup=ut;exports.SER=Pe;exports.SERConversionError=H;exports.SERError=_e;exports.SERParseError=de;exports.SERValidationError=D;exports.Table=Ze;exports.VERSION=Yi;exports.XISF=J;exports.XISFChecksumError=ge;exports.XISFCompressionError=K;exports.XISFConversionError=Y;exports.XISFError=ae;exports.XISFParseError=B;exports.XISFResourceError=ce;exports.XISFSignatureError=ke;exports.XISFValidationError=F;exports.XISFWriter=ne;exports.ZERO_VALUE=Kr;exports.convertFitsToHiPS=Or;exports.convertFitsToSer=ja;exports.convertFitsToXisf=Er;exports.convertHiPSToFITS=Xr;exports.convertHiPSToXisf=iu;exports.convertSerToFits=Ga;exports.convertSerToXisf=Za;exports.convertXisfToFits=Fr;exports.convertXisfToHiPS=nu;exports.convertXisfToSer=Qa;exports.createImageBytesFromArray=G;exports.createImageHDU=oe;exports.getCompressedImageDecoderProvider=uo;exports.getExtent=Ke;exports.getPixel=Ye;exports.lintHiPS=uu;exports.parseBlob=Gt;exports.parseBuffer=zt;exports.parseSERBlob=Pr;exports.parseSERBuffer=Tr;exports.riceDecompress=Ht;exports.setCompressedImageDecoderProvider=co;exports.writeFITS=ie;exports.writeSER=Pt;//# sourceMappingURL=index.cjs.map
3
19
  //# sourceMappingURL=index.cjs.map