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/README.md +272 -27
- package/dist/index.cjs +18 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +716 -10
- package/dist/index.d.ts +716 -10
- package/dist/index.js +18 -2
- package/dist/index.js.map +1 -1
- package/package.json +27 -15
package/dist/index.js
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
var F=80,I=2880,fe=36,re=600,se=-2147483647,ne=-2147483646,S=1e4,he="1.0.0";var L=class extends Error{constructor(e){super(e),this.name="FITSError";}},x=class extends L{constructor(e){super(e),this.name="HeaderError";}},W=class extends L{constructor(e){super(e),this.name="DataError";}},N=class extends L{constructor(e){super(e),this.name="DecompressionError";}};function D(s,e,t){t!==s.cardIndex&&s.warn(`${e} should appear at index ${t} in the FITS header`);}function V(s,e,t,r){if(e<t||e>r)throw new x(`The ${s} value of ${e} is not between ${t} and ${r}`)}function G(s){return s==="T"}var Y={SIMPLE(s,e){return s.primary=true,D(s,"SIMPLE",0),G(e)},XTENSION(s,e){return s.extension=true,s.extensionType=e,D(s,"XTENSION",0),s.extensionType},BITPIX(s,e){let t=parseInt(String(e),10);if(D(s,"BITPIX",1),![8,16,32,-32,-64].includes(t))throw new x(`BITPIX value ${t} is not permitted`);return t},NAXIS(s,e,t){let r=parseInt(String(e),10);if(!t&&(D(s,"NAXIS",2),V("NAXIS",r,0,999),s.isExtension()&&(s.extensionType==="TABLE"||s.extensionType==="BINTABLE")&&r!==2))throw new x("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(D(s,"PCOUNT",n),s.isExtension()&&(s.extensionType==="IMAGE"||s.extensionType==="TABLE")&&t!==0)throw new x(`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(D(s,"GCOUNT",n),s.isExtension()&&(s.extensionType==="IMAGE"||s.extensionType==="TABLE"||s.extensionType==="BINTABLE")&&t!==1)throw new x(`GCOUNT must be 1 for the ${s.extensionType} extensions`);return t},EXTEND(s,e){if(!s.isPrimary())throw new x("EXTEND must only appear in the primary header");return G(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 V("TFIELDS",t,0,999),t},TBCOL(s,e,t,r){let n=s.get("TFIELDS");return r!==void 0&&V("TBCOL",parseInt(r,10),0,n),e},ZIMAGE(s,e){return G(e)},ZCMPTYPE(s,e){let t=String(e);if(!["GZIP_1","RICE_1","PLIO_1","HCOMPRESS_1"].includes(t))throw new x(`ZCMPTYPE value ${t} is not permitted`);if(!["RICE_1"].includes(t))throw new x(`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 x(`ZBITPIX value ${t} is not permitted`);return t},ZNAXIS(s,e,t){let r=parseInt(String(e),10);return t||V("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 O=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 x(`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 x(`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 x(`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 Y&&(t=Y[r](this,t,n,i)),t}};var U=class{header;data;constructor(e,t){this.header=e,this.data=t;}hasData(){return this.data!==void 0}};var ie=s=>s,oe=s=>(s&255)<<8|s>>8&255,ae=s=>(s&255)<<24|(s&65280)<<8|s>>8&65280|s>>24&255,X={8:ie,B:ie,16:oe,I:oe,32:ae,J:ae},me=new TextDecoder("ascii");function P(s){return me.decode(s)}function K(s){return (2880-s%2880)%2880}function ce(s){let e=[],t=128;for(;t>=1;)e.push(s&t?1:0),t>>=1;return e}var R=class{buffer;blob;static swapEndian=X;constructor(e){e instanceof ArrayBuffer?this.buffer=e:typeof Blob<"u"&&e instanceof Blob&&(this.blob=e);}};function H(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 M(s,e,t,r){let n=t*r+e;return n<0||n>=s.length?NaN:s[n]}var k=class s extends R{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 H(e)}getPixel(e,t,r){return M(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},_={B:Uint8Array,I:Int16Array,J:Int32Array,E:Float32Array,D:Float64Array,1:Uint8Array,2:Int16Array,4:Int32Array};var v=class extends R{maxMemory=1048576;rowByteSize;rows;cols;length;heapLength;columns;accessors=[];descriptors=[];elementByteLengths=[];columnTypes=[];heap;typedArray=_;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 pe={A:s=>s.trim(),I:s=>parseInt(s,10),F:s=>parseFloat(s),E:s=>parseFloat(s),D:s=>parseFloat(s)},z=class extends v{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=pe[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=P(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 le={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]}},C=class extends v{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=_[r];if(!a)throw new Error(`No typed array constructor for descriptor: ${r}`);let u=new a(l),m=X[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 N("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=le[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(ce(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=le[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 $={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 Q(s,e,t,r,n,i=$){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 B=(p>>d)-1;p&=(1<<d)-1;let E=w+e;if(E>n&&(E=n),B<0)for(;w<E;)r[w]=c,w++;else if(B===a)for(;w<E;){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<E;){for(;p===0;)d+=8,p=s[f++];for(A=d-y[p],d-=A+1,p^=1<<d,d-=B;d<0;)p=p<<8|s[f++],d+=8;let T=A<<B|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 ye(){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=ye(),Z=class extends C{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=_[u];if(!c)throw new Error(`No typed array for bytepix: ${u}`);let f=this.ztile[0]??this.width,h=new c(f);return Q(l,m,u,h,f,$),[h,a]}:r==="GZIP_COMPRESSED_DATA"&&(this.accessors[t]=(i,o)=>{throw new N("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 H(e)}getPixel(e,t,r){return M(e,t,r,this.width)}};function ue(s,e){let t=s.getDataType();if(t)switch(t){case "Image":return new k(s,e);case "BinaryTable":return new C(s,e);case "Table":return new z(s,e);case "CompressedImage":return new Z(s,e);default:return}}function j(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=P(o),h=new O(f,e?.maxHeaderLines,e?.onWarning),y=n+i*2880,A=h.getDataLength(),b=s.slice(y,y+A),g;if(h.hasDataUnit()&&(g=ue(h,b)),t.push(new U(h,g)),n=y+A+K(A),n>=r)break}if(!l)break}return t}async function ee(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 B=f-1;B>=0;B--){let E=B*80,T=c[E];if(T!==32){if(T===69&&c[E+1]===78&&c[E+2]===68&&c[E+3]===32){l=true;break}break}}if(i++,!l)continue;let h=o.reduce((B,E)=>B+E.length,0),y=new Uint8Array(h),A=0;for(let B of o)y.set(B,A),A+=B.length;let b=P(y),g=new O(b,e?.maxHeaderLines,e?.onWarning),p=n+i*2880,d=g.getDataLength(),w;if(g.hasDataUnit()){let B=s.slice(p,p+d);w=ue(g,B);}if(t.push(new U(g,w)),n=p+d+K(d),n>=r)break}if(!l)break}return t}var te=class s{hdus;constructor(e){this.hdus=e;}static fromArrayBuffer(e,t){let r=j(e,t);return new s(r)}static async fromBlob(e,t){let r=await ee(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}};export{I as BLOCK_LENGTH,C as BinaryTable,Z as CompressedImage,re as DEFAULT_MAX_HEADER_LINES,W as DataError,R as DataUnit,N as DecompressionError,te as FITS,L as FITSError,U as HDU,O as Header,x as HeaderError,k as Image,fe as LINES_PER_BLOCK,F as LINE_WIDTH,se as NULL_VALUE,S as N_RANDOM,$ as RiceSetup,z as Table,he as VERSION,ne as ZERO_VALUE,H as getExtent,M as getPixel,ee as parseBlob,j as parseBuffer,Q as riceDecompress};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {gunzipSync,zipSync,unzlibSync,zlibSync}from'fflate';import {DOMParser,XMLSerializer}from'@xmldom/xmldom';import {decompressBlock,compressBound,compressBlock}from'lz4js';import {decompress}from'fzstd';import Un from'js-sha3';import {decode,encode}from'fast-png';import {decode as decode$1,encode as encode$1}from'jpeg-js';import {order2nside,max_pixrad,ang2vec,query_disc_inclusive_nest,pix2ang_nest,nside2npix,nest2ring,pixcoord2vec_nest,vec2ang,za2tu,bit_combine}from'@hscmap/healpix';// fitsjs-ng v1.0.2 | MIT License
|
|
2
|
+
var Se=80,X=2880,ji=36,zr=600,Gr=-2147483647,jr=-2147483646,we=1e4,Ki="1.0.2";var oe=class extends Error{constructor(t){super(t),this.name="FITSError";}},W=class extends oe{constructor(t){super(t),this.name="HeaderError";}},Lt=class extends oe{constructor(t){super(t),this.name="DataError";}},D=class extends oe{constructor(t){super(t),this.name="DecompressionError";}};function Re(e,t,r){r!==e.cardIndex&&e.warn(`${t} should appear at index ${r} in the FITS header`);}function st(e,t,r,n){if(t<r||t>n)throw new W(`The ${e} value of ${t} is not between ${r} and ${n}`)}function Dt(e){return e==="T"}var Ot={SIMPLE(e,t){return e.primary=true,Re(e,"SIMPLE",0),Dt(t)},XTENSION(e,t){return e.extension=true,e.extensionType=t,Re(e,"XTENSION",0),e.extensionType},BITPIX(e,t){let r=parseInt(String(t),10);if(Re(e,"BITPIX",1),![8,16,32,64,-32,-64].includes(r))throw new W(`BITPIX value ${r} is not permitted`);return r},NAXIS(e,t,r){let n=parseInt(String(t),10);if(!r&&(Re(e,"NAXIS",2),st("NAXIS",n,0,999),e.isExtension()&&(e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&n!==2))throw new W("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(Re(e,"PCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE")&&r!==0)throw new W(`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(Re(e,"GCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&r!==1)throw new W(`GCOUNT must be 1 for the ${e.extensionType} extensions`);return r},EXTEND(e,t){if(!e.isPrimary())throw new W("EXTEND must only appear in the primary header");return Dt(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 st("TFIELDS",r,0,999),r},TBCOL(e,t,r,n){let i=e.get("TFIELDS");return n!==void 0&&st("TBCOL",parseInt(n,10),0,i),t},ZIMAGE(e,t){return Dt(t)},ZCMPTYPE(e,t){let r=String(t);if(!["GZIP_1","RICE_1","PLIO_1","HCOMPRESS_1"].includes(r))throw new W(`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 W(`ZBITPIX value ${r} is not permitted`);return r},ZNAXIS(e,t,r){let n=parseInt(String(t),10);return r||st("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 Ce=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 W(`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 W(`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 W(`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 Ot&&(r=Ot[n](this,r,i,o)),r}};var Ue=class{header;data;constructor(t,r){this.header=t,this.data=r;}hasData(){return this.data!==void 0}};var Kr=e=>e,Yr=e=>(e&255)<<8|e>>8&255,Zr=e=>(e&255)<<24|(e&65280)<<8|e>>8&65280|e>>24&255,at={8:Kr,B:Kr,16:Yr,I:Yr,32:Zr,J:Zr},Yi=new TextDecoder("ascii");function Ge(e){return Yi.decode(e)}function Mt(e){return (2880-e%2880)%2880}function qr(e){let t=[],r=128;for(;r>=1;)t.push(e&r?1:0),r>>=1;return t}var Ie=class{buffer;blob;static swapEndian=at;constructor(t){t instanceof ArrayBuffer?this.buffer=t:typeof Blob<"u"&&t instanceof Blob&&(this.blob=t);}};function Zi(e){return e instanceof BigInt64Array||e instanceof BigUint64Array}function je(e){if(Zi(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 Ke(e,t,r,n){let i=r*n+t;return i<0||i>=e.length?NaN:e[i]}var Q=class e extends Ie{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 je(t)}getPixel(t,r,n){return Ke(t,r,n,this.width)}};var Xt={L:1,B:1,I:2,J:4,K:8,A:1,E:4,D:8,C:8,M:16},Ne={B:Uint8Array,I:Int16Array,J:Int32Array,K:BigInt64Array,E:Float32Array,D:Float64Array,1:Uint8Array,2:Int16Array,4:Int32Array};var Be=class extends Ie{maxMemory=1048576;rowByteSize;rows;cols;length;heapLength;columns;accessors=[];descriptors=[];elementByteLengths=[];columnTypes=[];heap;typedArray=Ne;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 qi={A:e=>e.trim(),I:e=>parseInt(e,10),F:e=>parseFloat(e),E:e=>parseFloat(e),D:e=>parseFloat(e)},Ye=class extends Be{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=qi[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=Ge(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 Jr={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]}},Z=class extends Be{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((Xt[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=Xt[n]??1,c=this.heap.slice(o,o+i*s),a=Ne[n];if(!a)throw new Error(`No typed array constructor for descriptor: ${n}`);let u=new a(c),f=at[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 D("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=Jr[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(qr(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=Jr[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 ct={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 _t(e,t,r,n,i,o=ct){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 Ji=221,Qi=153,Ht=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 D("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 en(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 tn(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 eo(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 to(e,t,r,n,i){eo(t,r,n,i,n);for(let o=r*n-1;o>=0;o--)i[o]!==0&&(i[o]=en(e));}function ro(e,t,r,n,i,o,s){let c=(n+1>>1)*(i+1>>1);e.inputNNybble(c,o),tn(o,n,i,t,r,s);}function ut(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){ro(e,t,r,n,i,f,l);continue}if(m!==15)throw new D("Invalid HCOMPRESS bitplane format code");f[0]=en(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,to(e,f,d,p,f);tn(f,n,i,t,r,l);}}function Qr(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 no(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 io(e,t){if(!(t<=1))for(let r=0;r<e.length;r++)e[r]=Math.imul(e[r],t);}function oo(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,k=1<<s;for(let R=s-1;R>=0;R--){k>>=1,I<<=1,A<<=1,x<=k?I-=1:x-=k,E<=k?A-=1:E-=k,R===0&&(y=0,a=2);for(let P=0;P<I;P++)Qr(e,r*P,A,1,c);for(let P=0;P<A;P++)Qr(e,P,I,r,c);n&&no(e,I,A,r,i);let H=I%2,C=A%2,v=0;for(;v<I-H;v+=2){let P=r*v,M=P+r,Y=0;for(;Y<A-C;Y+=2){let T=e[P],B=e[M],U=e[P+1],J=e[M+1];B=B+(B>=0?b:w)&d,U=U+(U>=0?b:w)&d,J=J+(J>=0?h:y)&m;let fe=J&u;B=B>=0?B-fe:B+fe,U=U>=0?U-fe:U+fe;let pe=(J^B^U)&f;T=T>=0?T+fe-pe:T+(fe===0?pe:fe-pe),e[M+1]=T+B+U+J>>a,e[M]=T+B-U-J>>a,e[P+1]=T-B+U-J>>a,e[P]=T-B-U+J>>a,P+=2,M+=2;}if(C){let T=e[P],B=e[M];B=B+(B>=0?b:w)&d;let U=B&f;T=T>=0?T-U:T+U,e[M]=T+B>>a,e[P]=T-B>>a;}}if(H){let P=r*v,M=0;for(;M<A-C;M+=2){let Y=e[P],T=e[P+1];T=T+(T>=0?b:w)&d;let B=T&f;Y=Y>=0?Y-B:Y+B,e[P+1]=Y+T>>a,e[P]=Y-T>>a,P+=2;}C&&(e[P]=e[P]>>a);}l=f,f=u,u>>=1,d=m,m>>=1,b=h,h>>=1,w=y,y=h-1;}}function so(e,t){let r=e.readByte(),n=e.readByte();if(r!==Ji||n!==Qi)throw new D("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(),ut(e,u.subarray(0),o,f,l,a[0]),ut(e,u.subarray(l),o,f,Math.floor(o/2),a[1]),ut(e,u.subarray(o*f),o,Math.floor(i/2),l,a[1]),ut(e,u.subarray(o*f+l),o,Math.floor(i/2),Math.floor(o/2),a[2]),e.inputNybble()!==0)throw new D("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,io(u,s),oo(u,i,o,t,s),{pixels:u,nx:i,ny:o}}function rn(e,t=false){let r=new Ht(e);return so(r,t)}var Vt;function ao(e){Vt=e;}function co(){return Vt}function uo(){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 $t=uo();function lo(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 fo(e){if(e instanceof Int16Array)return e;if(e instanceof Uint8Array){if(e.byteLength%2!==0)throw new D("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 D(`PLIO_1 requires Int16Array/Uint16Array/Uint8Array compressed payload, got ${e.constructor.name}`)}function mo(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function on(e,t,r){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t===8){if(e.byteLength<r)throw new D("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 D("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 D("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 D("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 D("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 D("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 D(`Unsupported ZBITPIX for GZIP_1: ${t}`)}var Ze=class extends Z{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=mo(t);if(this.zcmptype==="RICE_1"){let s=this.algorithmParameters.BYTEPIX??4,c=this.algorithmParameters.BLOCKSIZE??32,a=Ne[s];if(!a)throw new Error(`No typed array for bytepix: ${s}`);let u=new a(n);return _t(i,c,s,u,n,ct),u}if(this.zcmptype==="GZIP_1"){let s=gunzipSync(i);return on(s,this.zbitpix,n)}if(this.zcmptype==="PLIO_1"){let s=fo(t);return lo(s,n)}if(this.zcmptype==="HCOMPRESS_1"){let s=(this.algorithmParameters.SMOOTH??0)!==0,c=rn(i,s).pixels;if(c.length!==n)throw new D(`HCOMPRESS_1 tile length mismatch (decoded=${c.length}, expected=${n})`);return c}let o=this.decoderProvider??Vt;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 D(`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=gunzipSync(u);return [on(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($t[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=$t[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($t[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]=je(t);return [Number(r),Number(n)]}getPixel(t,r,n){return Number(Ke(t,r,n,this.width))}};function sn(e,t){let r=e.getDataType();if(r)switch(r){case "Image":return new Q(e,t);case "BinaryTable":return new Z(e,t);case "Table":return new Ye(e,t);case "CompressedImage":return new Ze(e,t);default:return}}function Wt(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=Ge(s),d=new Ce(m,t?.maxHeaderLines,t?.onWarning),p=i+o*2880,h=d.getDataLength(),b=e.slice(p,p+h),g;if(d.hasDataUnit()&&(g=sn(d,b)),r.push(new Ue(d,g)),i=p+h+Mt(h),i>=n)break}if(!c)break}return r}async function zt(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=Ge(p),g=new Ce(b,t?.maxHeaderLines,t?.onWarning),y=i+o*2880,w=g.getDataLength(),S;if(g.hasDataUnit()){let I=e.slice(y,y+w);S=sn(g,I);}if(r.push(new Ue(g,S)),i=y+w+Mt(w),i>=n)break}if(!c)break}return r}var G=class e{hdus;constructor(t){this.hdus=t;}static fromArrayBuffer(t,r){let n=Wt(t,r);return new e(n)}static async fromBlob(t,r){let n=await zt(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 se=class extends oe{constructor(t){super(t),this.name="XISFError";}},N=class extends se{constructor(t){super(t),this.name="XISFParseError";}},F=class extends se{constructor(t){super(t),this.name="XISFValidationError";}},ae=class extends se{constructor(t){super(t),this.name="XISFResourceError";}},j=class extends se{constructor(t){super(t),this.name="XISFCompressionError";}},he=class extends se{constructor(t){super(t),this.name="XISFChecksumError";}},ve=class extends se{constructor(t){super(t),this.name="XISFSignatureError";}},K=class extends se{constructor(t){super(t),this.name="XISFConversionError";}};var Gt="XISF0100",qe=8,an=8,cn=4,Je=qe+4+cn;function un(e){return new TextDecoder("ascii").decode(e)}function ln(e){return e.byteLength<Je?false:un(new Uint8Array(e,0,qe))===Gt}function fn(e){if(e.byteLength<Je)throw new N("Invalid XISF file: too short");let t=un(new Uint8Array(e,0,qe));if(t!==Gt)throw new N(`Invalid XISF signature: ${t}`);let n=new DataView(e).getUint32(an,true),i=Je,o=i+n;if(o>e.byteLength)throw new N("Invalid XISF header length");let s=new Uint8Array(e,i,n),c=new TextDecoder("utf-8").decode(s),a=new Uint8Array(e,qe+4,cn),u=new Uint8Array(e,o);return {signature:t,headerLength:n,reserved:a,headerXml:c,payload:u}}function mn(e,t,r){if(t<0||r<0||t+r>e.byteLength)throw new N(`Attachment block out of bounds: position=${t}, size=${r}`);return new Uint8Array(e,t,r)}function dn(e,t){let r=new TextEncoder().encode(e),i=Je+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(Gt),0);let s=new DataView(o.buffer);s.setUint32(an,r.byteLength,true),s.setUint32(qe+4,0,true),o.set(r,Je);for(let c of t)o.set(c.data,c.position);return o}var ho="http://www.pixinsight.com/xisf";function jt(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 go(e){return e.nodeType===1}function hn(e){let t=new DOMParser().parseFromString(e,"application/xml"),r=t.getElementsByTagName("parsererror");if(r.length>0)throw new N((r[0]?.textContent??"Invalid XML").trim());let n=t.documentElement;if(!n)throw new N("Empty XML document");if(jt(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 bo(e){let t=[];for(let r=0;r<e.childNodes.length;r++){let n=e.childNodes.item(r);n&&go(n)&&t.push(n);}return t}function ee(e,t){return bo(e).filter(r=>jt(r)===t)}function Qe(e,t){let r=ee(e,t);return r.length>0?r[0]:null}function Ae(e){return jt(e)}function lt(e){return new XMLSerializer().serializeToString(e)}function Kt(){let e=new DOMParser().parseFromString('<?xml version="1.0" encoding="UTF-8"?><xisf version="1.0"/>',"application/xml"),t=e.documentElement;return t.setAttribute("xmlns",ho),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 yo=/^(url|path)\((.*)\)(?::(.*))?$/;function So(e){if(!e)return;let t=e.trim();if(t.length!==0)return t.startsWith("0x")||t.startsWith("0X"),BigInt(t)}function Yt(e){let t=e.trim();if(t.startsWith("inline:")){let n=t.slice(7);if(n!=="base64"&&n!=="hex")throw new N(`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 N(`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 N(`Invalid attachment numbers: ${e}`);return {type:"attachment",position:o,size:s}}let r=yo.exec(t);if(r){let n=r[1],i=r[2],o=So(r[3]);return n==="url"?{type:"url",url:i,indexId:o}:{type:"path",path:i,indexId:o}}throw new N(`Unsupported location syntax: ${e}`)}function Zt(e){return e.trim()?e.split(":").map(t=>{let r=t.split(",");if(r.length!==2)throw new N(`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 N(`Invalid subblocks values: ${t}`);return {compressedSize:n,uncompressedSize:i}}):[]}function gn(e){let t=e.indexOf(":");if(t<=0)throw new N(`Invalid checksum format: ${e}`);return {algorithm:e.slice(0,t).toLowerCase(),digest:e.slice(t+1).toLowerCase()}}function qt(e){let t=e.split(":");if(t.length<2||t.length>3)throw new N(`Invalid compression format: ${e}`);let r=t[0].toLowerCase(),n=Number(t[1]);if(!Number.isInteger(n)||n<0)throw new N(`Invalid uncompressed size: ${e}`);if(t.length===3){let i=Number(t[2]);if(!Number.isInteger(i)||i<=0)throw new N(`Invalid shuffle item size: ${e}`);return {codec:r,uncompressedSize:n,itemSize:i}}return {codec:r,uncompressedSize:n}}function bn(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 wo={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"},Sn={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"},Io={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 Jt(e){return wo[e]}function Ao(e){let t=e.toLowerCase();return t==="true"||t==="1"}function xo(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 yn(e,t){switch(Jt(e)??e){case "Boolean":return Ao(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 xo(t);default:return t}}function Fo(e){return e.byteOrder==="big"?"big":"little"}function wn(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 Eo(e,t,r){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=r==="little";if(t.byteLength<wn(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 Qt(e,t,r,n){let i=r==="little",o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=wn(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 ft(e){let t=e.getAttribute("location");if(!t)return;let r=Yt(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=gn(n);c.checksum={algorithm:a.algorithm,digest:a.digest};}if(i){let a=qt(i);c.compression={codec:a.codec,uncompressedSize:a.uncompressedSize,itemSize:a.itemSize,subblocks:s?Zt(s):void 0};}if(r.type==="inline")c.inlineData=(e.textContent??"").trim();else if(r.type==="embedded"){let a=Qe(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=qt(f);c.compression={codec:l.codec,uncompressedSize:l.uncompressedSize,itemSize:l.itemSize,subblocks:a.getAttribute("subblocks")?Zt(a.getAttribute("subblocks")):void 0};}}}}return c}function To(e,t,r){let n=Sn[e];return n?Qt(n,t,"little",r):new Uint8Array(t)}async function xe(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=yn(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=ft(e);if(!d)return o==="String"||o==="TimePoint"?a.value=e.textContent??"":Jt(o)&&(e.textContent??"").trim().length>0&&(a.value=yn(o,(e.textContent??"").trim())),a;a.dataBlock=d;let p=await t(e,d),h=Fo(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=Jt(o);if(b&&b!=="String"&&b!=="TimePoint")return a.value=Eo(b,p,h),a;if(o.endsWith("Vector")||o==="ByteArray"||o==="IVector"||o==="UIVector"||o==="Vector"){let g=Sn[o];return g?(a.value=Qt(g,p,h,a.length),a):(a.value=To(o,p,a.length),a)}if(o.endsWith("Matrix")){let g=a.rows??0,y=a.columns??0,w=Io[o];if(!w)return a.value=p,a;let S=g>0&&y>0?g*y:void 0,I=Qt(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 Po(e){return {id:e.getAttribute("id")??"",type:e.getAttribute("type")??"",format:e.getAttribute("format")??void 0,header:e.getAttribute("header")??void 0}}function Ro(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 Co(e,t,r,n){let i=ee(e,"Cell");return {cells:await Promise.all(i.map((s,c)=>{let a=t[c],u=Ro(s,a);return xe(u,r,{...n,defaultType:a?.type,defaultId:a?.id,defaultFormat:a?.format})}))}}async function mt(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=Qe(e,"Structure");if(!f){let p=Qe(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?ee(f,"Field").map(Po):[],m=ee(e,"Row"),d=await Promise.all(m.map(p=>Co(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 Uo=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),No=new Set(["Gray","RGB","CIELab"]),Bo=new Set(["Planar","Normal"]),vo=new Set(["0","flip","90","90;flip","-90","-90;flip","180","180;flip"]),ko=/^[0RGBWCMY]+$/;function ce(e){return e.split(":").map(t=>Number(t.trim()))}function Lo(e){let t=ce(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 Do(e){if(!e)return;let[t,r]=ce(e);if(!(t===void 0||r===void 0))return [t,r]}function Oo(e){let t=e.getAttribute("gamma")??"sRGB",r=ce(e.getAttribute("x")??"0:0:0"),n=ce(e.getAttribute("y")??"0:0:0"),i=ce(e.getAttribute("Y")??"0:0:0");return {gamma:t,x:r,y:n,Y:i,name:e.getAttribute("name")??void 0}}function Mo(e){return {m:ce(e.getAttribute("m")??"0.5:0.5:0.5:0.5"),s:ce(e.getAttribute("s")??"0:0:0:0"),h:ce(e.getAttribute("h")??"1:1:1:1"),l:ce(e.getAttribute("l")??"0:0:0:0"),r:ce(e.getAttribute("r")??"1:1:1:1"),name:e.getAttribute("name")??void 0}}function Xo(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&&!ko.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 _o(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 Ho(e){return {name:e.getAttribute("name")??"",value:e.getAttribute("value")??"",comment:e.getAttribute("comment")??""}}async function er(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(!Uo.has(c))throw new F(`Unsupported image sampleFormat: ${c}`);let{dimensions:a,channels:u}=Lo(s),f=ft(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(!Bo.has(l))throw new F(`Unsupported pixelStorage: ${l}`);let m=e.getAttribute("colorSpace")||"Gray";if(!No.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&&!vo.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=Do(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=ee(e,"Reference"),w=I=>{let A=[],x=I.childNodes;for(let E=0;E<x.length;E++){let k=x.item(E);k&&k.nodeType===1&&A.push(k);}return A},S=[];for(let I of w(e)){if(Ae(I)==="Reference"){let A=I.getAttribute("ref");if(A){let x=t(A);if(x){if(i&&Ae(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&&Ae(x)==="Reference")throw new F(`Chained references are not allowed (${A})`);x&&!S.includes(x)&&S.push(x);}for(let I of S)switch(Ae(I)){case "Property":g.properties.push(await xe(I,r,{strictValidation:i}));break;case "Table":g.tables.push(await mt(I,t,r,{strictValidation:i}));break;case "FITSKeyword":g.fitsKeywords.push(Ho(I));break;case "ICCProfile":{if(i&&I.hasAttribute("byteOrder"))throw new F("ICCProfile must not define byteOrder");let x=ft(I);x&&(g.iccProfile=await r(I,x));break}case "RGBWorkingSpace":g.rgbWorkingSpace=Oo(I);break;case "DisplayFunction":g.displayFunction=Mo(I);break;case "ColorFilterArray":if(o)throw new F("Thumbnail must not contain ColorFilterArray");g.colorFilterArray=Xo(I,i);break;case "Resolution":g.resolution=_o(I,i);break;case "Thumbnail":if(o)throw new F("Nested Thumbnail elements are not allowed");g.thumbnail=await er(I,t,r,n,i,true);break;}return g}var ke="+sh",jo=new Set([0,1,2,3,4,5,6,7,8,9]),tr=new Set(["lz4","lz4hc"]),rr=new Set(["zstd"]);function Ko(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 Yo(e){let t=new Uint8Array(compressBound(e.byteLength)),r=new Uint32Array(65536),n=compressBlock(e,t,0,e.byteLength,r);return n>0?t.slice(0,n):Ko(e)}function Zo(e,t){if(!t||t<=0)throw new j("LZ4 codecs require uncompressedSize in XISF compression spec");let r=new Uint8Array(t),n=decompressBlock(e,r,0,e.byteLength,0),i=typeof n=="number"?n:r.byteLength;if(i!==r.byteLength)throw new j(`Decoded LZ4 block length mismatch: expected ${r.byteLength}, got ${i}`);return r}var dt={supports(e){let t=e.toLowerCase(),r=t.endsWith(ke)?t.slice(0,-ke.length):t;return r==="zlib"||tr.has(r)||rr.has(r)},compress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new j(`Unsupported codec in default provider: ${e}`);if(tr.has(n))return Yo(t);if(rr.has(n))throw new j("Default provider supports zstd decompression only; provide a custom codecProvider for zstd encoding");let i=r!==void 0&&jo.has(r)?r:void 0;return zlibSync(t,{level:i})},decompress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new j(`Unsupported codec in default provider: ${e}`);if(tr.has(n))return Zo(t,r);if(rr.has(n)){let i=r&&r>0?new Uint8Array(r):void 0,o=i?decompress(t,i):decompress(t);if(i&&o.byteLength!==i.byteLength)throw new j(`Decoded zstd block length mismatch: expected ${i.byteLength}, got ${o.byteLength}`);return o}return unzlibSync(t)}};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[o++]=e[c*t+s];return n>0&&i.set(e.slice(r*t),o),i}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[c*t+s]=e[o++];return n>0&&i.set(e.slice(o),r*t),i}function Qo(e,t){let r=[],n=0;for(let i of t){let o=n+i.compressedSize;if(o>e.byteLength)throw new j("Compressed subblocks exceed block length");r.push(e.slice(n,o)),n=o;}if(n!==e.byteLength)throw new j("Compressed subblocks length mismatch");return r}function An(e,t,r){let n=t.codec.toLowerCase(),i=n.endsWith(ke),o=i?n.slice(0,-ke.length):n,s=f=>{let l=r.decompress(o,f,t.uncompressedSize);if(!i)return l;if(!t.itemSize||t.itemSize<=0)throw new j(`Shuffle codec ${n} requires itemSize`);return Jo(l,t.itemSize)};if(!t.subblocks||t.subblocks.length===0)return s(e);let c=Qo(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 j("Decoded subblock size mismatch");a.set(l,u),u+=l.byteLength;}if(u!==t.uncompressedSize)throw new j("Decoded uncompressed size mismatch");return a}function xn(e,t,r,n,i){let o=t.toLowerCase(),s=o.endsWith(ke),c=s?o.slice(0,-ke.length):o,a=s?qo(e,i??1):e;return {data:r.compress(c,a,n),spec:{codec:o,uncompressedSize:e.byteLength,itemSize:s?i??1:void 0}}}function es(e){return import(e)}function ts(){return typeof process<"u"&&typeof process=="object"}function Fn(){return typeof navigator<"u"&&navigator.product==="ReactNative"}function Le(){if(!ts()||Fn())return false;let e=process.versions;return typeof e?.node=="string"&&e.node.length>0}function nr(){return Le()?"node":Fn()?"react-native":typeof window<"u"?"browser":"unknown"}async function V(e,t,r){if(!Le()){let i=r?` ${r}`:"";throw new Error(`${t} requires Node.js runtime. Current runtime: ${nr()}.${i}`)}let n=e.startsWith("node:")?e:`node:${e}`;try{return await es(n)}catch(i){throw new Error(`${t} failed to load ${n}: ${i.message}`)}}function rs(e){return new Uint8Array(e)}async function ns(e){try{let r=await(await V("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 ae(`Failed to read path "${e}": ${t.message}`)}}var En={async resolveURL(e){let t=await fetch(e);if(!t.ok)throw new ae(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);return rs(await t.arrayBuffer())},async resolvePath(e){if(!Le())throw new ae(`Path-based distributed XISF access requires Node.js or a custom resourceResolver.resolvePath (runtime=${nr()}): ${e}`);return ns(e)}};var Tn="XISB0100";function is(e){return new TextDecoder("ascii").decode(e)}function ir(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new F(`${t} exceeds Number.MAX_SAFE_INTEGER`);return Number(e)}function Pn(e){let t=new Uint8Array(e);if(t.byteLength<16)throw new N("Invalid XISB file: too short");let r=is(t.slice(0,8));if(r!==Tn)throw new N(`Invalid XISB signature: ${r}`);let n=new DataView(e),i=[],o=16,s=new Set;for(;o!==0;){if(s.has(o))throw new N("Invalid XISB index: cyclic block index list");if(s.add(o),o+16>t.byteLength)throw new N("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 N("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=ir(u,"nextNode");}let c=new Map;for(let a of i)c.set(a.uniqueId,a);return {elements:i,byId:c}}function Rn(e,t){if(t.blockPosition===BigInt(0)||t.blockLength===BigInt(0))throw new F("Cannot read free XISB index element");let r=ir(t.blockPosition,"blockPosition"),n=ir(t.blockLength,"blockLength"),i=new Uint8Array(e);if(r+n>i.byteLength)throw new N("XISB block out of bounds");return i.slice(r,r+n)}function Cn(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(Tn),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 os=Un.sha3_256,ss=Un.sha3_512;function as(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 or(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 as(o)}let n=(await V("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 sr(e,t){switch(t.toLowerCase()){case "sha1":case "sha-1":return or("SHA-1",e);case "sha256":case "sha-256":return or("SHA-256",e);case "sha512":case "sha-512":return or("SHA-512",e);case "sha3-256":return os(e);case "sha3-512":return ss(e);default:throw new he(`Unsupported checksum algorithm: ${t}`)}}async function Nn(e,t){return (await sr(e,t.algorithm)).toLowerCase()===t.digest.toLowerCase()}var De="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ar=new Int16Array(128).fill(-1);for(let e=0;e<De.length;e++)ar[De.charCodeAt(e)]=e;function cs(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 us(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t}function pt(e){return e<0||e>=ar.length?-1:ar[e]??-1}function ht(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 ls(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+=De[s>>18&63],t+=De[s>>12&63],t+=r+1<e.length?De[s>>6&63]:"=",t+=r+2<e.length?De[s&63]:"=";}return t}function fs(e){let t=ht(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?pt(s):-1,l=c<128?pt(c):-1,m=a===61?-2:a<128?pt(a):-1,d=u===61?-2:u<128?pt(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 Oe(e){return typeof btoa=="function"?btoa(cs(e)):ls(e)}function Fe(e){let t=ht(e);return typeof atob=="function"?us(atob(t)):fs(t)}var O="http://www.w3.org/2000/09/xmldsig#",mr="http://www.w3.org/TR/2001/REC-xml-c14n-20010315",ms="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments",ds="http://www.w3.org/2006/12/xml-c14n11",ps="http://www.w3.org/2006/12/xml-c14n11#WithComments",hs="http://www.w3.org/2001/10/xml-exc-c14n#",gs="http://www.w3.org/2001/10/xml-exc-c14n#WithComments",bs="http://www.w3.org/2000/09/xmldsig#enveloped-signature",ys="http://www.w3.org/2000/09/xmldsig#base64";function Me(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 et(e){return !!e&&e.nodeType===1}function Ss(e){return !!e&&e.nodeType===8}function ws(e){return !!e&&(e.nodeType===3||e.nodeType===4)}function dr(e,t,r){let n=[];for(let i=0;i<e.childNodes.length;i++){let o=e.childNodes.item(i);et(o)&&Me(o)===t&&((o.namespaceURI??"")!==r||n.push(o));}return n}function $(e,t,r){let n=dr(e,t,r);return n.length>0?n[0]:null}function Ln(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(et(n)&&Me(n)==="Signature"&&(n.namespaceURI??"")===O)return n}return null}function Dn(e){return Ln(e)!==null}function Is(e){return ht(e)}function gt(e){return Oe(e).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/gu,"")}async function ge(e){return Fe(Is(e))}function ur(e){return new TextEncoder().encode(e)}function lr(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 As(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll("\r","
")}function cr(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll('"',""").replaceAll(" ","	").replaceAll(`
|
|
3
|
+
`,"
").replaceAll("\r","
")}function Bn(e){let t=e.prefix,r=Me(e);return t?`${t}:${r}`:r}function xs(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 Fs(e){return new Map(e.entries())}function Es(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(et(o)&&Me(o)==="Signature"&&(o.namespaceURI??"")===O){n.removeChild(o);continue}r(o);}}};return r(t),t}function pr(e){switch(e){case mr:case ds:return {withComments:false,exclusive:false};case ms:case ps:return {withComments:true,exclusive:false};case hs:return {withComments:false,exclusive:true};case gs:return {withComments:true,exclusive:true};default:return null}}function Ts(e){return e.prefix??""}function vn(e){let t=e.prefix;return !t||t==="xmlns"?"":t}function Ps(e,t,r){let n=Ts(e),i=e.namespaceURI??"",o=xs(e),s=Fs(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=vn(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=vn(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="${cr(h)}"`:` xmlns:${p}="${cr(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?Me(p).localeCompare(Me(h)):b.localeCompare(g)});let f=u.map(p=>` ${p.name}="${cr(p.value)}"`).join(""),l=`<${Bn(e)}${a.join("")}${f}>`,m="";for(let p=0;p<e.childNodes.length;p++){let h=e.childNodes.item(p);h&&(m+=hr(h,s,r));}let d=`</${Bn(e)}>`;return `${l}${m}${d}`}function hr(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+=hr(s,t,r));}return i}if(et(e))return Ps(e,t,r);if(ws(e))return As(e.data);if(Ss(e))return r.withComments?`<!--${e.data}-->`:"";if(e.nodeType===7){let n=e;return `<?${n.target}${n.data?` ${n.data}`:""}?>`}return ""}function fr(e,t){let r=pr(t);if(!r)throw new Error(`Unsupported canonicalization algorithm: ${t}`);return hr(e,new Map,r)}function Rs(e){let t=$(e,"Transforms",O);if(!t)return [];let r=[];for(let n of dr(t,"Transform",O)){let i=n.getAttribute("Algorithm");i&&r.push(i);}return r}function Cs(e,t){let r=[e.documentElement];for(;r.length>0;){let n=r.pop();if(!n||!et(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 Us(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=Cs(e,r);if(!n)throw new Error(`Unable to resolve signature reference URI: ${t}`);return {kind:"node",node:n}}function be(e){return (e.textContent??"").trim()}function Ns(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 Bs(e,t){let r=Ns(e);if(typeof crypto<"u"&&crypto.subtle){let s=await crypto.subtle.digest(r,lr(t));return new Uint8Array(s)}let n=await V("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 vs(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 bt(e){let t=0;for(;t<e.length-1&&e[t]===0;)t++;return e.subarray(t)}async function ks(e){let t=await V("crypto","XISF signature key loading from KeyInfo","Enable WebCrypto-compatible KeyInfo or run in Node.js for detached-signature verification."),r=$(e,"X509Data",O);if(r){let i=$(r,"X509Certificate",O);if(i){let o=await ge(be(i));return new t.X509Certificate(o).publicKey}}let n=$(e,"KeyValue",O);if(n){let i=$(n,"RSAKeyValue",O);if(i){let o=$(i,"Modulus",O),s=$(i,"Exponent",O);if(!o||!s)throw new Error("Invalid RSAKeyValue: missing Modulus/Exponent");let c=bt(await ge(be(o))),a=bt(await ge(be(s))),u={kty:"RSA",n:gt(c),e:gt(a)};return t.createPublicKey({key:u,format:"jwk"})}}throw new Error("Unsupported KeyInfo content")}async function Ls(e,t){if(t.kind==="ecdsa")throw new Error("ECDSA KeyInfo import is not yet supported without SPKI");let r=$(e,"KeyValue",O);if(!r)throw new Error("No RSA KeyValue in KeyInfo");let n=$(r,"RSAKeyValue",O);if(!n)throw new Error("Only RSAKeyValue is supported for WebCrypto verification");let i=$(n,"Modulus",O),o=$(n,"Exponent",O);if(!i||!o)throw new Error("Invalid RSAKeyValue: missing Modulus/Exponent");let s=bt(await ge(be(i))),c=bt(await ge(be(o))),a={kty:"RSA",n:gt(s),e:gt(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 Ds(e,t){let r=$(e,"KeyInfo",O);if(!r)throw new Error("Missing ds:KeyInfo in signature");try{return {kind:"node",key:await ks(r)}}catch(n){if(typeof crypto<"u"&&crypto.subtle)try{return {kind:"webcrypto",key:await Ls(r,t)}}catch(i){throw new Error(`Unable to load signature public key (node=${n.message}; web=${i.message})`)}throw n}}function Os(e){return e.toLowerCase().replace("-","")}function kn(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 Ms(e,t,r,n){if(n.kind==="node"){let o=await V("crypto",`XISF detached signature verification (${r.name})`,"Enable WebCrypto or run in Node.js for detached-signature verification."),s=o.createVerify(Os(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:kn(r.hash)},t):s.verify(n.key,t)}let i;return r.kind==="rsa-pss"?i={name:"RSA-PSS",saltLength:kn(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,lr(t),lr(e))}async function Xs(e,t){let r=t.getAttribute("URI"),n=Us(e,r),i=Rs(t);for(let o of i){if(o===bs){if(n.kind!=="node")throw new Error("Enveloped-signature transform requires XML node input");n={kind:"node",node:Es(n.node)};continue}if(o===ys){let s=n.kind==="node"?be(n.node):new TextDecoder("ascii").decode(n.bytes);n={kind:"bytes",bytes:await ge(s)};continue}if(pr(o)){if(n.kind!=="node")throw new Error("Canonicalization transform requires XML node input");n={kind:"bytes",bytes:ur(fr(n.node,o))};continue}throw new Error(`Unsupported signature transform: ${o}`)}return n.kind==="bytes"?n.bytes:ur(fr(n.node,mr))}async function _s(e,t){let r=dr(t,"Reference",O);if(r.length===0)throw new Error("SignedInfo has no Reference elements");for(let n of r){let i=n.getAttribute("URI")??"",o=$(n,"DigestMethod",O),s=$(n,"DigestValue",O);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 ge(be(s)),u=await Xs(e,n),f=await Bs(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 te(e,t){return {present:true,verified:false,algorithm:e,reason:t}}async function On(e){let t=Ln(e);if(!t)return {present:false,verified:true};let r=$(t,"SignedInfo",O);if(!r)return te(void 0,"Signature is missing SignedInfo");let n=$(r,"CanonicalizationMethod",O);if(!n)return te(void 0,"SignedInfo is missing CanonicalizationMethod");let i=n.getAttribute("Algorithm")??mr;if(!pr(i))return te(void 0,`Unsupported canonicalization algorithm: ${i}`);let o=$(r,"SignatureMethod",O);if(!o)return te(void 0,"SignedInfo is missing SignatureMethod");let s=o.getAttribute("Algorithm")??void 0;if(!s)return te(void 0,"SignatureMethod is missing Algorithm");let c=$(t,"SignatureValue",O);if(!c)return te(s,"SignatureValue is missing");let a;try{a=vs(s);}catch(d){return te(s,d.message)}try{await _s(e,r);}catch(d){return te(s,`Digest verification failed: ${d.message}`)}let u=ur(fr(r,i)),f=await ge(be(c)),l;try{l=await Ds(t,a);}catch(d){return te(s,`Key loading failed: ${d.message}`)}let m=false;try{m=await Ms(u,f,a,l);}catch(d){return te(s,`Signature verification failed: ${d.message}`)}return m?{present:true,verified:true,algorithm:a.name}:te(s,"SignatureValue does not match SignedInfo")}function Hs(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??dt,resourceResolver:e?.resourceResolver??En}}function Mn(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Xn(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 _n(e){return Fe(e)}function Hn(e,t){e.onWarning(t);}function gr(e,t,r){if(e.strictValidation)throw t;Hn(e,{code:r,message:t.message});}async function $s(e){if(e.location.type==="inline")return e.location.encoding==="base64"?_n(e.inlineData??""):Xn("hex",e.inlineData??"");if(e.location.type==="embedded")return (e.location.encoding??"base64")==="base64"?_n(e.embeddedData??""):Xn("hex",e.embeddedData??"");throw new N("decodeInlineOrEmbedded called on non-inline block")}var q=class e{unit;constructor(t){this.unit=t;}static async fromArrayBuffer(t,r){let n=Hs(r);if(!n.verifySignatures&&n.signaturePolicy==="require")throw new ve("signaturePolicy=require requires verifySignatures=true");let i="",o;ln(t)?(i=fn(t).headerXml,o=t):i=new TextDecoder("utf-8").decode(new Uint8Array(t));let s=hn(i),c=Dn(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 $s(S);else if(A.type==="attachment"){if(!o)throw new ae("Attachment location found but no monolithic XISF payload exists");I=mn(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&&gr(n,new he(`Checksum is required for signed block in ${w.tagName}`),"checksum_required_for_signed_block"),S.checksum&&(n.verifyChecksums||u)&&(await Nn(I,S.checksum)||gr(n,new he(`Checksum mismatch for ${w.tagName}`),"checksum_mismatch")),S.compression)try{I=An(I,S.compression,n.codecProvider);}catch(E){gr(n,E,"decompression_failed");}return I},d=[],p=[],h=[],b=ee(a,"Metadata")[0];if(b){let w=ee(b,"Property");for(let S of w)d.push(await xe(S,m,{strictValidation:n.strictValidation}));}let g=[];for(let w of ee(a,"Image")){let S=await er(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=Ae(I);A==="Property"?p.push(await xe(I,m,{strictValidation:n.strictValidation})):A==="Table"&&h.push(await mt(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 On(s),y.present&&!y.verified)){if(n.signaturePolicy==="require")throw new ve(y.reason??"Signature verification failed");Hn(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 ae(`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(Mn(o),t.indexId):o}let n=bn(t.path,r.headerDir||void 0),i=await r.resourceResolver.resolvePath(n);return t.indexId?e.sliceIndexedBlock(Mn(i),t.indexId):i}static sliceIndexedBlock(t,r){let i=Pn(t).byId.get(r);if(!i)throw new F(`Missing XISB block for indexId ${r.toString(16)}`);return Rn(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 It={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"},jn={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"},Vs=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),Ws=new Set(["Gray","RGB","CIELab"]),zs=new Set(["Planar","Normal"]);function $n(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??dt}}function Kn(e){return typeof e=="boolean"?e?"true":"false":typeof e=="bigint"?e.toString(10):String(e)}function br(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 yt(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 St(e){let t=It[e]??jn[e];return t?br(t)>1:false}function Gs(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 js(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 Vn(e){return ArrayBuffer.isView(e)?Array.from(e):Array.isArray(e)?e.length>0&&Array.isArray(e[0])?e.flat():e:[]}function Yn(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=js(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*br(s)),u=new DataView(a.buffer),f=br(s);for(let l=0;l<c.length;l++)Gs(u,s,l*f,c[l],r);return a},i=It[e.type];if(i){let s=Vn(e.value);return {bytes:n(i,s),itemCount:s.length}}let o=jn[e.type];if(o){let s=e.value,c=e.rows??s?.rows,a=e.columns??s?.columns,u=s?.values??e.value,f=Vn(u);return {bytes:n(o,f),itemCount:f.length,rows:c,columns:a}}}function Wn(e,t){if(!Vs.has(e.sampleFormat))throw new F(`Unsupported image sampleFormat: ${e.sampleFormat}`);if(!Ws.has(e.colorSpace??"Gray"))throw new F(`Unsupported image colorSpace: ${e.colorSpace}`);if(!zs.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 zn(e,t,r,n){let i=e;if(r.compression){let o=xn(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 sr(i,r.checksumAlgorithm);t.setAttribute("checksum",`${r.checksumAlgorithm}:${o}`);}return i}function tt(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",Kn(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(wt(c)))):(o.setAttribute("length",String(s.length??c.byteLength)),o.setAttribute("location",`attachment:0:${c.byteLength}`),n.push({element:o,data:c})),St(r.type)&&r.dataBlock?.byteOrder&&o.setAttribute("byteOrder",r.dataBlock.byteOrder);}else {let c=Yn(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 It&&o.setAttribute("length",String(c.itemCount)),c.bytes.byteLength<=i?(o.setAttribute("location","inline:base64"),o.appendChild(e.createTextNode(wt(c.bytes)))):(o.setAttribute("location",`attachment:0:${c.bytes.byteLength}`),n.push({element:o,data:c.bytes})),St(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 yr(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",Kn(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(wt(p)))):(m.setAttribute("location",`attachment:0:${p.byteLength}`),n.push({element:m,data:p})),d&&St(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder);}else if(d){let p=Yn({...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 It&&m.setAttribute("length",String(p.itemCount)),p.bytes.byteLength<=i?(m.setAttribute("location","inline:base64"),m.appendChild(e.createTextNode(wt(p.bytes)))):(m.setAttribute("location",`attachment:0:${p.bytes.byteLength}`),n.push({element:m,data:p.bytes})),St(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder));}}a.appendChild(m);}o.appendChild(a);}t.appendChild(o);}function Gn(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)tt(e,t,o,n,i);for(let o of r.tables)yr(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 wt(e){try{return Oe(e)}catch(t){throw new F(`No base64 encoder available in this environment: ${t.message}`)}}async function Ks(e,t,r){let n=-1,i="",o=0;for(;o!==n;){let c=t.ownerDocument;if(i=lt(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 re=class{static async toMonolithic(t,r){let n=$n(r),i=Kt(),o=i.documentElement,s=i.createElement("Metadata"),c=[];for(let l of t.metadata)tt(i,s,l,c,n.maxInlineBlockSize);o.appendChild(s);for(let l of t.standaloneProperties)tt(i,o,l,c,n.maxInlineBlockSize);for(let l of t.standaloneTables)yr(i,o,l,c,n.maxInlineBlockSize);for(let l of t.images){if(Wn(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&&yt(l.sampleFormat)>1&&m.setAttribute("byteOrder",l.dataBlock.byteOrder);let d=yt(l.sampleFormat),p=await zn(l.data,m,n,Math.max(1,d));m.setAttribute("location",`attachment:0:${p.byteLength}`),c.push({element:m,data:p}),Gn(i,m,l,c,n.maxInlineBlockSize),o.appendChild(m);}let a=await Ks(n,o,c),u=lt(i);return dn(u,a).slice().buffer}static async toDistributed(t,r){let n=$n(r),i=Kt(),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)tt(i,a,d,c,n.maxInlineBlockSize);for(let d of t.standaloneProperties)tt(i,o,d,c,n.maxInlineBlockSize);for(let d of t.standaloneTables)yr(i,o,d,c,n.maxInlineBlockSize);for(let d of t.images){if(Wn(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&&yt(d.sampleFormat)>1&&p.setAttribute("byteOrder",d.dataBlock.byteOrder);let h=yt(d.sampleFormat),b=await zn(d.data,p,n,Math.max(1,h));p.setAttribute("location",`attachment:0:${b.byteLength}`),c.push({element:p,data:b}),Gn(i,p,d,c,n.maxInlineBlockSize),o.appendChild(p);}for(let d of c)u(d.element,d.data);let{bytes:f,ids:l}=Cn(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(lt(i)),blocks:{"blocks.xisb":f}}}};function At(e){return e.padEnd(80," ").slice(0,80)}function Ys(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 Zs(e){let t=e.key.toUpperCase().slice(0,8).padEnd(8," ");if(e.key==="END")return At("END");if(e.value===void 0)return At(`${t} ${e.comment??""}`);let r=Ys(e.value),n=`${t}= ${r}`;return e.comment?At(`${n} / ${e.comment}`):At(n)}function Zn(e){return e+(2880-e%2880)%2880}function qs(e){let t=[...e];t.some(i=>i.key==="END")||t.push({key:"END"});let r=t.map(Zs).join(""),n=r.padEnd(Zn(r.length)," ");return new TextEncoder().encode(n)}function ne(e){let t=e.map(s=>qs(s.cards)),r=e.map(s=>{let c=s.data??new Uint8Array(0),a=Zn(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 z(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 ie(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 wr=32768,Ir=2147483648,xt=9223372036854775808n,Jn="FITS:PreservedHDULayout";function Js(e){return e.reduce((t,r)=>t*r,1)}function Sr(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 Ar(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 Qs(e){if(!e.data)throw new K("XISF image data was not decoded");let t=Ar(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=Ar(s),a=new Array(n*t/c),u=0;for(let f=0;f<n;f++){let l=f*t;a[u++]=Number(Sr(r,l,s,i)),a[u++]=Number(Sr(r,l+c,s,i));}return a}let o=new Array(n);for(let s=0;s<n;s++)o[s]=Sr(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 ea(e,t){let r=Ar(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 ta(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 Qn(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function ra(e){return Oe(e)}async function na(e){return Fe(e)}function ia(e){return JSON.stringify({metadata:e.unit.metadata,standaloneProperties:e.unit.standaloneProperties,standaloneTables:e.unit.standaloneTables},null,0)}function oa(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=Js(e.geometry.slice(2));return {width:t,height:r,depth:e.channelCount*n}}function ei(e){return e?.strictValidation??e?.relaxed!==true}function sa(e,t){let r=e.get(t);return r===true||r==="T"||r==="true"||r===1}function aa(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 qn(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:aa(o.slice(10))}return null}function ca(e){if(!e)return null;let t=e.trim();if(!/^[-+]?\d+$/u.test(t))return null;try{return BigInt(t)}catch{return null}}function ua(e,t){if(t.bitpix!==64)return false;let r=qn(e,"BSCALE"),n=qn(e,"BZERO");return (r?Number(r):1)!==1?false:ca(n)===xt}function la(e){return e===true?"T":e===false?"F":e==null?"":String(e)}function fa(e,t,r){let n=e.filter(i=>i.id!==t);return n.push({id:t,type:"String",value:r}),n}function ma(e){let t=e.find(r=>r.id===Jn);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 da(e,t){return {cards:e.cards.map(r=>({key:r.key,value:r.value,comment:r.comment})),data:t}}async function pa(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 ra(n)}}async function xr(e,t){let r=ei(t),n=e instanceof q?e:await q.fromArrayBuffer(await Qn(e),{strictValidation:r}),i=[];for(let u=0;u<n.unit.images.length;u++){let f=n.unit.images[u],l=Qs(f),{width:m,height:d,depth:p}=oa(f),h=f.fitsKeywords.map(w=>({key:w.name,value:w.value,comment:w.comment}));if(f.sampleFormat==="Complex32"||f.sampleFormat==="Complex64"){let w=z(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=z(l,8);break;case "UInt16":{b=16,g=wr;let w=Array.from(l,S=>Number(S)-wr);y=z(w,16);break}case "UInt32":{b=32,g=Ir;let w=Array.from(l,S=>Number(S)-Ir);y=z(w,32);break}case "UInt64":{b=64,g=xt;let w=Array.from(l,S=>BigInt(S)-xt);y=z(w,64);break}case "Float32":b=-32,y=z(l,-32);break;case "Float64":b=-64,y=z(l,-64);break;default:throw new K(`Unsupported sample format: ${f.sampleFormat}`)}i.push(ie({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=ma(n.unit.metadata),s=[];if(o)for(let u of o.nonImageHDUs)s.push({index:u.index,hdu:da(u,await na(u.dataBase64))});if(n.unit.images.length===0){if(s.length===0)throw new K("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 ne(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(ia(n));c.push(ie({primary:false,extensionType:"IMAGE",width:u.byteLength,height:1,bitpix:8,data:u,extname:"XISF_META"}));}return ne(c)}async function ha(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 ga(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 K("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)+xt);}return t}function ba(e,t){let r=t.bzero;return t.bitpix===8?"UInt8":t.bitpix===16&&r===wr?"UInt16":t.bitpix===32&&r===Ir?"UInt32":ua(e,t)?"UInt64":t.bitpix===-32?"Float32":(t.bitpix===-64,"Float64")}async function Fr(e,t){let r=ei(t),n=t?.writeOptions,i=e instanceof G?e:G.fromArrayBuffer(await Qn(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 Z&&sa(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),R=await m.data.getRows(0,m.data.rows),H=m.data.columns?.[0]??"XISFCPLX",C=[];for(let v of R){let P=v[H];if(!Array.isArray(P)||P.length!==2)throw new K("Invalid complex payload in BINTABLE extension");C.push(Number(P[0]),Number(P[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:C.length*(S==="Complex32"?4:8)},byteOrder:"little"},data:ta(C,S),properties:[],tables:[],fitsKeywords:[]}),s.push(l);continue}if(!m.data||!(m.data instanceof Q)){c.push(await pa(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=ba(d,m.data);if(r&&m.data.bitpix===64&&h!=="UInt64")throw new K("FITS BITPIX=64 without canonical UInt64 BZERO cannot be converted losslessly");let b=h==="UInt64"?await ga(m.data):await ha(m.data),g=ea(b,h),y=d.getCards().map(S=>({name:S.key,value:la(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 K("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=fa(u,Jn,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?re.toDistributed(f,n):re.toMonolithic(f,n)}var Xe=class extends oe{constructor(t){super(t),this.name="SERError";}},me=class extends Xe{constructor(t){super(t),this.name="SERParseError";}},L=class extends Xe{constructor(t){super(t),this.name="SERValidationError";}},_=class extends Xe{constructor(t){super(t),this.name="SERConversionError";}};var rt="LUCAM-RECORDER",ti=[0,8,9,10,11,16,17,18,19,100,101],Ee={0:1,8:1,9:1,10:1,11:1,16:1,17:1,18:1,19:1,100:3,101:3},_e={8:"RGGB",9:"GRBG",10:"GBRG",11:"BGGR",16:"CYYM",17:"YCMY",18:"YMCY",19:"MYYC"},ri=621355968000000000n;var ya=e=>{};function Sa(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??ya}}function He(e,t,r){e.onWarning({code:t,message:r});}function Ft(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 ni(e){return ti.includes(e)}function wa(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 Ia(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 ii(e,t,r){let n=Sa(t),i=new Uint8Array(e);if(i.byteLength<178)throw new me(`SER buffer is too short: expected at least ${178} bytes, got ${i.byteLength}`);let o=new DataView(e),s=Ft(i.slice(0,14));if(s!==rt)throw new me(`Invalid SER FileID: expected "${rt}", 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=Ft(i.slice(42,82)),h=Ft(i.slice(82,122)),b=Ft(i.slice(122,162)),g=o.getBigUint64(162,true),y=o.getBigUint64(170,true);if(!Number.isInteger(f)||f<=0)throw new L(`Invalid SER width: ${f}`);if(!Number.isInteger(l)||l<=0)throw new L(`Invalid SER height: ${l}`);if(!Number.isInteger(m)||m<1||m>16)throw new L(`Invalid SER pixel depth: ${m}`);if(!Number.isInteger(d)||d<0)throw new L(`Invalid SER frame count: ${d}`);if(!ni(a)){let T=`Unsupported SER color ID: ${a}`;if(n.strictValidation)throw new L(T);He(n,"unsupported_color_id",`${T}; falling back to monochrome (0)`);}let w=ni(a)?a:0,S=Ee[w],I=m<=8?1:2,A=f*l*S*I;if(!Number.isSafeInteger(A)||A<=0)throw new L(`Invalid SER frame byte length: ${A}`);let x=i.byteLength-178,E=d;if(E*A>x){let T=`SER frame count exceeds payload capacity (declared=${E}, frameBytes=${A}, payload=${x})`;if(n.strictValidation)throw new L(T);let B=Ia(E,x,A);He(n,"frame_count_adjusted",`${T}; adjusted to ${B}`),E=B;}E===0&&He(n,"empty_sequence","SER sequence has zero frames");let k=E>0?i.slice(178,178+Math.min(A,8192)):null,R=wa(u,n.endiannessPolicy,k),H=E*A,C=178+H,v=i.byteLength-C,P=false,M=[];if(E>0&&v>=E*8){P=true;let T=new DataView(e,C,E*8);for(let U=0;U<E;U++)M.push(T.getBigUint64(U*8,true));let B=true;for(let U=1;U<M.length;U++)if(M[U]<M[U-1]){B=false;break}if(B||He(n,"timestamps_not_ordered","SER frame timestamps are not in ascending order"),v!==E*8){let U=`SER trailer contains extra bytes (${v-E*8}) beyond timestamps`;if(n.strictValidation)throw new L(U);He(n,"extra_trailer_bytes",U);}}else if(v>0){let T=`SER trailer has ${v} bytes but expected 0 or ${E*8}`;if(n.strictValidation)throw new L(T);He(n,"truncated_timestamps",T);}let Y=[];for(let T=0;T<E;T++)Y.push({index:T,offset:178+T*A,byteLength:A,timestamp:M[T]});return {header:{fileId:s,luId:c,colorId:w,littleEndianFlag:u,byteOrder:R,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:Y,timestamps:M,timestampsPresent:P,buffer:e,blob:r}}function Er(e,t){return ii(e,t)}async function Tr(e,t){let r=await e.arrayBuffer();return ii(r,t,e)}function Aa(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 xa(e){return _e[e]}function nt(e,t,r,n){return Number(e[r*n+t]??0)}function oi(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 Fa(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]=oi(s(y,g));if(f===0?w:f===1?S:I)return nt(e,y,g,t)}}return nt(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]=oi(l);o[f]=m?nt(e,u,a,t):c(u,a,0),o[f+1]=d?nt(e,u,a,t):c(u,a,1),o[f+2]=p?nt(e,u,a,t):c(u,a,2);}return o}var Te=class e{parsed;constructor(t){this.parsed=t;}static fromArrayBuffer(t,r){return new e(Er(t,r))}static async fromBlob(t,r){return new e(await Tr(t,r))}static async fromURL(t,r){let n=await fetch(t,r?.requestInit);if(!n.ok)throw new me(`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 L(`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-ri,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 me("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=xa(r);if(!c)throw new L(`No RGB decode helper available for color ID ${r}`);return Fa(t,n,i,c,o)}getFrame(t,r){let n=this.getFrameInfo(t),i=this.readFrameRawBytes(n),o=Aa(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 Ea=e=>{};function Ta(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??Ea}}function Rr(e,t,r){e.onWarning({code:t,message:r});}function Et(e,t,r,n){let o=new TextEncoder().encode(n);for(let s=0;s<r;s++)e[t+s]=o[s]??0;}function Pr(e,t){return e===void 0?t:typeof e=="bigint"?e:BigInt(Math.trunc(e))}function Pa(e,t){return t==="spec"?e?1:0:e?0:1}function Ra(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 L(i);Rr(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 Tt(e,t){let r=Ta(t),n=e.header,i=n.frameCount??e.frames.length;if(!Number.isInteger(i)||i<0)throw new L(`Invalid SER frame count: ${i}`);if(!Number.isInteger(n.width)||n.width<=0)throw new L(`Invalid SER width: ${n.width}`);if(!Number.isInteger(n.height)||n.height<=0)throw new L(`Invalid SER height: ${n.height}`);if(!Number.isInteger(n.pixelDepth)||n.pixelDepth<1||n.pixelDepth>16)throw new L(`Invalid SER pixel depth: ${n.pixelDepth}`);let o=Ee[n.colorId];if(!o)throw new L(`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 L(g);Rr(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 L(`Invalid computed frame length: ${c}`);let a=[];for(let g=0;g<i;g++){let y=e.frames[g]??new Uint8Array(0);a.push(Ra(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 L(g);Rr(r,"timestamp_count_mismatch",g);}u=new Array(i);for(let g=0;g<i;g++)u[g]=Pr(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);Et(d,0,14,rt),p.setInt32(14,n.luId??0,true),p.setInt32(18,n.colorId,true);let h=n.littleEndian??true;p.setInt32(22,Pa(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),Et(d,42,40,n.observer??""),Et(d,82,40,n.instrument??""),Et(d,122,40,n.telescope??""),p.setBigUint64(162,Pr(n.startTime,0n),true),p.setBigUint64(170,Pr(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 li="SERCOLOR",fi="SERPDEP",Ur="SERFRMS",mi="SERCHANS",Ca="SERCHORD",di="SERLUID",pi="SERBYORD",hi="SEROBS",gi="SERINST",bi="SERTEL",yi="SERSTRT",Si="SERSTUTC",Ua="SERCFAP",wi="SERFRAME",Ii="SER_TSTP",Ai=32768;function Ct(e){return e?.strictValidation??e?.relaxed!==true}function xi(e){return e instanceof ArrayBuffer?Promise.resolve(e):e.arrayBuffer()}function Fi(e,t){return e instanceof Te?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(Te.fromArrayBuffer(e,{strictValidation:Ct(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})):Te.fromBlob(e,{strictValidation:Ct(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})}function Na(e){return e instanceof G?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(G.fromArrayBuffer(e)):xi(e).then(t=>G.fromArrayBuffer(t))}function ye(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 Ba(e,t){return e.metadata.find(r=>r.id===t)}function va(e,t){return e.properties.find(r=>r.id===t)}function le(e,t,r){let n=va(t,r);return n?.value!==void 0?n.value:Ba(e,r)?.value}function ka(e,t,r){let n=le(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=>ye(i)).filter(i=>i!==null):[]}function Nr(e,t,r){e?.onWarning?.({code:t,message:r});}function La(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 Da(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 Oa(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 Ma(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:Ii}],data:t}}function Xa(e){if(e.channelCount===3)return 100;let t=e.colorFilterArray?.pattern;if(!t)return 0;let r=Object.entries(_e).find(([,n])=>n===t);return r?Number(r[0]):0}function si(e,t){let r=e.get(t);return ye(r)??void 0}function Pt(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 Rt(e,t){let r=e.get(t);return typeof r=="string"?r:void 0}function _a(e){let t=e.getHeader(),r=_e[t.colorId];return [{key:li,value:t.colorId},{key:fi,value:t.pixelDepth},{key:Ur,value:t.frameCount},{key:mi,value:t.channelCount},{key:Ca,value:t.colorId===101?"BGR":"RGB"},{key:di,value:t.luId},{key:pi,value:t.byteOrder},{key:hi,value:t.observer},{key:gi,value:t.instrument},{key:bi,value:t.telescope},{key:yi,value:t.startTime.toString()},{key:Si,value:t.startTimeUtc.toString()},...r?[{key:Ua,value:r}]:[]]}function ai(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 ci(e){return e.map(t=>t-Ai)}function Ha(e){return e.hdus.filter(t=>t.data instanceof Q).map(t=>({header:t.header,image:t.data}))}function $a(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(wi)||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 Va(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 _(a);return Nr(r,"fits_multi_hdu_incompatible",a),false});if(i.length===0)throw new _("No compatible image HDUs available for multi-HDU FITS conversion");return i}async function Cr(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 ui(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 Wa(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 za(e,t){let r=await Fi(e,t),n=r.getHeader(),i=n.frameCount,o=_a(r),s=t?.layout??"cube",c=n.bytesPerSample===1?8:16,a=c===16?Ai:void 0,u=[];if(s==="multi-hdu")for(let f=0;f<i;f++){let l=r.getFrame(f),m=ai(l),d=c===16?ci(m):m,p=z(d,c);u.push(ie({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:wi,value:f},{key:Ur,value:i},{key:mi,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=ai(p),b=c===16?ci(h):h;l.push(...b);}let m=z(l,c);u.push(ie({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(Ma(r.parsed.timestamps)),ne(u)}async function Ga(e,t){let r=Ct(t),n=await Na(e),i=Ha(n),o=i[0];if(!o)throw new _("No FITS image HDU found for SER conversion");let s=o.header,c=o.image,a=Pt(s,li)??0,u=Ee[a]??1,f=Pt(s,fi);if(!f)if(c.bitpix===8)f=8;else if(c.bitpix===16)f=16;else throw new _(`Cannot infer SER pixel depth from FITS BITPIX=${c.bitpix}; metadata is missing`);let l=Pt(s,Ur),m=$a(t,i,l),d=f<=8?1:2,p=m==="multi-hdu"?Va(i,r,t):i,h=(Rt(s,pi)??"little")!=="big",b=Rt(s,hi)??"",g=Rt(s,gi)??"",y=Rt(s,bi)??"",w=Pt(s,di)??0,S=si(s,yi)??0n,I=si(s,Si)??S,A=[],x=l??0;if(m==="cube")if(u===1){x=l??c.depth;for(let R=0;R<x;R++)A.push(await Cr(c,R,d,h));}else {if(x=l??c.depth,!l)if(c.depth%3!==0){if(r)throw new _(`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 R=0;R<x;R++)A.push(await ui(c,R,d,h));}else {if(u===1)for(let R of p)if(R.image.depth>1)for(let H=0;H<R.image.depth;H++)A.push(await Cr(R.image,H,d,h));else A.push(await Cr(R.image,0,d,h));else {let R=p.every(C=>C.image.depth===3),H=p.every(C=>C.image.depth===1);if(R)for(let C of p)A.push(await ui(C.image,0,d,h));else if(H){let C=p.length;if(C%3!==0){let v=`RGB/BGR multi-HDU layout has ${C} channels; expected multiple of 3`;if(r)throw new _(v);Nr(t,"fits_multi_hdu_rgb_tail_drop",v),C-=C%3;}for(let v=0;v+2<C;v+=3)A.push(await Wa(p[v].image,p[v+1].image,p[v+2].image,d,h));}else throw new _("Cannot decode RGB/BGR sequence from multi-HDU FITS layout; expected depth=3 per HDU or HDU triplets")}x=A.length;}let E,k=n.hdus.find(R=>R.data instanceof Z&&R.header.getString("EXTNAME","").trim().toUpperCase()===Ii);if(k&&k.data instanceof Z){let R=k.data.columns?.[0];if(R&&(E=(await k.data.getColumn(R)).map(C=>ye(C)).filter(C=>C!==null),E.length!==x)){if(r)throw new _(`SER timestamp extension row count mismatch: expected ${x}, got ${E.length}`);E=E.slice(0,x);}}return Tt({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 ja(e){return e===1?"UInt8":"UInt16"}function Ka(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=Da(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=Oa(u);for(let l=0;l<f.length;l++)s.setUint16(c*2,f[l],true),c++;}return o}async function Ya(e,t){let r=await Fi(e,t),n=r.getHeader(),i=Ka(r),o={id:"SER_SEQUENCE",geometry:[n.width,n.height,n.frameCount],channelCount:n.channelCount,sampleFormat:ja(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=_e[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=La(c,r);let a={metadata:c,images:[o],standaloneProperties:[],standaloneTables:[],version:"1.0",signature:{present:false,verified:true}};return t?.distributed?re.toDistributed(a,t.writeOptions):re.toMonolithic(a,t?.writeOptions)}function Za(e){if(!e.data)throw new _("XISF image data is not decoded");return e.data}function qa(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=Za(e),f=s*r*t*c;if(u.byteLength<f)throw new _(`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 Ja(e,t){let r=Ct(t),n=e instanceof q?e:await q.fromArrayBuffer(await xi(e),{strictValidation:r,decodeImageData:true}),i=t?.imageIndex??0;if(!Number.isInteger(i)||i<0)throw new _(`XISF image index must be a non-negative integer, got ${i}`);let o=n.unit.images[i];if(!o)throw new _(`No XISF image available at index ${i}`);if(o.sampleFormat!=="UInt8"&&o.sampleFormat!=="UInt16")throw new _(`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 _("XISF image must have width and height geometry");let a=le(n.unit,o,"SER:ColorID"),u=ye(a)??BigInt(Xa(o)),f=Number(u),l=Ee[f]??(o.channelCount===3?3:1),m=o.geometry[2]??1,d=le(n.unit,o,"SER:PixelDepth"),p=Number(ye(d)??(o.sampleFormat==="UInt8"?8n:16n))||8,h=le(n.unit,o,"SER:LittleEndian"),b=typeof h=="boolean"?h:String(h??"true").toLowerCase()!=="false",g=qa(o,m,l,b),y=ka(n.unit,o,"SER:FrameTimestamps");if(y.length>0&&y.length!==m){if(r)throw new _(`XISF SER:FrameTimestamps length mismatch: expected ${m}, got ${y.length}`);Nr(t,"xisf_timestamp_length_mismatch",`SER:FrameTimestamps length mismatch: expected ${m}, got ${y.length}; truncating`),y=y.slice(0,m);}let w=Number(ye(le(n.unit,o,"SER:LuID"))??0n),S=String(le(n.unit,o,"SER:Observer")??""),I=String(le(n.unit,o,"SER:Instrument")??""),A=String(le(n.unit,o,"SER:Telescope")??""),x=ye(le(n.unit,o,"SER:StartTime"))??0n,E=ye(le(n.unit,o,"SER:StartTimeUTC"))??x;return Tt({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 Qa={fits:"fits",png:"png",jpeg:"jpg"};function Br(e){return Qa[e]}function Ei(e){let t=e.toLowerCase();return t==="fits"?"fits":t==="png"?"png":t==="jpg"||t==="jpeg"?"jpeg":null}function Ti(e){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid ipix: ${e}`);return Math.floor(e/1e4)*1e4}function Ut(e){if(e.spectralOrder!==void 0||e.spectralIndex!==void 0){let t=e.spectralOrder??0,r=e.spectralIndex??0,n=`${Ti(e.ipix)}_${Math.floor(r/10)*10}`;return `Norder${e.order}_${t}/Dir${n}/Npix${e.ipix}_${r}.${Br(e.format)}`}return `Norder${e.order}/Dir${Ti(e.ipix)}/Npix${e.ipix}.${Br(e.format)}`}function Nt(e){return `Norder3/Allsky.${Br(e)}`}function vr(e){let t=e.replaceAll("\\","/"),r=/^Norder(\d+)_(\d+)\/Dir(\d+)_(\d+)\/Npix(\d+)_(\d+)\.(\w+)$/i.exec(t);if(r){let o=Ei(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=Ei(n[4]);return i?{order:Number(n[1]),ipix:Number(n[3]),frame:"equatorial",format:i}:null}var ec=["creator_did","obs_title","dataproduct_type","hips_version","hips_frame","hips_order","hips_tile_width","hips_tile_format"],tc=["hips_cube_depth","hips_cube_firstframe"],rc=new Set(["equatorial","galactic","ecliptic"]),nc=new Set(["image","cube"]),ic=new Set(["fits","png","jpeg"]);function Pi(e){return e.trim()}var $e=class e{data=new Map;constructor(t){if(t)for(let[r,n]of Object.entries(t))this.data.set(r.trim(),Pi(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"?Pi(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=ec.filter(l=>!this.data.has(l)),r=[],n=[],i=this.get("hips_frame");i&&!rc.has(i)&&r.push(`hips_frame=${i}`);let o=this.get("dataproduct_type");o&&!nc.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=>!ic.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 tc)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 Ri(e){let t=$e.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 cc(e){let t=e%360;return t<0?t+360:t}function uc(e,t,r){return Math.max(t,Math.min(r,e))}function lc(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 Bt(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:cc(n+o*g+s*y),lat:uc(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 Ci(e){return Bt({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 Ui(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 Bt({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 Ni(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 Bi(e,t,r,n){let i=order2nside(e.order),o=(t+.5)/n,s=(r+.5)/n,[c,a,u]=pixcoord2vec_nest(i,e.ipix,o,s),{theta:f,phi:l}=vec2ang([c,a,u]);return {lon:l*180/Math.PI,lat:90-f*180/Math.PI}}function fc(e){let t=order2nside(e.order),{theta:r,phi:n}=pix2ang_nest(t,e.ipix);return {lon:n*180/Math.PI,lat:90-r*180/Math.PI}}function vi(e,t,r=1){let n=order2nside(e.order),{ctype1:i,ctype2:o}=lc(e.frame),s=45/t/n,c=fc(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 gc(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 bc(e){let[t,r]=gc(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 yc(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Sc(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function ki(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 Li(e,t){let r=yc(t);if(e.format==="fits"){let s=G.fromArrayBuffer(Sc(r)).getDataUnit();if(!(s instanceof Q))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=decode(r),s=ki(o.data,o.width,o.height,o.channels);return {meta:e,width:o.width,height:o.height,depth:1,data:s}}let n=decode$1(r,{useTArray:true,formatAsRGBA:true}),i=ki(n.data,n.width,n.height,4);return {meta:e,width:n.width,height:n.height,depth:1,data:i}}function it(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=z(t,-32),u=vi(e,r,n),f=ie({primary:true,width:r,height:r,depth:n,bitpix:-32,data:a,additionalCards:u});return new Uint8Array(ne([f]))}let o=bc(t.subarray(0,i));if(e.format==="png")return 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=encode$1({width:r,height:r,data:s},90);return new Uint8Array(c.data)}function vt(e){return /^https?:\/\//iu.test(e)}async function kt(){let[e,t]=await Promise.all([V("fs/promises","HiPS local-path access","Use URL-based HiPS input or provide a custom HiPSExportTarget in browser/React Native."),V("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 de=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(vt(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 kt();return n.readFile(i.join(r,t),"utf8")}}if(typeof this.source=="string"){if(vt(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 kt();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(vt(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 kt(),o=await n.readFile(i.join(r,t));return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}}if(typeof this.source=="string"){if(vt(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 kt(),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=$e.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(Ut(c));return Li(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(Nt(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 Ve(e,t,r,n,i,o){return n<0||i<0||n>=t||i>=r?o:e[i*t+n]??o}function wc(e,t,r,n,i,o){return Ve(e,t,r,Math.round(n),Math.round(i),o)}function Oi(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=Ve(e,t,r,s,c,Number.NaN),d=Ve(e,t,r,a,c,Number.NaN),p=Ve(e,t,r,s,u,Number.NaN),h=Ve(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 Di(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 Ic(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]=Ve(e,t,r,s+d,c+l,Number.NaN);if([m[0],m[1],m[2],m[3]].some(d=>!Number.isFinite(d)))return Oi(e,t,r,n,i,o);f[l+1]=Di(m[0],m[1],m[2],m[3],a);}return Di(f[0],f[1],f[2],f[3],u)}function Lr(e,t,r,n,i,o,s){return o==="nearest"?wc(e,t,r,n,i,s):o==="bicubic"?Ic(e,t,r,n,i,s):Oi(e,t,r,n,i,s)}function Mi(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}=Bi(t,u,a,r),m=e.wcs.worldToPixel(f,l);for(let d=0;d<e.depth;d++){let p=e.planes[d],h=Lr(p,e.width,e.height,m.x,m.y,o,i);c[d*s+a*r+u]=h;}}return c}function Xi(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 Pe(e){return e*Math.PI/180}function Tc(e,t,r,n){let i=Pe(e),o=Pe(t),s=Pe(r),c=Pe(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 Pc(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function Rc(e){return e instanceof G?e:G.fromArrayBuffer(await Pc(e))}function Cc(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 Uc(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 Nc(e,t,r,n=64){if(t<=n)return e;let i=e,o=t;for(;o>n;)i=Xi(i,o,r,"mean"),o=Math.max(1,Math.floor(o/2));return i}async function Bc(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 vc(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 kc(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 Lc(e,t){let r=Cc(t),i=(await Rc(e)).getHDU();if(!i?.data)throw new Error("No image HDU found in FITS input");kc(i.data);let o=i.data,s=Ci(i.header),c=o.depth,a=[];for(let S=0;S<c;S++)a.push(Uc(await o.getFrame(S)));let u=Ni(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,Tc(d.lon,d.lat,S.lon,S.lat));let b=[],g=new Map,y=0;for(let S=m;S<=f;S++){let I=order2nside(S),A=Math.min(Math.PI,Pe(h)+max_pixrad(I)),x=ang2vec(Pe(90-d.lat),Pe(d.lon)),E=[];if(query_disc_inclusive_nest(I,x,A,k=>{E.push(k);}),E.length>r.maxTilesPerOrder)throw new Error(`Order ${S} would generate ${E.length} tiles, above maxTilesPerOrder=${r.maxTilesPerOrder}`);for(let k of E){let R={order:S,ipix:k,frame:r.frame},H=Mi({width:o.width,height:o.height,depth:c,planes:a,wcs:s,blankValue:r.blankValue},{...R},r.tileWidth,{interpolation:r.interpolation,blankValue:r.blankValue});for(let C of r.formats){if(c>1&&C!=="fits")continue;let v=it({...R,format:C},H,r.tileWidth,c);await t.output.writeBinary(Ut({...R,format:C}),v);}if(y++,S===f&&r.includeMoc){let{theta:C,phi:v}=pix2ang_nest(I,k);b.push(v*180/Math.PI,90-C*180/Math.PI);}S===3&&r.includeAllsky&&g.set(k,Nc(H,r.tileWidth,c,64));}}let w=Ri({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=order2nside(3),x=12*A*A,E=Math.ceil(Math.sqrt(x)),k=Math.ceil(x/E),R=E*64,H=k*64,C=R*H,v=new Float32Array(C*c);v.fill(Number.NaN);for(let[P,M]of g.entries()){let Y=Math.floor(P/E),T=P%E,B=4096;for(let U=0;U<c;U++){let J=U*B,fe=U*C;for(let pe=0;pe<64;pe++){let zi=Y*64+pe;for(let ot=0;ot<64;ot++){let Gi=T*64+ot;v[fe+zi*R+Gi]=M[J+pe*64+ot]??Number.NaN;}}}}for(let P of r.formats){if(c>1&&P!=="fits")continue;let M=it({order:3,ipix:0,frame:r.frame,format:P},v,R,c);await t.output.writeBinary(Nt(P),M);}}if(r.includeMoc){let S=await Bc(b,f);S.byteLength>0&&await t.output.writeBinary("Moc.fits",S);}return r.includeIndexHtml&&await t.output.writeText("index.html",vc(r.title)),{properties:w,maxOrder:f,minOrder:l,generatedTiles:y}}async function Dr(e,t){return Lc(e,t)}var Dc="https://alasky.cds.unistra.fr/hips-image-services/hips2fits",Oc="https://alaskybis.cds.unistra.fr/hips-image-services/hips2fits";function Mc(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 Xc(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 Or(e,t,r={}){let n=r.timeoutMs??25e3,i=[r.endpoint??Dc,r.endpointFallback??Oc],o;for(let s of i)try{let c=new URL(s);Mc(c,e,t);let a=await Xc(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 Wc(e){return e==="galactic"?"G":e==="ecliptic"?"E":"C"}function Hi(e,t){return e<0?t- -e%t:e%t}function $i(e,t,r){return e<t?t:e>r?r:e}function zc(e,t,r,n){let i=(90-n)*Math.PI/180,o=Hi(r*Math.PI/180,2*Math.PI),s=Math.cos(i),{t:c,u:a}=za2tu(s,o),u=Math.PI/4,f=c/u,l=a/u;f=Hi(f,8),f-=4,l+=5;let m=$i((l+f)/2,0,5),d=Math.floor(m),p=$i((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=order2nside(e),A=I*w,x=I*S,E=Math.max(0,Math.min(I-1,Math.floor(A))),k=Math.max(0,Math.min(I-1,Math.floor(x)));return {ipix:y*I*I+bit_combine(E,k),x:(A-E)*t,y:(x-k)*t}}function Gc(e){if(e.wcs)return Ui(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 Bt({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 jc(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=Zc(i.data);return it({order:t.order,ipix:t.ipix,frame:n,format:"fits"},o,i.width,i.depth).slice().buffer}function Kc(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 Yc(){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 Zc(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 qc(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 Jc(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=order2nside(n),c=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"?nest2ring(s,l):l;a[b]=h>0?p/h:Number.NaN;}catch{continue}let u=Kc(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:Wc(i)}],data:u};return {fits:ne([Yc(),f]),map:{order:n,nside:s,ordering:o,values:a}}}async function Qc(e,t,r,n,i,o,s,c){let a=zc(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=qc(l.data),c.set(u,f);}return Lr(f,i,i,a.x,a.y,s,Number.NaN)}async function Vi(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=Gc(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 Qc(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=ie({primary:true,width:t.width,height:t.height,bitpix:-32,data:z(c,-32),additionalCards:f});return ne([l])}async function Mr(e,t={}){let r=e instanceof de?e:new de(e),n=t.backend??"local",i;if(t.tile)i=await jc(r,t.tile);else if(t.map)i=(await Jc(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 Or(t.cutout?.hipsId??t.hipsId,o,t);}else if(n==="auto")try{i=await Vi(r,o);}catch(s){let c=t.cutout?.hipsId??t.hipsId;if(!c)throw s;i=await Or(c,o,t);}else i=await Vi(r,o);}return t.output&&await t.output.writeBinary("output.fits",new Uint8Array(i)),i}function eu(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 tu(e,t){if(e instanceof q)return e;let r=e instanceof ArrayBuffer?e:await e.arrayBuffer();return q.fromArrayBuffer(r,{...t,decodeImageData:true})}async function ru(e,t){let{imageIndex:r=0,xisfReadOptions:n,...i}=t,o=await tu(e,n),s=o.unit.images[r];if(!s)throw new K(`XISF imageIndex ${r} is out of range (images=${o.unit.images.length})`);if(s.sampleFormat==="Complex32"||s.sampleFormat==="Complex64")throw new K("Complex XISF images cannot be converted to HiPS image/cube");if(!s.data)throw new K("Selected XISF image has no decoded data");let c={metadata:o.unit.metadata.map(f=>({...f})),images:[eu(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 re.toMonolithic(c),u=await xr(a,{strictValidation:n?.strictValidation,includeXisfMetaExtension:false});return Dr(u,i)}async function nu(e,t={}){let{distributed:r,writeOptions:n,conversionOptions:i,...o}=t,s=await Mr(e,o);return Fr(s,{...i??{},distributed:r,writeOptions:n})}function $r(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function ze(e){return e.replaceAll("\\","/").replace(/^\/+/u,"")}async function We(){let[e,t]=await Promise.all([V("fs/promises","NodeFSTarget filesystem access","Use BrowserZipTarget or a custom HiPSExportTarget in browser/React Native."),V("path","NodeFSTarget filesystem access","Use BrowserZipTarget or a custom HiPSExportTarget in browser/React Native.")]);return {fs:e,path:t}}var Xr=class{constructor(t){this.root=t;}async absolute(t){let{path:r}=await We();return r.join(this.root,ze(t))}async writeBinary(t,r){let{fs:n,path:i}=await We(),o=await this.absolute(t);await n.mkdir(i.dirname(o),{recursive:true}),await n.writeFile(o,$r(r));}async writeText(t,r){let{fs:n,path:i}=await We(),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 We(),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 We(),n=await this.absolute(t);return r.readFile(n,"utf8")}async exists(t){let{fs:r}=await We();try{return await r.access(await this.absolute(t)),!0}catch{return false}}},_r=class{entries=new Map;async writeBinary(t,r){this.entries.set(ze(t),$r(r));}async writeText(t,r){this.entries.set(ze(t),new TextEncoder().encode(r));}async readBinary(t){let r=this.entries.get(ze(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(ze(t))}async finalize(){let t={};for(let[n,i]of this.entries.entries())t[n]=i;let r=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 ou(){return typeof navigator<"u"&&!!navigator.storage?.getDirectory}var Hr=class{constructor(t="fitsjs-hips"){this.baseDir=t;}rootHandlePromise;async rootHandle(){if(!ou())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=ze(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($r(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 Vr(e){return /^https?:\/\//iu.test(e)}async function Wr(e){let[t,r]=await Promise.all([V("fs/promises",e,"Use URL-based HiPS linting or run lintHiPS local-path checks in Node.js."),V("path",e,"Use URL-based HiPS linting or run lintHiPS local-path checks in Node.js.")]);return {fs:t,pathApi:r}}async function su(e){let t=[],{fs:r,pathApi:n}=await Wr("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")&&(vr(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 au(e,t){let r=[],{fs:n,pathApi:i}=await Wr("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=vr(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 cu(e){let t=new de(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"&&!Vr(e))try{let{fs:s,pathApi:c}=await Wr("HiPS local Moc.fits check");await s.access(c.join(e,"Moc.fits")),o=!0;}catch{o=!1;}else if(typeof e=="string"&&Vr(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"&&!Vr(e)&&Le())try{let n=await new de(e).getProperties();r.push(...await au(e,n));}catch{r.push(...await su(e));}return {ok:r.every(n=>n.level!=="error"),issues:r}}
|
|
18
|
+
export{X as BLOCK_LENGTH,Z as BinaryTable,Hr as BrowserOPFSTarget,_r as BrowserZipTarget,Ze as CompressedImage,zr as DEFAULT_MAX_HEADER_LINES,Lt as DataError,Ie as DataUnit,D as DecompressionError,G as FITS,oe as FITSError,Ue as HDU,Ce as Header,W as HeaderError,de as HiPS,$e as HiPSProperties,Q as Image,ji as LINES_PER_BLOCK,Se as LINE_WIDTH,Gr as NULL_VALUE,we as N_RANDOM,Xr as NodeFSTarget,ct as RiceSetup,Te as SER,_ as SERConversionError,Xe as SERError,me as SERParseError,L as SERValidationError,Ye as Table,Ki as VERSION,q as XISF,he as XISFChecksumError,j as XISFCompressionError,K as XISFConversionError,se as XISFError,N as XISFParseError,ae as XISFResourceError,ve as XISFSignatureError,F as XISFValidationError,re as XISFWriter,jr as ZERO_VALUE,Dr as convertFitsToHiPS,Ga as convertFitsToSer,Fr as convertFitsToXisf,Mr as convertHiPSToFITS,nu as convertHiPSToXisf,za as convertSerToFits,Ya as convertSerToXisf,xr as convertXisfToFits,ru as convertXisfToHiPS,Ja as convertXisfToSer,z as createImageBytesFromArray,ie as createImageHDU,co as getCompressedImageDecoderProvider,je as getExtent,Ke as getPixel,cu as lintHiPS,zt as parseBlob,Wt as parseBuffer,Tr as parseSERBlob,Er as parseSERBuffer,_t as riceDecompress,ao as setCompressedImageDecoderProvider,ne as writeFITS,Tt as writeSER};//# sourceMappingURL=index.js.map
|
|
3
19
|
//# sourceMappingURL=index.js.map
|