fitsjs-ng 1.0.1 → 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 +32 -1
- package/dist/index.cjs +6 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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
|
|
2
|
-
var ye=80,X=2880,Di=36,Lr=600,Dr=-2147483647,Or=-2147483646,we=1e4,Oi="1.0.1";var oe=class extends Error{constructor(t){super(t),this.name="FITSError";}},V=class extends oe{constructor(t){super(t),this.name="HeaderError";}},Rt=class extends oe{constructor(t){super(t),this.name="DataError";}},D=class extends oe{constructor(t){super(t),this.name="DecompressionError";}};function Te(e,t,r){r!==e.cardIndex&&e.warn(`${t} should appear at index ${r} in the FITS header`);}function tt(e,t,r,n){if(t<r||t>n)throw new V(`The ${e} value of ${t} is not between ${r} and ${n}`)}function Ct(e){return e==="T"}var Ut={SIMPLE(e,t){return e.primary=true,Te(e,"SIMPLE",0),Ct(t)},XTENSION(e,t){return e.extension=true,e.extensionType=t,Te(e,"XTENSION",0),e.extensionType},BITPIX(e,t){let r=parseInt(String(t),10);if(Te(e,"BITPIX",1),![8,16,32,64,-32,-64].includes(r))throw new V(`BITPIX value ${r} is not permitted`);return r},NAXIS(e,t,r){let n=parseInt(String(t),10);if(!r&&(Te(e,"NAXIS",2),tt("NAXIS",n,0,999),e.isExtension()&&(e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&n!==2))throw new V("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(Te(e,"PCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE")&&r!==0)throw new V(`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(Te(e,"GCOUNT",i),e.isExtension()&&(e.extensionType==="IMAGE"||e.extensionType==="TABLE"||e.extensionType==="BINTABLE")&&r!==1)throw new V(`GCOUNT must be 1 for the ${e.extensionType} extensions`);return r},EXTEND(e,t){if(!e.isPrimary())throw new V("EXTEND must only appear in the primary header");return Ct(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 tt("TFIELDS",r,0,999),r},TBCOL(e,t,r,n){let i=e.get("TFIELDS");return n!==void 0&&tt("TBCOL",parseInt(n,10),0,i),t},ZIMAGE(e,t){return Ct(t)},ZCMPTYPE(e,t){let r=String(t);if(!["GZIP_1","RICE_1","PLIO_1","HCOMPRESS_1"].includes(r))throw new V(`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 V(`ZBITPIX value ${r} is not permitted`);return r},ZNAXIS(e,t,r){let n=parseInt(String(t),10);return r||tt("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 Pe=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 V(`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 V(`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 V(`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 c=t.slice(8).trim();r==="COMMENT"?this.comments.push(c):r==="HISTORY"&&this.history.push(c);return}let o,s;if(i.trimStart().startsWith("'")){let c=i.indexOf("'"),u=-1,f=c+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 c=i.indexOf(" /");c!==-1?(o=i.slice(0,c).trim(),s=i.slice(c+2).trim()):(o=i.trim(),s="");}let a;o.startsWith("'")?a=o.slice(1,-1).replaceAll("''","'").trim():o==="T"||o==="F"?a=o:a=parseFloat(o),a=this.validate(r,a),this.set(r,a,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 Ut&&(r=Ut[n](this,r,i,o)),r}};var Re=class{header;data;constructor(t,r){this.header=t,this.data=r;}hasData(){return this.data!==void 0}};var Mr=e=>e,Xr=e=>(e&255)<<8|e>>8&255,_r=e=>(e&255)<<24|(e&65280)<<8|e>>8&65280|e>>24&255,rt={8:Mr,B:Mr,16:Xr,I:Xr,32:_r,J:_r},Mi=new TextDecoder("ascii");function He(e){return Mi.decode(e)}function Bt(e){return (2880-e%2880)%2880}function Hr(e){let t=[],r=128;for(;r>=1;)t.push(e&r?1:0),r>>=1;return t}var Se=class{buffer;blob;static swapEndian=rt;constructor(t){t instanceof ArrayBuffer?this.buffer=t:typeof Blob<"u"&&t instanceof Blob&&(this.blob=t);}};function Xi(e){return e instanceof BigInt64Array||e instanceof BigUint64Array}function $e(e){if(Xi(e)){if(e.length===0)return [NaN,NaN];let o=e[0],s=e[0];for(let a=1;a<e.length;a++){let c=e[a];c<o?o=c:c>s&&(s=c);}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 Ve(e,t,r,n){let i=r*n+t;return i<0||i>=e.length?NaN:e[i]}var J=class e extends Se{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,a=n===0&&i===1,c=new DataView(t),u=!(Number.isInteger(n)&&Number.isInteger(i));if(r===8){if(a)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*c.getUint8(m);return l}if(r===16){if(a){let m=new Int16Array(s);for(let d=0;d<s;d++)m[d]=c.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*c.getInt16(m*2,false);return l}if(r===32){if(a){let m=new Int32Array(s);for(let d=0;d<s;d++)m[d]=c.getInt32(d*4,false);return m}let l=new Float64Array(s);for(let m=0;m<s;m++)l[m]=n+i*c.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]=c.getBigInt64(h*8,false)+p;return d}let m=new Float64Array(s);if(a)for(let d=0;d<s;d++)m[d]=Number(c.getBigInt64(d*8,false));else for(let d=0;d<s;d++)m[d]=n+i*Number(c.getBigInt64(d*8,false));return m}if(r===-32){let l=new Float32Array(s);if(a)for(let m=0;m<s;m++)l[m]=c.getFloat32(m*4,false);else for(let m=0;m<s;m++)l[m]=n+i*c.getFloat32(m*4,false);return l}let f=new Float64Array(s);if(a)for(let l=0;l<s;l++)f[l]=c.getFloat64(l*8,false);else for(let l=0;l<s;l++)f[l]=n+i*c.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 $e(t)}getPixel(t,r,n){return Ve(t,r,n,this.width)}};var Nt={L:1,B:1,I:2,J:4,K:8,A:1,E:4,D:8,C:8,M:16},Ce={B:Uint8Array,I:Int16Array,J:Int32Array,K:BigInt64Array,E:Float32Array,D:Float64Array,1:Uint8Array,2:Int16Array,4:Int32Array};var Ue=class extends Se{maxMemory=1048576;rowByteSize;rows;cols;length;heapLength;columns;accessors=[];descriptors=[];elementByteLengths=[];columnTypes=[];heap;typedArray=Ce;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 c;if(this.cachedBuffer){let u=(t-this.firstRowInBuffer)*this.rowByteSize;c=this.cachedBuffer.slice(u,u+r*this.rowByteSize);}else if(this.buffer){let u=t*this.rowByteSize,f=u+r*this.rowByteSize;c=this.buffer.slice(u,f);}else throw new Error("No data source available");return this._getRows(c,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,a=await this.blob.slice(n,o).arrayBuffer();return this.cachedBuffer=a,this.firstRowInBuffer=t,this.lastRowInBuffer=t+i,this._getRows(a,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),a=this.rows/s,c=Math.floor(a)===a?a:Math.floor(a)+1,u=0,f=0;for(;c>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;c--,f++;}return o}};var _i={A:e=>e.trim(),I:e=>parseInt(e,10),F:e=>parseFloat(e),E:e=>parseFloat(e),D:e=>parseFloat(e)},We=class extends Ue{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],a=parseInt(o[2],10),c=_i[s]??(f=>f.trim());this.asciiAccessors.push(c);let u=t.contains(`TBCOL${n}`)?t.getNumber(`TBCOL${n}`)-1:0;this.colStarts.push(u),this.colWidths.push(a);}}_getRows(t,r){let n=t.byteLength/this.rowByteSize,i=new Uint8Array(t),o=[],s=this.asciiAccessors??[];for(let a=0;a<n;a++){let c=a*this.rowByteSize,u=c+this.rowByteSize,f=i.subarray(c,u),l=He(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 $r={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]}},Y=class extends Ue{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 a=parseInt(s[1],10)||1,c=s[2],u=s[3];this.descriptors.push(u),this.columnTypes.push(o),this.elementByteLengths.push((Nt[u]??1)*a),c?this.setupArrayAccessor(u,o):a===1?this.setupSingleAccessor(u):u==="X"?this.setupBitArrayAccessor(a):u==="A"?this.setupCharArrayAccessor(a):this.setupMultiAccessor(u,a);}}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=Nt[n]??1,a=this.heap.slice(o,o+i*s),c=Ce[n];if(!c)throw new Error(`No typed array constructor for descriptor: ${n}`);let u=new c(a),f=rt[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,a]=this.getFromHeap(i,o,t);return [s,a]};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=$r[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),a=new Uint8Array(s),c=[];for(let u=0;u<a.length;u++)c=c.concat(Hr(a[u]));return [c.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),a="";for(let c=0;c<s.length;c++)a+=String.fromCharCode(s[c]);return [a.trim(),i+t]};this.accessors.push(r);}setupMultiAccessor(t,r){let n=$r[t];if(!n)throw new Error(`Unknown binary table type code: ${t}`);let i=(o,s)=>{let a=[],c=s;for(let u=0;u<r;u++){let[f,l]=n(o,c);a.push(f),c=l;}return [a,c]};this.accessors.push(i);}_getRows(t,r){let n=new DataView(t),i=0,o=[];for(let s=0;s<r;s++){let a={};for(let c=0;c<this.accessors.length;c++){let[u,f]=this.accessors[c](n,i);i=f,this.columns&&(a[this.columns[c]]=u);}o.push(a);}return o}};var nt={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 vt(e,t,r,n,i,o=nt){let s=o[r];if(!s)throw new Error(`Unsupported bytepix value: ${r}`);let[a,c,u,f]=s(e),l=u,m=f,d=1<<a,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++],S=8,w=0;for(;w<i;){for(S-=a;S<0;)y=y<<8|e[m++],S+=8;let I=(y>>S)-1;y&=(1<<S)-1;let A=w+t;if(A>i&&(A=i),I<0)for(;w<A;)n[w]=l,w++;else if(I===c)for(;w<A;){b=d-S;let x=y<<b;for(b-=8;b>=0;)y=e[m++],x|=y<<b,b-=8;S>0?(y=e[m++],x|=y>>-b,y&=(1<<S)-1):y=0,(x&1)===0?x=x>>1:x=~(x>>1),n[w]=x+l,l=n[w],w++;}else for(;w<A;){for(;y===0;)S+=8,y=e[m++];for(h=S-p[y],S-=h+1,y^=1<<S,S-=I;S<0;)y=y<<8|e[m++],S+=8;let x=h<<I|y>>S;y&=(1<<S)-1,(x&1)===0?x=x>>1:x=~(x>>1),n[w]=x+l,l=n[w],w++;}}return n}var Hi=221,$i=153,kt=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 Wr(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 zr(e,t,r,n,i,o){let s=1<<o,a=0,c=0;for(;c<t-1;c+=2){let u=i*c,f=0;for(;f<r-1;f+=2){let l=e[a];(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,a+=1;}if(f<r){let l=e[a];(l&2)!==0&&(n[u+i]=n[u+i]|s),(l&8)!==0&&(n[u]=n[u]|s),a+=1;}}if(c<t){let u=i*c,f=0;for(;f<r-1;f+=2){let l=e[a];(l&4)!==0&&(n[u+1]=n[u+1]|s),(l&8)!==0&&(n[u]=n[u]|s),u+=2,a+=1;}f<r&&((e[a]&8)!==0&&(n[u]=n[u]|s),a+=1);}}function Vi(e,t,r,n,i){let o=t+1>>1,s=r+1>>1,a=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[a],a-=1,f-=2;}let c=0;for(;c<t-1;c+=2){let u=i*c,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(c<t){let u=i*c,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 Wi(e,t,r,n,i){Vi(t,r,n,i,n);for(let o=r*n-1;o>=0;o--)i[o]!==0&&(i[o]=Wr(e));}function zi(e,t,r,n,i,o,s){let a=(n+1>>1)*(i+1>>1);e.inputNNybble(a,o),zr(o,n,i,t,r,s);}function it(e,t,r,n,i,o){if(o<=0||n<=0||i<=0)return;let s=n>i?n:i,a=Math.floor(Math.log(s)/Math.log(2)+.5);s>1<<a&&(a+=1);let c=n+1>>1,u=i+1>>1,f=new Uint8Array(c*u);for(let l=o-1;l>=0;l--){let m=e.inputNybble();if(m===0){zi(e,t,r,n,i,f,l);continue}if(m!==15)throw new D("Invalid HCOMPRESS bitplane format code");f[0]=Wr(e);let d=1,p=1,h=n,b=i,g=1<<a;for(let y=1;y<a;y++)g>>=1,d<<=1,p<<=1,h<=g?d-=1:h-=g,b<=g?p-=1:b-=g,Wi(e,f,d,p,f);zr(f,n,i,t,r,l);}}function Vr(e,t,r,n,i){let o=r+1>>1,s=0,a=t+n*o;for(let u=o;u<r;u++)i[s++]=e[a],a+=n;let c=t+n*(o-1);a=t+(n*(o-1)<<1);for(let u=o-1;u>=0;u--)e[a]=e[c],c-=n,a-=n+n;s=0,a=t+n;for(let u=1;u<r;u+=2)e[a]=i[s++],a+=n+n;}function Gi(e,t,r,n,i){let o=i>>1;if(o<=0)return;let s=n<<1;for(let a=2;a<t-2;a+=2){let c=n*a,u=c+n;for(let f=0;f<r;f+=2){let l=e[c-s],m=e[c],d=e[c+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;}c+=2,u+=2;}}for(let a=0;a<t;a+=2){let c=n*a+2;for(let u=2;u<r-2;u+=2){let f=e[c-2],l=e[c],m=e[c+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[c+1]<<3);b=b>=0?b>>3:b+7>>3,b=Math.max(Math.min(b,o),-o),e[c+1]=e[c+1]+b|0;}c+=2;}}for(let a=2;a<t-2;a+=2){let c=n*a+2,u=c+n;for(let f=2;f<r-2;f+=2){let l=e[c-s-2],m=e[c+s-2],d=e[c-s+2],p=e[c+s+2],h=e[c],b=p+l-d-m,g=e[u]<<1,y=e[c+1]<<1,S=Math.min(Math.max(p-h,0)-g-y,Math.max(h-m,0)+g-y),w=Math.min(Math.max(h-d,0)-g+y,Math.max(l-h,0)+g+y),I=Math.min(S,w)<<4;S=Math.max(Math.min(p-h,0)-g-y,Math.min(h-m,0)+g-y),w=Math.max(Math.min(h-d,0)-g+y,Math.min(l-h,0)+g+y);let A=Math.max(S,w)<<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;}c+=2,u+=2;}}}function ji(e,t){if(!(t<=1))for(let r=0;r<e.length;r++)e[r]=Math.imul(e[r],t);}function Ki(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 a=new Int32Array(o+1>>1),c=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,S=b-1,w=g-1;e[0]=e[0]+(e[0]>=0?g:w)&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,c=2);for(let P=0;P<I;P++)Vr(e,r*P,A,1,a);for(let P=0;P<A;P++)Vr(e,P,I,r,a);n&&Gi(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,K=0;for(;K<A-C;K+=2){let T=e[P],N=e[M],U=e[P+1],q=e[M+1];N=N+(N>=0?b:S)&d,U=U+(U>=0?b:S)&d,q=q+(q>=0?h:y)&m;let le=q&u;N=N>=0?N-le:N+le,U=U>=0?U-le:U+le;let de=(q^N^U)&f;T=T>=0?T+le-de:T+(le===0?de:le-de),e[M+1]=T+N+U+q>>c,e[M]=T+N-U-q>>c,e[P+1]=T-N+U-q>>c,e[P]=T-N-U+q>>c,P+=2,M+=2;}if(C){let T=e[P],N=e[M];N=N+(N>=0?b:S)&d;let U=N&f;T=T>=0?T-U:T+U,e[M]=T+N>>c,e[P]=T-N>>c;}}if(H){let P=r*v,M=0;for(;M<A-C;M+=2){let K=e[P],T=e[P+1];T=T+(T>=0?b:S)&d;let N=T&f;K=K>=0?K-N:K+N,e[P+1]=K+T>>c,e[P]=K-T>>c,P+=2;}C&&(e[P]=e[P]>>c);}l=f,f=u,u>>=1,d=m,m>>=1,b=h,h>>=1,S=y,y=h-1;}}function Yi(e,t){let r=e.readByte(),n=e.readByte();if(r!==Hi||n!==$i)throw new D("Invalid HCOMPRESS stream magic");let i=e.readInt32BE(),o=e.readInt32BE(),s=e.readInt32BE(),a=Number(e.readInt64BE()),c=Uint8Array.from([e.readByte(),e.readByte(),e.readByte()]),u=new Int32Array(i*o),f=i+1>>1,l=o+1>>1;if(e.startBitInput(),it(e,u.subarray(0),o,f,l,c[0]),it(e,u.subarray(l),o,f,Math.floor(o/2),c[1]),it(e,u.subarray(o*f),o,Math.floor(i/2),l,c[1]),it(e,u.subarray(o*f+l),o,Math.floor(i/2),Math.floor(o/2),c[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]=a|0,ji(u,s),Ki(u,i,o,t,s),{pixels:u,nx:i,ny:o}}function Gr(e,t=false){let r=new kt(e);return Yi(r,t)}var Dt;function Zi(e){Dt=e;}function qi(){return Dt}function Ji(){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 Lt=Ji();function Qi(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,a=s+t-1,c=false,u=1,f=1,l=1;for(let m=i;m<=n;m++){if(c){c=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,a),S=y-g+1;if(S>0){let w=u+S-1;if(p===4)for(let I=u;I<=w;I++)o[I-1]=l;else {for(let I=u;I<=w;I++)o[I-1]=0;p===5&&y===b&&(o[w-1]=l);}u=w+1;}f=b+1;}else p===1?(l=(r(m+1)<<12)+h,c=true):p===2?l+=h:p===3?l-=h:(p===6||p===7)&&(l+=p===6?h:-h,f>=s&&f<=a&&(o[u-1]=l,u++),f++);if(f>a)break}for(let m=u;m<=t;m++)o[m-1]=0;return o}function eo(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 to(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Kr(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 Y{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=to(t);if(this.zcmptype==="RICE_1"){let s=this.algorithmParameters.BYTEPIX??4,a=this.algorithmParameters.BLOCKSIZE??32,c=Ce[s];if(!c)throw new Error(`No typed array for bytepix: ${s}`);let u=new c(n);return vt(i,a,s,u,n,nt),u}if(this.zcmptype==="GZIP_1"){let s=gunzipSync(i);return Kr(s,this.zbitpix,n)}if(this.zcmptype==="PLIO_1"){let s=eo(t);return Qi(s,n)}if(this.zcmptype==="HCOMPRESS_1"){let s=(this.algorithmParameters.SMOOTH??0)!==0,a=Gr(i,s).pixels;if(a.length!==n)throw new D(`HCOMPRESS_1 tile length mismatch (decoded=${a.length}, expected=${n})`);return a}let o=this.decoderProvider??Dt;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,a=Math.floor(o/i),c=s*r,u=a*n,f=Math.max(0,Math.min(r,this.width-c)),l=Math.max(0,Math.min(n,this.height-u));return {x:c,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[a,c]=this.getFromHeap(o,s,i),u=this.currentTilePixelCount??this.getDefaultTilePixelCount();return [this.decodeCompressedTile(a,i,u),c]}:n==="GZIP_COMPRESSED_DATA"&&(this.accessors[r]=(o,s)=>{let[a,c]=this.getFromHeap(o,s,i),u=a instanceof Uint8Array?a:new Uint8Array(a.buffer,a.byteOffset,a.byteLength),f=this.currentTilePixelCount??this.getDefaultTilePixelCount(),l=gunzipSync(u);return [Kr(l,this.zbitpix,f),c]});}}_getRows(t,r){let n=new DataView(t),i=0,o=new Float32Array(this.width*this.height),s=0,a=r;for(;a--;){s++;let c=s,u=this.getTilePlacement(c);this.currentTilePixelCount=u.pixelCount;let f={};for(let y=0;y<this.accessors.length;y++){let[S,w]=this.accessors[y](n,i);i=w,this.columns&&(f[this.columns[y]]=S);}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 S=(c+this.zdither-1-1)%1e4;b=S<0?S+1e4:S,h=Math.floor(Lt[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 S=y%u.width,w=Math.floor(y/u.width);if(w>=u.height)break;let I=(u.y+w)*this.width+u.x+S,A=l[y];if(A===-2147483647)o[I]=NaN;else if(A===-2147483646)o[I]=0;else if(p){let x=Lt[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(Lt[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]=$e(t);return [Number(r),Number(n)]}getPixel(t,r,n){return Number(Ve(t,r,n,this.width))}};function Yr(e,t){let r=e.getDataType();if(r)switch(r){case "Image":return new J(e,t);case "BinaryTable":return new Y(e,t);case "Table":return new We(e,t);case "CompressedImage":return new ze(e,t);default:return}}function Ot(e,t){let r=[],n=e.byteLength,i=0;for(;i<n;){let o=0,s=new Uint8Array(0),a=false;for(;!a&&i+o*2880+2880<=n;){let c=i+o*2880,u=new Uint8Array(e,c,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 S=y*80,w=u[S];if(w!==32){if(w===69&&u[S+1]===78&&u[S+2]===68&&u[S+3]===32){a=true;break}break}}if(o++,!a)continue;let m=He(s),d=new Pe(m,t?.maxHeaderLines,t?.onWarning),p=i+o*2880,h=d.getDataLength(),b=e.slice(p,p+h),g;if(d.hasDataUnit()&&(g=Yr(d,b)),r.push(new Re(d,g)),i=p+h+Bt(h),i>=n)break}if(!a)break}return r}async function Mt(e,t){let r=[],n=e.size,i=0;for(;i<n;){let o=0,s=[],a=false;for(;!a&&i+o*2880+2880<=n;){let c=i+o*2880,f=await e.slice(c,c+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){a=true;break}break}}if(o++,!a)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=He(p),g=new Pe(b,t?.maxHeaderLines,t?.onWarning),y=i+o*2880,S=g.getDataLength(),w;if(g.hasDataUnit()){let I=e.slice(y,y+S);w=Yr(g,I);}if(r.push(new Re(g,w)),i=y+S+Bt(S),i>=n)break}if(!a)break}return r}var z=class e{hdus;constructor(t){this.hdus=t;}static fromArrayBuffer(t,r){let n=Ot(t,r);return new e(n)}static async fromBlob(t,r){let n=await Mt(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";}},B=class extends se{constructor(t){super(t),this.name="XISFParseError";}},F=class extends se{constructor(t){super(t),this.name="XISFValidationError";}},Q=class extends se{constructor(t){super(t),this.name="XISFResourceError";}},G=class extends se{constructor(t){super(t),this.name="XISFCompressionError";}},pe=class extends se{constructor(t){super(t),this.name="XISFChecksumError";}},Be=class extends se{constructor(t){super(t),this.name="XISFSignatureError";}},j=class extends se{constructor(t){super(t),this.name="XISFConversionError";}};var Xt="XISF0100",Ge=8,Zr=8,qr=4,je=Ge+4+qr;function Jr(e){return new TextDecoder("ascii").decode(e)}function Qr(e){return e.byteLength<je?false:Jr(new Uint8Array(e,0,Ge))===Xt}function en(e){if(e.byteLength<je)throw new B("Invalid XISF file: too short");let t=Jr(new Uint8Array(e,0,Ge));if(t!==Xt)throw new B(`Invalid XISF signature: ${t}`);let n=new DataView(e).getUint32(Zr,true),i=je,o=i+n;if(o>e.byteLength)throw new B("Invalid XISF header length");let s=new Uint8Array(e,i,n),a=new TextDecoder("utf-8").decode(s),c=new Uint8Array(e,Ge+4,qr),u=new Uint8Array(e,o);return {signature:t,headerLength:n,reserved:c,headerXml:a,payload:u}}function tn(e,t,r){if(t<0||r<0||t+r>e.byteLength)throw new B(`Attachment block out of bounds: position=${t}, size=${r}`);return new Uint8Array(e,t,r)}function rn(e,t){let r=new TextEncoder().encode(e),i=je+r.byteLength;for(let a of t){let c=a.position+a.data.byteLength;c>i&&(i=c);}let o=new Uint8Array(i);o.set(new TextEncoder().encode(Xt),0);let s=new DataView(o.buffer);s.setUint32(Zr,r.byteLength,true),s.setUint32(Ge+4,0,true),o.set(r,je);for(let a of t)o.set(a.data,a.position);return o}var no="http://www.pixinsight.com/xisf";function _t(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 io(e){return e.nodeType===1}function on(e){let t=new DOMParser().parseFromString(e,"application/xml"),r=t.getElementsByTagName("parsererror");if(r.length>0)throw new B((r[0]?.textContent??"Invalid XML").trim());let n=t.documentElement;if(!n)throw new B("Empty XML document");if(_t(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 oo(e){let t=[];for(let r=0;r<e.childNodes.length;r++){let n=e.childNodes.item(r);n&&io(n)&&t.push(n);}return t}function ee(e,t){return oo(e).filter(r=>_t(r)===t)}function Ke(e,t){let r=ee(e,t);return r.length>0?r[0]:null}function Ie(e){return _t(e)}function ot(e){return new XMLSerializer().serializeToString(e)}function Ht(){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",no),t.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance"),t.setAttribute("xsi:schemaLocation","http://www.pixinsight.com/xisf http://pixinsight.com/xisf/xisf-1.0.xsd"),e}var so=/^(url|path)\((.*)\)(?::(.*))?$/;function ao(e){if(!e)return;let t=e.trim();if(t.length!==0)return t.startsWith("0x")||t.startsWith("0X"),BigInt(t)}function $t(e){let t=e.trim();if(t.startsWith("inline:")){let n=t.slice(7);if(n!=="base64"&&n!=="hex")throw new B(`Unsupported inline encoding: ${n}`);return {type:"inline",encoding:n}}if(t==="embedded")return {type:"embedded"};if(t.startsWith("attachment:")||t.startsWith("attached:")){let i=(t.startsWith("attached:")?`attachment:${t.slice(9)}`:t).split(":");if(i.length!==3)throw new B(`Invalid attachment location: ${e}`);let o=Number(i[1]),s=Number(i[2]);if(!Number.isInteger(o)||!Number.isInteger(s)||o<0||s<0)throw new B(`Invalid attachment numbers: ${e}`);return {type:"attachment",position:o,size:s}}let r=so.exec(t);if(r){let n=r[1],i=r[2],o=ao(r[3]);return n==="url"?{type:"url",url:i,indexId:o}:{type:"path",path:i,indexId:o}}throw new B(`Unsupported location syntax: ${e}`)}function Vt(e){return e.trim()?e.split(":").map(t=>{let r=t.split(",");if(r.length!==2)throw new B(`Invalid subblocks entry: ${t}`);let n=Number(r[0]),i=Number(r[1]);if(!Number.isInteger(n)||!Number.isInteger(i)||n<0||i<0)throw new B(`Invalid subblocks values: ${t}`);return {compressedSize:n,uncompressedSize:i}}):[]}function sn(e){let t=e.indexOf(":");if(t<=0)throw new B(`Invalid checksum format: ${e}`);return {algorithm:e.slice(0,t).toLowerCase(),digest:e.slice(t+1).toLowerCase()}}function Wt(e){let t=e.split(":");if(t.length<2||t.length>3)throw new B(`Invalid compression format: ${e}`);let r=t[0].toLowerCase(),n=Number(t[1]);if(!Number.isInteger(n)||n<0)throw new B(`Invalid uncompressed size: ${e}`);if(t.length===3){let i=Number(t[2]);if(!Number.isInteger(i)||i<=0)throw new B(`Invalid shuffle item size: ${e}`);return {codec:r,uncompressedSize:n,itemSize:i}}return {codec:r,uncompressedSize:n}}function an(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 co={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"},un={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"},uo={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 zt(e){return co[e]}function lo(e){let t=e.toLowerCase();return t==="true"||t==="1"}function fo(e){let t=e.trim().replace(",",":"),r=t.indexOf(":");return r>0?{real:Number.parseFloat(t.slice(0,r)),imag:Number.parseFloat(t.slice(r+1))}:{real:Number.parseFloat(t),imag:0}}function cn(e,t){switch(zt(e)??e){case "Boolean":return lo(t);case "Int8":case "Int16":case "Int32":return Number.parseInt(t,10);case "UInt8":case "UInt16":case "UInt32":return Number.parseInt(t,10);case "Int64":case "UInt64":return BigInt(t);case "Float32":case "Float64":return Number.parseFloat(t);case "Complex32":case "Complex64":return fo(t);default:return t}}function mo(e){return e.byteOrder==="big"?"big":"little"}function ln(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 po(e,t,r){let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=r==="little";if(t.byteLength<ln(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 Gt(e,t,r,n){let i=r==="little",o=new DataView(t.buffer,t.byteOffset,t.byteLength),s=ln(e),a=n??Math.floor(t.byteLength/s);switch(e){case "Int8":{let c=new Int8Array(a);for(let u=0;u<a;u++)c[u]=o.getInt8(u);return c}case "UInt8":case "Boolean":{let c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=o.getUint8(u);return c}case "Int16":{let c=new Int16Array(a);for(let u=0;u<a;u++)c[u]=o.getInt16(u*2,i);return c}case "UInt16":{let c=new Uint16Array(a);for(let u=0;u<a;u++)c[u]=o.getUint16(u*2,i);return c}case "Int32":{let c=new Int32Array(a);for(let u=0;u<a;u++)c[u]=o.getInt32(u*4,i);return c}case "UInt32":{let c=new Uint32Array(a);for(let u=0;u<a;u++)c[u]=o.getUint32(u*4,i);return c}case "Int64":{let c=new BigInt64Array(a);for(let u=0;u<a;u++)c[u]=o.getBigInt64(u*8,i);return c}case "UInt64":{let c=new BigUint64Array(a);for(let u=0;u<a;u++)c[u]=o.getBigUint64(u*8,i);return c}case "Float32":{let c=new Float32Array(a);for(let u=0;u<a;u++)c[u]=o.getFloat32(u*4,i);return c}case "Float64":{let c=new Float64Array(a);for(let u=0;u<a;u++)c[u]=o.getFloat64(u*8,i);return c}case "Complex32":{let c=new Float32Array(a*2);for(let u=0;u<a;u++)c[u*2]=o.getFloat32(u*8,i),c[u*2+1]=o.getFloat32(u*8+4,i);return c}case "Complex64":{let c=new Float64Array(a*2);for(let u=0;u<a;u++)c[u*2]=o.getFloat64(u*16,i),c[u*2+1]=o.getFloat64(u*16+8,i);return c}case "String":case "TimePoint":return new Uint8Array(t)}}function st(e){let t=e.getAttribute("location");if(!t)return;let r=$t(t),n=e.getAttribute("checksum"),i=e.getAttribute("compression"),o=e.getAttribute("byteOrder"),s=e.getAttribute("subblocks"),a={location:r,byteOrder:o==="big"?"big":o==="little"?"little":void 0};if(n){let c=sn(n);a.checksum={algorithm:c.algorithm,digest:c.digest};}if(i){let c=Wt(i);a.compression={codec:c.codec,uncompressedSize:c.uncompressedSize,itemSize:c.itemSize,subblocks:s?Vt(s):void 0};}if(r.type==="inline")a.inlineData=(e.textContent??"").trim();else if(r.type==="embedded"){let c=Ke(e,"Data");if(c){let u=c.getAttribute("encoding");if((u==="base64"||u==="hex")&&(r.encoding=u),a.embeddedData=(c.textContent??"").trim(),!a.compression){let f=c.getAttribute("compression");if(f){let l=Wt(f);a.compression={codec:l.codec,uncompressedSize:l.uncompressedSize,itemSize:l.itemSize,subblocks:c.getAttribute("subblocks")?Vt(c.getAttribute("subblocks")):void 0};}}}}return a}function ho(e,t,r){let n=un[e];return n?Gt(n,t,"little",r):new Uint8Array(t)}async function Ae(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,a=e.getAttribute("comment")??void 0;if(n&&!o)throw new F(`Property '${i||"<unnamed>"}' is missing type`);let c={id:i,type:o,format:s,comment:a},u=e.hasAttribute("value")?e.getAttribute("value"):null;if(u!==null)return c.value=cn(o,u),c;let f=e.getAttribute("length"),l=e.getAttribute("rows"),m=e.getAttribute("columns");if(f&&(c.length=Number(f)),l&&(c.rows=Number(l)),m&&(c.columns=Number(m)),n&&c.length!==void 0&&(!Number.isInteger(c.length)||c.length<0))throw new F(`Invalid property length '${f}' for '${i||"<unnamed>"}'`);if(n&&c.rows!==void 0&&(!Number.isInteger(c.rows)||c.rows<0))throw new F(`Invalid property rows '${l}' for '${i||"<unnamed>"}'`);if(n&&c.columns!==void 0&&(!Number.isInteger(c.columns)||c.columns<0))throw new F(`Invalid property columns '${m}' for '${i||"<unnamed>"}'`);let d=st(e);if(!d)return o==="String"||o==="TimePoint"?c.value=e.textContent??"":zt(o)&&(e.textContent??"").trim().length>0&&(c.value=cn(o,(e.textContent??"").trim())),c;c.dataBlock=d;let p=await t(e,d),h=mo(d);if(o==="String")return c.value=new TextDecoder("utf-8").decode(p),c;if(o==="TimePoint")return c.value=new TextDecoder("utf-8").decode(p),c;let b=zt(o);if(b&&b!=="String"&&b!=="TimePoint")return c.value=po(b,p,h),c;if(o.endsWith("Vector")||o==="ByteArray"||o==="IVector"||o==="UIVector"||o==="Vector"){let g=un[o];return g?(c.value=Gt(g,p,h,c.length),c):(c.value=ho(o,p,c.length),c)}if(o.endsWith("Matrix")){let g=c.rows??0,y=c.columns??0,S=uo[o];if(!S)return c.value=p,c;let w=g>0&&y>0?g*y:void 0,I=Gt(S,p,h,w),A=Array.from(I),x=[];for(let E=0;E<g;E++)x.push(A.slice(E*y,(E+1)*y));return c.value={rows:g,columns:y,values:x},c}return c.value=p,c}function go(e){return {id:e.getAttribute("id")??"",type:e.getAttribute("type")??"",format:e.getAttribute("format")??void 0,header:e.getAttribute("header")??void 0}}function bo(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 yo(e,t,r,n){let i=ee(e,"Cell");return {cells:await Promise.all(i.map((s,a)=>{let c=t[a],u=bo(s,c);return Ae(u,r,{...n,defaultType:c?.type,defaultId:c?.id,defaultFormat:c?.format})}))}}async function at(e,t,r,n){let i=n?.strictValidation??true,o=e.getAttribute("id")??"",s=e.getAttribute("caption")??void 0,a=e.getAttribute("rows")?Number(e.getAttribute("rows")):void 0,c=e.getAttribute("columns")?Number(e.getAttribute("columns")):void 0,u=e.getAttribute("comment")??void 0;if(i&&a!==void 0&&(!Number.isInteger(a)||a<0))throw new F(`Table '${o||"<unnamed>"}' has invalid rows value`);if(i&&c!==void 0&&(!Number.isInteger(c)||c<0))throw new F(`Table '${o||"<unnamed>"}' has invalid columns value`);let f=Ke(e,"Structure");if(!f){let p=Ke(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(go):[],m=ee(e,"Row"),d=await Promise.all(m.map(p=>yo(p,l,r,{strictValidation:i})));if(i&&a!==void 0&&a!==d.length)throw new F(`Table '${o||"<unnamed>"}' row count mismatch`);if(i&&c!==void 0){for(let p of d)if(p.cells.length!==c)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:a,columns:c,comment:u,structure:l,dataRows:d}}var wo=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),So=new Set(["Gray","RGB","CIELab"]),Io=new Set(["Planar","Normal"]),Ao=new Set(["0","flip","90","90;flip","-90","-90;flip","180","180;flip"]),xo=/^[0RGBWCMY]+$/;function ae(e){return e.split(":").map(t=>Number(t.trim()))}function Fo(e){let t=ae(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 Eo(e){if(!e)return;let[t,r]=ae(e);if(!(t===void 0||r===void 0))return [t,r]}function To(e){let t=e.getAttribute("gamma")??"sRGB",r=ae(e.getAttribute("x")??"0:0:0"),n=ae(e.getAttribute("y")??"0:0:0"),i=ae(e.getAttribute("Y")??"0:0:0");return {gamma:t,x:r,y:n,Y:i,name:e.getAttribute("name")??void 0}}function Po(e){return {m:ae(e.getAttribute("m")??"0.5:0.5:0.5:0.5"),s:ae(e.getAttribute("s")??"0:0:0:0"),h:ae(e.getAttribute("h")??"1:1:1:1"),l:ae(e.getAttribute("l")??"0:0:0:0"),r:ae(e.getAttribute("r")??"1:1:1:1"),name:e.getAttribute("name")??void 0}}function Ro(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&&!xo.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 Co(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 Uo(e){return {name:e.getAttribute("name")??"",value:e.getAttribute("value")??"",comment:e.getAttribute("comment")??""}}async function jt(e,t,r,n,i=true,o=false){let s=e.getAttribute("geometry");if(!s)throw new F("Image element is missing geometry");let a=e.getAttribute("sampleFormat");if(!a)throw new F("Image element is missing sampleFormat");if(!wo.has(a))throw new F(`Unsupported image sampleFormat: ${a}`);let{dimensions:c,channels:u}=Fo(s),f=st(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(!Io.has(l))throw new F(`Unsupported pixelStorage: ${l}`);let m=e.getAttribute("colorSpace")||"Gray";if(!So.has(m))throw new F(`Unsupported colorSpace: ${m}`);if(i&&(a==="Float32"||a==="Float64")&&!e.getAttribute("bounds"))throw new F("bounds is required for Float32/Float64 images");let d=e.getAttribute("orientation")??void 0;if(d&&!Ao.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=Eo(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(a))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&&c.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:c,channelCount:u,sampleFormat:a,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"),S=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},w=[];for(let I of S(e)){if(Ie(I)==="Reference"){let A=I.getAttribute("ref");if(A){let x=t(A);if(x){if(i&&Ie(x)==="Reference")throw new F(`Chained references are not allowed (${A})`);w.push(x);}}continue}w.push(I);}for(let I of y){let A=I.getAttribute("ref");if(!A)continue;let x=t(A);if(i&&x&&Ie(x)==="Reference")throw new F(`Chained references are not allowed (${A})`);x&&!w.includes(x)&&w.push(x);}for(let I of w)switch(Ie(I)){case "Property":g.properties.push(await Ae(I,r,{strictValidation:i}));break;case "Table":g.tables.push(await at(I,t,r,{strictValidation:i}));break;case "FITSKeyword":g.fitsKeywords.push(Uo(I));break;case "ICCProfile":{if(i&&I.hasAttribute("byteOrder"))throw new F("ICCProfile must not define byteOrder");let x=st(I);x&&(g.iccProfile=await r(I,x));break}case "RGBWorkingSpace":g.rgbWorkingSpace=To(I);break;case "DisplayFunction":g.displayFunction=Po(I);break;case "ColorFilterArray":if(o)throw new F("Thumbnail must not contain ColorFilterArray");g.colorFilterArray=Ro(I,i);break;case "Resolution":g.resolution=Co(I,i);break;case "Thumbnail":if(o)throw new F("Nested Thumbnail elements are not allowed");g.thumbnail=await jt(I,t,r,n,i,true);break;}return g}var Ne="+sh",Do=new Set([0,1,2,3,4,5,6,7,8,9]),Kt=new Set(["lz4","lz4hc"]),Yt=new Set(["zstd"]);function Oo(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 Mo(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):Oo(e)}function Xo(e,t){if(!t||t<=0)throw new G("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 G(`Decoded LZ4 block length mismatch: expected ${r.byteLength}, got ${i}`);return r}var ct={supports(e){let t=e.toLowerCase(),r=t.endsWith(Ne)?t.slice(0,-Ne.length):t;return r==="zlib"||Kt.has(r)||Yt.has(r)},compress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new G(`Unsupported codec in default provider: ${e}`);if(Kt.has(n))return Mo(t);if(Yt.has(n))throw new G("Default provider supports zstd decompression only; provide a custom codecProvider for zstd encoding");let i=r!==void 0&&Do.has(r)?r:void 0;return zlibSync(t,{level:i})},decompress(e,t,r){let n=e.toLowerCase();if(!this.supports(n))throw new G(`Unsupported codec in default provider: ${e}`);if(Kt.has(n))return Xo(t,r);if(Yt.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 G(`Decoded zstd block length mismatch: expected ${i.byteLength}, got ${o.byteLength}`);return o}return unzlibSync(t)}};function _o(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 a=0;a<r;a++)i[o++]=e[a*t+s];return n>0&&i.set(e.slice(r*t),o),i}function Ho(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 a=0;a<r;a++)i[a*t+s]=e[o++];return n>0&&i.set(e.slice(o),r*t),i}function $o(e,t){let r=[],n=0;for(let i of t){let o=n+i.compressedSize;if(o>e.byteLength)throw new G("Compressed subblocks exceed block length");r.push(e.slice(n,o)),n=o;}if(n!==e.byteLength)throw new G("Compressed subblocks length mismatch");return r}function mn(e,t,r){let n=t.codec.toLowerCase(),i=n.endsWith(Ne),o=i?n.slice(0,-Ne.length):n,s=f=>{let l=r.decompress(o,f,t.uncompressedSize);if(!i)return l;if(!t.itemSize||t.itemSize<=0)throw new G(`Shuffle codec ${n} requires itemSize`);return Ho(l,t.itemSize)};if(!t.subblocks||t.subblocks.length===0)return s(e);let a=$o(e,t.subblocks),c=new Uint8Array(t.uncompressedSize),u=0;for(let f=0;f<a.length;f++){let l=s(a[f]),m=t.subblocks[f].uncompressedSize;if(l.byteLength!==m)throw new G("Decoded subblock size mismatch");c.set(l,u),u+=l.byteLength;}if(u!==t.uncompressedSize)throw new G("Decoded uncompressed size mismatch");return c}function dn(e,t,r,n,i){let o=t.toLowerCase(),s=o.endsWith(Ne),a=s?o.slice(0,-Ne.length):o,c=s?_o(e,i??1):e;return {data:r.compress(a,c,n),spec:{codec:o,uncompressedSize:e.byteLength,itemSize:s?i??1:void 0}}}function Vo(e){return new Uint8Array(e)}async function Wo(e){try{let r=await(await import('fs/promises')).readFile(e);return new Uint8Array(r)}catch(t){throw new Q(`Failed to read path "${e}": ${t.message}`)}}var pn={async resolveURL(e){let t=await fetch(e);if(!t.ok)throw new Q(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);return Vo(await t.arrayBuffer())},async resolvePath(e){if(typeof window<"u")throw new Q(`Path-based distributed XISF access requires a custom resourceResolver in browser environments: ${e}`);return Wo(e)}};var hn="XISB0100";function zo(e){return new TextDecoder("ascii").decode(e)}function Zt(e,t){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new F(`${t} exceeds Number.MAX_SAFE_INTEGER`);return Number(e)}function gn(e){let t=new Uint8Array(e);if(t.byteLength<16)throw new B("Invalid XISB file: too short");let r=zo(t.slice(0,8));if(r!==hn)throw new B(`Invalid XISB signature: ${r}`);let n=new DataView(e),i=[],o=16,s=new Set;for(;o!==0;){if(s.has(o))throw new B("Invalid XISB index: cyclic block index list");if(s.add(o),o+16>t.byteLength)throw new B("Invalid XISB index node offset");let c=n.getUint32(o,true),u=n.getBigUint64(o+8,true),f=o+16;for(let l=0;l<c;l++){if(f+40>t.byteLength)throw new B("Invalid XISB index element offset");let m=n.getBigUint64(f,true),d=n.getBigUint64(f+8,true),p=n.getBigUint64(f+16,true),h=n.getBigUint64(f+24,true);i.push({uniqueId:m,blockPosition:d,blockLength:p,uncompressedBlockLength:h}),f+=40;}o=Zt(u,"nextNode");}let a=new Map;for(let c of i)a.set(c.uniqueId,c);return {elements:i,byId:a}}function bn(e,t){if(t.blockPosition===BigInt(0)||t.blockLength===BigInt(0))throw new F("Cannot read free XISB index element");let r=Zt(t.blockPosition,"blockPosition"),n=Zt(t.blockLength,"blockLength"),i=new Uint8Array(e);if(r+n>i.byteLength)throw new B("XISB block out of bounds");return i.slice(r,r+n)}function yn(e){let t=e.map((m,d)=>BigInt(d+1)),r=16,n=16,i=40,o=n+e.length*i,s=r+o,a=e.map((m,d)=>{let p=BigInt(s);return s+=m.byteLength,{uniqueId:t[d],blockPosition:p,blockLength:BigInt(m.byteLength),uncompressedBlockLength:BigInt(0)}}),c=s,u=new Uint8Array(c);u.set(new TextEncoder().encode(hn),0);let f=new DataView(u.buffer),l=r;f.setUint32(l,a.length,true),f.setUint32(l+4,0,true),f.setBigUint64(l+8,BigInt(0),true),l+=n;for(let m of a)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(a[m].blockPosition);u.set(d,p);}return {bytes:u,ids:t}}var Go=wn.sha3_256,jo=wn.sha3_512;function Ko(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 qt(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 Ko(o)}let n=(await import('crypto')).createHash(e.toLowerCase().replace("-",""));return n.update(t),n.digest("hex")}async function Jt(e,t){switch(t.toLowerCase()){case "sha1":case "sha-1":return qt("SHA-1",e);case "sha256":case "sha-256":return qt("SHA-256",e);case "sha512":case "sha-512":return qt("SHA-512",e);case "sha3-256":return Go(e);case "sha3-512":return jo(e);default:throw new pe(`Unsupported checksum algorithm: ${t}`)}}async function Sn(e,t){return (await Jt(e,t.algorithm)).toLowerCase()===t.digest.toLowerCase()}var O="http://www.w3.org/2000/09/xmldsig#",nr="http://www.w3.org/TR/2001/REC-xml-c14n-20010315",Yo="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments",Zo="http://www.w3.org/2006/12/xml-c14n11",qo="http://www.w3.org/2006/12/xml-c14n11#WithComments",Jo="http://www.w3.org/2001/10/xml-exc-c14n#",Qo="http://www.w3.org/2001/10/xml-exc-c14n#WithComments",es="http://www.w3.org/2000/09/xmldsig#enveloped-signature",ts="http://www.w3.org/2000/09/xmldsig#base64";function ve(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 Ye(e){return !!e&&e.nodeType===1}function rs(e){return !!e&&e.nodeType===8}function ns(e){return !!e&&(e.nodeType===3||e.nodeType===4)}function ir(e,t,r){let n=[];for(let i=0;i<e.childNodes.length;i++){let o=e.childNodes.item(i);Ye(o)&&ve(o)===t&&((o.namespaceURI??"")!==r||n.push(o));}return n}function $(e,t,r){let n=ir(e,t,r);return n.length>0?n[0]:null}function Fn(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(Ye(n)&&ve(n)==="Signature"&&(n.namespaceURI??"")===O)return n}return null}function En(e){return Fn(e)!==null}function is(e){return e.replace(/\s+/gu,"")}function ut(e){let t;if(typeof btoa=="function"){let r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);t=btoa(r);}else t=Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64");return t.replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/gu,"")}async function he(e){let t=is(e);if(typeof atob=="function"){let n=atob(t),i=new Uint8Array(n.length);for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);return i}let r=await import('buffer');return new Uint8Array(r.Buffer.from(t,"base64"))}function er(e){return new TextEncoder().encode(e)}function tr(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 os(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll("\r","
")}function Qt(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll('"',""").replaceAll(" ","	").replaceAll(`
|
|
3
|
-
`,"
").replaceAll("\r","
")}function In(e){let t=e.prefix,r=ve(e);return t?`${t}:${r}`:r}function ss(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 as(e){return new Map(e.entries())}function cs(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(Ye(o)&&ve(o)==="Signature"&&(o.namespaceURI??"")===O){n.removeChild(o);continue}r(o);}}};return r(t),t}function or(e){switch(e){case nr:case Zo:return {withComments:false,exclusive:false};case Yo:case qo:return {withComments:true,exclusive:false};case Jo:return {withComments:false,exclusive:true};case Qo:return {withComments:true,exclusive:true};default:return null}}function us(e){return e.prefix??""}function An(e){let t=e.prefix;return !t||t==="xmlns"?"":t}function ls(e,t,r){let n=us(e),i=e.namespaceURI??"",o=ss(e),s=as(t);for(let[p,h]of o.entries())s.set(p,h);let a=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=An(b);g&&p.add(g);}for(let h of p){let b=t.get(h)??"",g=h===n?i:s.get(h)??"";g!==b&&a.set(h,g);}}else {for(let[h,b]of o.entries()){let g=t.get(h)??"";b!==g&&a.set(h,b);}let p=t.get("")??"";n===""&&i!==p&&a.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=An(b);if(!g)continue;let y=t.get(g)??"",S=s.get(g)??"";S!==y&&a.set(g,S);}}let c=[...a.entries()].sort(([p],[h])=>p.localeCompare(h)).map(([p,h])=>p===""?` xmlns="${Qt(h)}"`:` xmlns:${p}="${Qt(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?ve(p).localeCompare(ve(h)):b.localeCompare(g)});let f=u.map(p=>` ${p.name}="${Qt(p.value)}"`).join(""),l=`<${In(e)}${c.join("")}${f}>`,m="";for(let p=0;p<e.childNodes.length;p++){let h=e.childNodes.item(p);h&&(m+=sr(h,s,r));}let d=`</${In(e)}>`;return `${l}${m}${d}`}function sr(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+=sr(s,t,r));}return i}if(Ye(e))return ls(e,t,r);if(ns(e))return os(e.data);if(rs(e))return r.withComments?`<!--${e.data}-->`:"";if(e.nodeType===7){let n=e;return `<?${n.target}${n.data?` ${n.data}`:""}?>`}return ""}function rr(e,t){let r=or(t);if(!r)throw new Error(`Unsupported canonicalization algorithm: ${t}`);return sr(e,new Map,r)}function fs(e){let t=$(e,"Transforms",O);if(!t)return [];let r=[];for(let n of ir(t,"Transform",O)){let i=n.getAttribute("Algorithm");i&&r.push(i);}return r}function ms(e,t){let r=[e.documentElement];for(;r.length>0;){let n=r.pop();if(!n||!Ye(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 ds(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=ms(e,r);if(!n)throw new Error(`Unable to resolve signature reference URI: ${t}`);return {kind:"node",node:n}}function ge(e){return (e.textContent??"").trim()}function ps(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 hs(e,t){let r=ps(e);if(typeof crypto<"u"&&crypto.subtle){let s=await crypto.subtle.digest(r,tr(t));return new Uint8Array(s)}let n=await import('crypto'),i=r.toLowerCase().replace("-",""),o=n.createHash(i);return o.update(t),new Uint8Array(o.digest())}function gs(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 lt(e){let t=0;for(;t<e.length-1&&e[t]===0;)t++;return e.subarray(t)}async function bs(e){let t=await import('crypto'),r=$(e,"X509Data",O);if(r){let i=$(r,"X509Certificate",O);if(i){let o=await he(ge(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 a=lt(await he(ge(o))),c=lt(await he(ge(s))),u={kty:"RSA",n:ut(a),e:ut(c)};return t.createPublicKey({key:u,format:"jwk"})}}throw new Error("Unsupported KeyInfo content")}async function ys(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=lt(await he(ge(i))),a=lt(await he(ge(o))),c={kty:"RSA",n:ut(s),e:ut(a),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",c,u,false,["verify"])}async function ws(e,t){let r=$(e,"KeyInfo",O);if(!r)throw new Error("Missing ds:KeyInfo in signature");try{return {kind:"node",key:await bs(r)}}catch(n){if(typeof crypto<"u"&&crypto.subtle)try{return {kind:"webcrypto",key:await ys(r,t)}}catch(i){throw new Error(`Unable to load signature public key (node=${n.message}; web=${i.message})`)}throw n}}function Ss(e){return e.toLowerCase().replace("-","")}function xn(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 Is(e,t,r,n){if(n.kind==="node"){let o=await import('crypto'),s=o.createVerify(Ss(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:xn(r.hash)},t):s.verify(n.key,t)}let i;return r.kind==="rsa-pss"?i={name:"RSA-PSS",saltLength:xn(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,tr(t),tr(e))}async function As(e,t){let r=t.getAttribute("URI"),n=ds(e,r),i=fs(t);for(let o of i){if(o===es){if(n.kind!=="node")throw new Error("Enveloped-signature transform requires XML node input");n={kind:"node",node:cs(n.node)};continue}if(o===ts){let s=n.kind==="node"?ge(n.node):new TextDecoder("ascii").decode(n.bytes);n={kind:"bytes",bytes:await he(s)};continue}if(or(o)){if(n.kind!=="node")throw new Error("Canonicalization transform requires XML node input");n={kind:"bytes",bytes:er(rr(n.node,o))};continue}throw new Error(`Unsupported signature transform: ${o}`)}return n.kind==="bytes"?n.bytes:er(rr(n.node,nr))}async function xs(e,t){let r=ir(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 a=o.getAttribute("Algorithm");if(!a)throw new Error(`Reference ${i} missing DigestMethod Algorithm`);let c=await he(ge(s)),u=await As(e,n),f=await hs(a,u);if(c.length!==f.length)throw new Error(`Reference digest length mismatch for URI ${i}`);for(let l=0;l<c.length;l++)if(c[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 Tn(e){let t=Fn(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")??nr;if(!or(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 a=$(t,"SignatureValue",O);if(!a)return te(s,"SignatureValue is missing");let c;try{c=gs(s);}catch(d){return te(s,d.message)}try{await xs(e,r);}catch(d){return te(s,`Digest verification failed: ${d.message}`)}let u=er(rr(r,i)),f=await he(ge(a)),l;try{l=await ws(t,c);}catch(d){return te(s,`Key loading failed: ${d.message}`)}let m=false;try{m=await Is(u,f,c,l);}catch(d){return te(s,`Signature verification failed: ${d.message}`)}return m?{present:true,verified:true,algorithm:c.name}:te(s,"SignatureValue does not match SignedInfo")}function Fs(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??ct,resourceResolver:e?.resourceResolver??pn}}function Pn(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Rn(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}async function Cn(e){let t=e.replace(/\s+/g,"");if(typeof atob=="function"){let o=atob(t),s=new Uint8Array(o.length);for(let a=0;a<o.length;a++)s[a]=o.charCodeAt(a);return s}let i=(await new Function("p","return import(p)")("node:buffer")).Buffer.from(t,"base64");return new Uint8Array(i)}function Un(e,t){e.onWarning(t);}function ar(e,t,r){if(e.strictValidation)throw t;Un(e,{code:r,message:t.message});}async function Es(e){if(e.location.type==="inline")return e.location.encoding==="base64"?Cn(e.inlineData??""):Rn("hex",e.inlineData??"");if(e.location.type==="embedded")return (e.location.encoding??"base64")==="base64"?Cn(e.embeddedData??""):Rn("hex",e.embeddedData??"");throw new B("decodeInlineOrEmbedded called on non-inline block")}var Z=class e{unit;constructor(t){this.unit=t;}static async fromArrayBuffer(t,r){let n=Fs(r);if(!n.verifySignatures&&n.signaturePolicy==="require")throw new Be("signaturePolicy=require requires verifySignatures=true");let i="",o;Qr(t)?(i=en(t).headerXml,o=t):i=new TextDecoder("utf-8").decode(new Uint8Array(t));let s=on(i),a=En(s),c=s.documentElement,u=a&&n.verifySignatures&&n.signaturePolicy!=="ignore",f=new Map;for(let S=0;S<c.childNodes.length;S++){let w=c.childNodes.item(S);if(!w||w.nodeType!==1)continue;let I=w,A=I.getAttribute("uid");A&&f.set(A,I);}let l=S=>f.get(S)??null,m=async(S,w)=>{let I,A=w.location;if(A.type==="inline"||A.type==="embedded")I=await Es(w);else if(A.type==="attachment"){if(!o)throw new Q("Attachment location found but no monolithic XISF payload exists");I=tn(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&&!w.checksum&&ar(n,new pe(`Checksum is required for signed block in ${S.tagName}`),"checksum_required_for_signed_block"),w.checksum&&(n.verifyChecksums||u)&&(await Sn(I,w.checksum)||ar(n,new pe(`Checksum mismatch for ${S.tagName}`),"checksum_mismatch")),w.compression)try{I=mn(I,w.compression,n.codecProvider);}catch(E){ar(n,E,"decompression_failed");}return I},d=[],p=[],h=[],b=ee(c,"Metadata")[0];if(b){let S=ee(b,"Property");for(let w of S)d.push(await Ae(w,m,{strictValidation:n.strictValidation}));}let g=[];for(let S of ee(c,"Image")){let w=await jt(S,l,m,n.decodeImageData,n.strictValidation);g.push(w);}for(let S=0;S<c.childNodes.length;S++){let w=c.childNodes.item(S);if(!w||w.nodeType!==1)continue;let I=w,A=Ie(I);A==="Property"?p.push(await Ae(I,m,{strictValidation:n.strictValidation})):A==="Table"&&h.push(await at(I,l,m,{strictValidation:n.strictValidation}));}let y={present:false,verified:true};if(a&&n.signaturePolicy==="ignore")y={present:true,verified:false,reason:"Signature verification skipped by signaturePolicy=ignore"};else if(n.verifySignatures&&(y=await Tn(s),y.present&&!y.verified)){if(n.signaturePolicy==="require")throw new Be(y.reason??"Signature verification failed");Un(n,{code:"signature_verification_failed",message:y.reason??"Signature verification failed"});}return new e({metadata:d,images:g,standaloneProperties:p,standaloneTables:h,version:c.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 Q(`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(Pn(o),t.indexId):o}let n=an(t.path,r.headerDir||void 0),i=await r.resourceResolver.resolvePath(n);return t.indexId?e.sliceIndexedBlock(Pn(i),t.indexId):i}static sliceIndexedBlock(t,r){let i=gn(t).byId.get(r);if(!i)throw new F(`Missing XISB block for indexId ${r.toString(16)}`);return bn(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 pt={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"},Dn={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"},Ts=new Set(["UInt8","UInt16","UInt32","UInt64","Float32","Float64","Complex32","Complex64"]),Ps=new Set(["Gray","RGB","CIELab"]),Rs=new Set(["Planar","Normal"]);function Bn(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??ct}}function On(e){return typeof e=="boolean"?e?"true":"false":typeof e=="bigint"?e.toString(10):String(e)}function cr(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 ft(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 mt(e){let t=pt[e]??Dn[e];return t?cr(t)>1:false}function Cs(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 Us(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 Nn(e){return ArrayBuffer.isView(e)?Array.from(e):Array.isArray(e)?e.length>0&&Array.isArray(e[0])?e.flat():e:[]}function Mn(e){let r=(e.dataBlock?.byteOrder==="big"?"big":"little")==="little",n=(s,a)=>{if(s==="Complex32"||s==="Complex64"){let l=s==="Complex32"?4:8,m=new Uint8Array(a.length*l*2),d=new DataView(m.buffer);for(let p=0;p<a.length;p++){let h=Us(a[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 c=new Uint8Array(a.length*cr(s)),u=new DataView(c.buffer),f=cr(s);for(let l=0;l<a.length;l++)Cs(u,s,l*f,a[l],r);return c},i=pt[e.type];if(i){let s=Nn(e.value);return {bytes:n(i,s),itemCount:s.length}}let o=Dn[e.type];if(o){let s=e.value,a=e.rows??s?.rows,c=e.columns??s?.columns,u=s?.values??e.value,f=Nn(u);return {bytes:n(o,f),itemCount:f.length,rows:a,columns:c}}}function vn(e,t){if(!Ts.has(e.sampleFormat))throw new F(`Unsupported image sampleFormat: ${e.sampleFormat}`);if(!Ps.has(e.colorSpace??"Gray"))throw new F(`Unsupported image colorSpace: ${e.colorSpace}`);if(!Rs.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 kn(e,t,r,n){let i=e;if(r.compression){let o=dn(i,r.compression,r.codecProvider,r.compressionLevel,n);i=o.data;let s=o.spec,a=s.itemSize?`${s.codec}:${s.uncompressedSize}:${s.itemSize}`:`${s.codec}:${s.uncompressedSize}`;t.setAttribute("compression",a);}if(r.checksumAlgorithm){let o=await Jt(i,r.checksumAlgorithm);t.setAttribute("checksum",`${r.checksumAlgorithm}:${o}`);}return i}function Ze(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 a=new TextEncoder().encode(String(s));o.setAttribute("location",`attachment:0:${a.byteLength}`),n.push({element:o,data:a});}else r.type==="String"&&!r.dataBlock?o.appendChild(e.createTextNode(String(s))):o.setAttribute("value",On(s));else if(ArrayBuffer.isView(s)){let a=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);a.byteLength<=i?(o.setAttribute("length",String(s.length??a.byteLength)),o.setAttribute("location","inline:base64"),o.appendChild(e.createTextNode(dt(a)))):(o.setAttribute("length",String(s.length??a.byteLength)),o.setAttribute("location",`attachment:0:${a.byteLength}`),n.push({element:o,data:a})),mt(r.type)&&r.dataBlock?.byteOrder&&o.setAttribute("byteOrder",r.dataBlock.byteOrder);}else {let a=Mn(r);a&&(a.rows!==void 0&&o.setAttribute("rows",String(a.rows)),a.columns!==void 0&&o.setAttribute("columns",String(a.columns)),r.type in pt&&o.setAttribute("length",String(a.itemCount)),a.bytes.byteLength<=i?(o.setAttribute("location","inline:base64"),o.appendChild(e.createTextNode(dt(a.bytes)))):(o.setAttribute("location",`attachment:0:${a.bytes.byteLength}`),n.push({element:o,data:a.bytes})),mt(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 ur(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 a of r.structure){let c=e.createElement("Field");c.setAttribute("id",a.id),c.setAttribute("type",a.type),a.format&&c.setAttribute("format",a.format),a.header&&c.setAttribute("header",a.header),s.appendChild(c);}o.appendChild(s);for(let a of r.dataRows){let c=e.createElement("Row");for(let u=0;u<a.cells.length;u++){let f=a.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",On(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(dt(p)))):(m.setAttribute("location",`attachment:0:${p.byteLength}`),n.push({element:m,data:p})),d&&mt(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder);}else if(d){let p=Mn({...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 pt&&m.setAttribute("length",String(p.itemCount)),p.bytes.byteLength<=i?(m.setAttribute("location","inline:base64"),m.appendChild(e.createTextNode(dt(p.bytes)))):(m.setAttribute("location",`attachment:0:${p.bytes.byteLength}`),n.push({element:m,data:p.bytes})),mt(d)&&f.dataBlock?.byteOrder&&m.setAttribute("byteOrder",f.dataBlock.byteOrder));}}c.appendChild(m);}o.appendChild(c);}t.appendChild(o);}function Ln(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)Ze(e,t,o,n,i);for(let o of r.tables)ur(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 dt(e){if(typeof btoa=="function"){let r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}let t=globalThis;if(t.Buffer)return t.Buffer.from(e).toString("base64");throw new F("No base64 encoder available in this environment")}async function Bs(e,t,r){let n=-1,i="",o=0;for(;o!==n;){let a=t.ownerDocument;if(i=ot(a),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 a of r){let c=a.element.getAttribute("location");if(!c)continue;let u=c.split(":"),f=Number(u[1]);s.push({position:f,data:a.data});}return s}var re=class{static async toMonolithic(t,r){let n=Bn(r),i=Ht(),o=i.documentElement,s=i.createElement("Metadata"),a=[];for(let l of t.metadata)Ze(i,s,l,a,n.maxInlineBlockSize);o.appendChild(s);for(let l of t.standaloneProperties)Ze(i,o,l,a,n.maxInlineBlockSize);for(let l of t.standaloneTables)ur(i,o,l,a,n.maxInlineBlockSize);for(let l of t.images){if(vn(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&&ft(l.sampleFormat)>1&&m.setAttribute("byteOrder",l.dataBlock.byteOrder);let d=ft(l.sampleFormat),p=await kn(l.data,m,n,Math.max(1,d));m.setAttribute("location",`attachment:0:${p.byteLength}`),a.push({element:m,data:p}),Ln(i,m,l,a,n.maxInlineBlockSize),o.appendChild(m);}let c=await Bs(n,o,a),u=ot(i);return rn(u,c).slice().buffer}static async toDistributed(t,r){let n=Bn(r),i=Ht(),o=i.documentElement,s=[],a=[],c=i.createElement("Metadata");o.appendChild(c);let u=(d,p)=>{s.push({element:d,data:p});};for(let d of t.metadata)Ze(i,c,d,a,n.maxInlineBlockSize);for(let d of t.standaloneProperties)Ze(i,o,d,a,n.maxInlineBlockSize);for(let d of t.standaloneTables)ur(i,o,d,a,n.maxInlineBlockSize);for(let d of t.images){if(vn(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&&ft(d.sampleFormat)>1&&p.setAttribute("byteOrder",d.dataBlock.byteOrder);let h=ft(d.sampleFormat),b=await kn(d.data,p,n,Math.max(1,h));p.setAttribute("location",`attachment:0:${b.byteLength}`),a.push({element:p,data:b}),Ln(i,p,d,a,n.maxInlineBlockSize),o.appendChild(p);}for(let d of a)u(d.element,d.data);let{bytes:f,ids:l}=yn(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(ot(i)),blocks:{"blocks.xisb":f}}}};function ht(e){return e.padEnd(80," ").slice(0,80)}function Ns(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 vs(e){let t=e.key.toUpperCase().slice(0,8).padEnd(8," ");if(e.key==="END")return ht("END");if(e.value===void 0)return ht(`${t} ${e.comment??""}`);let r=Ns(e.value),n=`${t}= ${r}`;return e.comment?ht(`${n} / ${e.comment}`):ht(n)}function Xn(e){return e+(2880-e%2880)%2880}function ks(e){let t=[...e];t.some(i=>i.key==="END")||t.push({key:"END"});let r=t.map(vs).join(""),n=r.padEnd(Xn(r.length)," ");return new TextEncoder().encode(n)}function ne(e){let t=e.map(s=>ks(s.cards)),r=e.map(s=>{let a=s.data??new Uint8Array(0),c=Xn(a.byteLength),u=new Uint8Array(c);return u.set(a),u}),n=t.reduce((s,a)=>s+a.byteLength,0)+r.reduce((s,a)=>s+a.byteLength,0),i=new Uint8Array(n),o=0;for(let s=0;s<e.length;s++){let a=t[s],c=r[s];i.set(a,o),o+=a.byteLength,i.set(c,o),o+=c.byteLength;}return i.buffer}function W(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],a=o*r;switch(t){case 8:i.setUint8(a,Number(s));break;case 16:i.setInt16(a,Number(s),false);break;case 32:i.setInt32(a,Number(s),false);break;case 64:i.setBigInt64(a,BigInt(s),false);break;case -32:i.setFloat32(a,Number(s),false);break;case -64:i.setFloat64(a,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 fr=32768,mr=2147483648,gt=9223372036854775808n,Hn="FITS:PreservedHDULayout";function Ls(e){return e.reduce((t,r)=>t*r,1)}function lr(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 dr(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 Ds(e){if(!e.data)throw new j("XISF image data was not decoded");let t=dr(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",a=dr(s),c=new Array(n*t/a),u=0;for(let f=0;f<n;f++){let l=f*t;c[u++]=Number(lr(r,l,s,i)),c[u++]=Number(lr(r,l+a,s,i));}return c}let o=new Array(n);for(let s=0;s<n;s++)o[s]=lr(r,s*t,e.sampleFormat,i);if(e.pixelStorage==="Normal"&&e.channelCount>1){let s=n/e.channelCount,a=new Array(n),c=0;for(let u=0;u<e.channelCount;u++)for(let f=0;f<s;f++)a[c++]=o[f*e.channelCount+u];return a}return o}function Os(e,t){let r=dr(t),n=new Uint8Array(e.length*r),i=new DataView(n.buffer);for(let o=0;o<e.length;o++){let s=e[o],a=o*r;switch(t){case "UInt8":i.setUint8(a,Number(s));break;case "UInt16":i.setUint16(a,Number(s),true);break;case "UInt32":i.setUint32(a,Number(s),true);break;case "UInt64":i.setBigUint64(a,BigInt(s),true);break;case "Float32":i.setFloat32(a,Number(s),true);break;case "Float64":i.setFloat64(a,Number(s),true);break;}}return n}function Ms(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],a=o*r;t==="Complex32"?i.setFloat32(a,s,true):i.setFloat64(a,s,true);}return n}function $n(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function Xs(e){if(typeof btoa=="function"){let r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r)}return (await import('buffer')).Buffer.from(e).toString("base64")}async function _s(e){if(typeof atob=="function"){let r=e.replace(/\s+/g,""),n=atob(r),i=new Uint8Array(n.length);for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);return i}let t=await import('buffer');return new Uint8Array(t.Buffer.from(e,"base64"))}function Hs(e){return JSON.stringify({metadata:e.unit.metadata,standaloneProperties:e.unit.standaloneProperties,standaloneTables:e.unit.standaloneTables},null,0)}function $s(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=Ls(e.geometry.slice(2));return {width:t,height:r,depth:e.channelCount*n}}function Vn(e){return e?.strictValidation??e?.relaxed!==true}function Vs(e,t){let r=e.get(t);return r===true||r==="T"||r==="true"||r===1}function Ws(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 _n(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:Ws(o.slice(10))}return null}function zs(e){if(!e)return null;let t=e.trim();if(!/^[-+]?\d+$/u.test(t))return null;try{return BigInt(t)}catch{return null}}function Gs(e,t){if(t.bitpix!==64)return false;let r=_n(e,"BSCALE"),n=_n(e,"BZERO");return (r?Number(r):1)!==1?false:zs(n)===gt}function js(e){return e===true?"T":e===false?"F":e==null?"":String(e)}function Ks(e,t,r){let n=e.filter(i=>i.id!==t);return n.push({id:t,type:"String",value:r}),n}function Ys(e){let t=e.find(r=>r.id===Hn);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 Zs(e,t){return {cards:e.cards.map(r=>({key:r.key,value:r.value,comment:r.comment})),data:t}}async function qs(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 Xs(n)}}async function pr(e,t){let r=Vn(t),n=e instanceof Z?e:await Z.fromArrayBuffer(await $n(e),{strictValidation:r}),i=[];for(let u=0;u<n.unit.images.length;u++){let f=n.unit.images[u],l=Ds(f),{width:m,height:d,depth:p}=$s(f),h=f.fitsKeywords.map(S=>({key:S.name,value:S.value,comment:S.comment}));if(f.sampleFormat==="Complex32"||f.sampleFormat==="Complex64"){let S=W(l,f.sampleFormat==="Complex32"?-32:-64),w=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:w,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:S});continue}let b,g,y;switch(f.sampleFormat){case "UInt8":b=8,y=W(l,8);break;case "UInt16":{b=16,g=fr;let S=Array.from(l,w=>Number(w)-fr);y=W(S,16);break}case "UInt32":{b=32,g=mr;let S=Array.from(l,w=>Number(w)-mr);y=W(S,32);break}case "UInt64":{b=64,g=gt;let S=Array.from(l,w=>BigInt(w)-gt);y=W(S,64);break}case "Float32":b=-32,y=W(l,-32);break;case "Float64":b=-64,y=W(l,-64);break;default:throw new j(`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=Ys(n.unit.metadata),s=[];if(o)for(let u of o.nonImageHDUs)s.push({index:u.index,hdu:Zs(u,await _s(u.dataBase64))});if(n.unit.images.length===0){if(s.length===0)throw new j("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 a=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);}a=l;}else s.length>0&&(a=[...i,...s.sort((u,f)=>u.index-f.index).map(u=>u.hdu)]);if(t?.includeXisfMetaExtension??true){let u=new TextEncoder().encode(Hs(n));a.push(ie({primary:false,extensionType:"IMAGE",width:u.byteLength,height:1,bitpix:8,data:u,extname:"XISF_META"}));}return ne(a)}async function Js(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 Qs(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 j("Image data source is unavailable for UInt64 conversion");n.buffers=[i];}let o=new DataView(i),s=i.byteLength/8;for(let a=0;a<s;a++)t.push(o.getBigInt64(a*8,false)+gt);}return t}function ea(e,t){let r=t.bzero;return t.bitpix===8?"UInt8":t.bitpix===16&&r===fr?"UInt16":t.bitpix===32&&r===mr?"UInt32":Gs(e,t)?"UInt64":t.bitpix===-32?"Float32":(t.bitpix===-64,"Float64")}async function hr(e,t){let r=Vn(t),n=t?.writeOptions,i=e instanceof z?e:z.fromArrayBuffer(await $n(e),{onWarning:r?void 0:()=>{}}),o=[],s=[],a=[],c={};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 Y&&Vs(d,"XISFCPLX")){let w=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 j("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:w,pixelStorage:"Planar",colorSpace:"Gray",dataBlock:{location:{type:"attachment",position:0,size:C.length*(w==="Complex32"?4:8)},byteOrder:"little"},data:Ms(C,w),properties:[],tables:[],fitsKeywords:[]}),s.push(l);continue}if(!m.data||!(m.data instanceof J)){a.push(await qs(m,l));continue}if(p==="XISF_META"){let w=await m.data.getFrame(0),I=new Uint8Array(w.length);for(let A=0;A<w.length;A++)I[A]=Number(w[A])&255;try{c=JSON.parse(new TextDecoder("utf-8").decode(I));}catch{}continue}let h=ea(d,m.data);if(r&&m.data.bitpix===64&&h!=="UInt64")throw new j("FITS BITPIX=64 without canonical UInt64 BZERO cannot be converted losslessly");let b=h==="UInt64"?await Qs(m.data):await Js(m.data),g=Os(b,h),y=d.getCards().map(w=>({name:w.key,value:js(w.value),comment:w.comment})),S=[m.data.width,m.data.height];m.data.depth>1&&S.push(m.data.depth),o.push({id:p||(l===0?"PRIMARY":`IMAGE_${l}`),geometry:S,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&&a.length===0)throw new j("No convertible FITS image HDUs found");let u=c.metadata??[{id:"XISF:CreatorApplication",type:"String",value:"fitsjs-ng conversion"},{id:"XISF:CreationTime",type:"TimePoint",value:new Date().toISOString()}];a.length>0&&(u=Ks(u,Hn,JSON.stringify({imageSourceIndices:s,nonImageHDUs:a})));let f={metadata:u,images:o,standaloneProperties:c.standaloneProperties??[],standaloneTables:c.standaloneTables??[],version:"1.0",signature:{present:false,verified:true}};return t?.distributed?re.toDistributed(f,n):re.toMonolithic(f,n)}var ke=class extends oe{constructor(t){super(t),this.name="SERError";}},fe=class extends ke{constructor(t){super(t),this.name="SERParseError";}},L=class extends ke{constructor(t){super(t),this.name="SERValidationError";}},_=class extends ke{constructor(t){super(t),this.name="SERConversionError";}};var qe="LUCAM-RECORDER",Wn=[0,8,9,10,11,16,17,18,19,100,101],xe={0:1,8:1,9:1,10:1,11:1,16:1,17:1,18:1,19:1,100:3,101:3},Le={8:"RGGB",9:"GRBG",10:"GBRG",11:"BGGR",16:"CYYM",17:"YCMY",18:"YMCY",19:"MYYC"},zn=621355968000000000n;var ta=e=>{};function ra(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??ta}}function De(e,t,r){e.onWarning({code:t,message:r});}function bt(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 Gn(e){return Wn.includes(e)}function na(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=c=>{let u=new DataView(r.buffer,r.byteOffset,r.byteLength),f=c==="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 S=0;S<l;S++){let w=u.getUint16(S*2,f);w%256===0&&m++,h.add(w&255),p+=Math.abs(w-d),d=w;}let b=h.size/256,g=1-m/l,y=1/(1+p/l);return g*.5+b*.4+y*.1},s=o(n),a=o(i);return s>=a?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 jn(e,t,r){let n=ra(t),i=new Uint8Array(e);if(i.byteLength<178)throw new fe(`SER buffer is too short: expected at least ${178} bytes, got ${i.byteLength}`);let o=new DataView(e),s=bt(i.slice(0,14));if(s!==qe)throw new fe(`Invalid SER FileID: expected "${qe}", got "${s}"`);let a=o.getInt32(14,true),c=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=bt(i.slice(42,82)),h=bt(i.slice(82,122)),b=bt(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(!Gn(c)){let T=`Unsupported SER color ID: ${c}`;if(n.strictValidation)throw new L(T);De(n,"unsupported_color_id",`${T}; falling back to monochrome (0)`);}let S=Gn(c)?c:0,w=xe[S],I=m<=8?1:2,A=f*l*w*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 N=ia(E,x,A);De(n,"frame_count_adjusted",`${T}; adjusted to ${N}`),E=N;}E===0&&De(n,"empty_sequence","SER sequence has zero frames");let k=E>0?i.slice(178,178+Math.min(A,8192)):null,R=na(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 N=true;for(let U=1;U<M.length;U++)if(M[U]<M[U-1]){N=false;break}if(N||De(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);De(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);De(n,"truncated_timestamps",T);}let K=[];for(let T=0;T<E;T++)K.push({index:T,offset:178+T*A,byteLength:A,timestamp:M[T]});return {header:{fileId:s,luId:a,colorId:S,littleEndianFlag:u,byteOrder:R,width:f,height:l,pixelDepth:m,frameCount:E,observer:p,instrument:h,telescope:b,startTime:g,startTimeUtc:y,channelCount:w,bytesPerSample:I,frameByteLength:A},frameInfos:K,timestamps:M,timestampsPresent:P,buffer:e,blob:r}}function gr(e,t){return jn(e,t)}async function br(e,t){let r=await e.arrayBuffer();return jn(r,t,e)}function oa(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 sa(e){return Le[e]}function Je(e,t,r,n){return Number(e[r*n+t]??0)}function Kn(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 aa(e,t,r,n,i){let o=i===1?new Uint8Array(t*r*3):new Uint16Array(t*r*3),s=(c,u)=>n[u%2*2+c%2]??"R",a=(c,u,f)=>{for(let m=0;m<=3;m++){let d=Math.max(0,c-m),p=Math.min(t-1,c+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[S,w,I]=Kn(s(y,g));if(f===0?S:f===1?w:I)return Je(e,y,g,t)}}return Je(e,c,u,t)};for(let c=0;c<r;c++)for(let u=0;u<t;u++){let f=(c*t+u)*3,l=s(u,c),[m,d,p]=Kn(l);o[f]=m?Je(e,u,c,t):a(u,c,0),o[f+1]=d?Je(e,u,c,t):a(u,c,1),o[f+2]=p?Je(e,u,c,t):a(u,c,2);}return o}var Fe=class e{parsed;constructor(t){this.parsed=t;}static fromArrayBuffer(t,r){return new e(gr(t,r))}static async fromBlob(t,r){return new e(await br(t,r))}static async fromURL(t,r){let n=await fetch(t,r?.requestInit);if(!n.ok)throw new fe(`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-zn,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 fe("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 c=o===1?new Uint8Array(s*3):new Uint16Array(s*3);for(let u=0;u<s;u++){let f=u*3;r===100?(c[f]=t[f]??0,c[f+1]=t[f+1]??0,c[f+2]=t[f+2]??0):(c[f]=t[f+2]??0,c[f+1]=t[f+1]??0,c[f+2]=t[f]??0);}return c}if(r===0){let c=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;c[l]=f,c[l+1]=f,c[l+2]=f;}return c}let a=sa(r);if(!a)throw new L(`No RGB decode helper available for color ID ${r}`);return aa(t,n,i,a,o)}getFrame(t,r){let n=this.getFrameInfo(t),i=this.readFrameRawBytes(n),o=oa(i,this.parsed.header.bytesPerSample,this.parsed.header.byteOrder),s=r?.asRGB?this.samplesToRGB(o,this.parsed.header.colorId):o,a=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:a,interleaved:a>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 ca=e=>{};function ua(e){return {strictValidation:e?.strictValidation??true,endiannessPolicy:e?.endiannessPolicy??"compat",onWarning:e?.onWarning??ca}}function wr(e,t,r){e.onWarning({code:t,message:r});}function yt(e,t,r,n){let o=new TextEncoder().encode(n);for(let s=0;s<r;s++)e[t+s]=o[s]??0;}function yr(e,t){return e===void 0?t:typeof e=="bigint"?e:BigInt(Math.trunc(e))}function la(e,t){return t==="spec"?e?1:0:e?0:1}function fa(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);wr(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 wt(e,t){let r=ua(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=xe[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);wr(r,"frame_count_mismatch",g);}let s=n.pixelDepth<=8?1:2,a=n.width*n.height*o*s;if(!Number.isSafeInteger(a)||a<=0)throw new L(`Invalid computed frame length: ${a}`);let c=[];for(let g=0;g<i;g++){let y=e.frames[g]??new Uint8Array(0);c.push(fa(y,a,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);wr(r,"timestamp_count_mismatch",g);}u=new Array(i);for(let g=0;g<i;g++)u[g]=yr(e.timestamps[g],0n);}let f=i*a,l=u?i*8:0,m=178+f+l,d=new Uint8Array(m),p=new DataView(d.buffer);yt(d,0,14,qe),p.setInt32(14,n.luId??0,true),p.setInt32(18,n.colorId,true);let h=n.littleEndian??true;p.setInt32(22,la(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),yt(d,42,40,n.observer??""),yt(d,82,40,n.instrument??""),yt(d,122,40,n.telescope??""),p.setBigUint64(162,yr(n.startTime,0n),true),p.setBigUint64(170,yr(n.startTimeUtc,0n),true);let b=178;for(let g of c)d.set(g,b),b+=a;if(u)for(let g=0;g<u.length;g++)p.setBigUint64(b+g*8,u[g],true);return d.buffer}var Qn="SERCOLOR",ei="SERPDEP",Ir="SERFRMS",ti="SERCHANS",ma="SERCHORD",ri="SERLUID",ni="SERBYORD",ii="SEROBS",oi="SERINST",si="SERTEL",ai="SERSTRT",ci="SERSTUTC",da="SERCFAP",ui="SERFRAME",li="SER_TSTP",fi=32768;function At(e){return e?.strictValidation??e?.relaxed!==true}function mi(e){return e instanceof ArrayBuffer?Promise.resolve(e):e.arrayBuffer()}function di(e,t){return e instanceof Fe?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(Fe.fromArrayBuffer(e,{strictValidation:At(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})):Fe.fromBlob(e,{strictValidation:At(t),endiannessPolicy:t?.endiannessPolicy,onWarning:t?.onWarning})}function pa(e){return e instanceof z?Promise.resolve(e):e instanceof ArrayBuffer?Promise.resolve(z.fromArrayBuffer(e)):mi(e).then(t=>z.fromArrayBuffer(t))}function be(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 ha(e,t){return e.metadata.find(r=>r.id===t)}function ga(e,t){return e.properties.find(r=>r.id===t)}function ue(e,t,r){let n=ga(t,r);return n?.value!==void 0?n.value:ha(e,r)?.value}function ba(e,t,r){let n=ue(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=>be(i)).filter(i=>i!==null):[]}function Ar(e,t,r){e?.onWarning?.({code:t,message:r});}function ya(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 wa(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 Sa(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 Ia(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:li}],data:t}}function Aa(e){if(e.channelCount===3)return 100;let t=e.colorFilterArray?.pattern;if(!t)return 0;let r=Object.entries(Le).find(([,n])=>n===t);return r?Number(r[0]):0}function Yn(e,t){let r=e.get(t);return be(r)??void 0}function St(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 It(e,t){let r=e.get(t);return typeof r=="string"?r:void 0}function xa(e){let t=e.getHeader(),r=Le[t.colorId];return [{key:Qn,value:t.colorId},{key:ei,value:t.pixelDepth},{key:Ir,value:t.frameCount},{key:ti,value:t.channelCount},{key:ma,value:t.colorId===101?"BGR":"RGB"},{key:ri,value:t.luId},{key:ni,value:t.byteOrder},{key:ii,value:t.observer},{key:oi,value:t.instrument},{key:si,value:t.telescope},{key:ai,value:t.startTime.toString()},{key:ci,value:t.startTimeUtc.toString()},...r?[{key:da,value:r}]:[]]}function Zn(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 qn(e){return e.map(t=>t-fi)}function Fa(e){return e.hdus.filter(t=>t.data instanceof J).map(t=>({header:t.header,image:t.data}))}function Ea(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 a=s.getString("EXTNAME","").trim().toUpperCase();return s.contains(ui)||a.startsWith("SER_FRAME_")||a==="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 Ta(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 c=`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 _(c);return Ar(r,"fits_multi_hdu_incompatible",c),false});if(i.length===0)throw new _("No compatible image HDUs available for multi-HDU FITS conversion");return i}async function Sr(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 c=0;c<i;c++)o[c]=Number(s[c]??0)&255;return o}let a=new DataView(o.buffer);for(let c=0;c<i;c++)a.setUint16(c*2,Number(s[c]??0),n);return o}async function Jn(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 c=0;c<i;c++)o[c*3]=Number(s[0][c]??0)&255,o[c*3+1]=Number(s[1][c]??0)&255,o[c*3+2]=Number(s[2][c]??0)&255;return o}let a=new DataView(o.buffer);for(let c=0;c<i;c++)a.setUint16(c*6,Number(s[0][c]??0),n),a.setUint16(c*6+2,Number(s[1][c]??0),n),a.setUint16(c*6+4,Number(s[2][c]??0),n);return o}async function Pa(e,t,r,n,i){let o=e.width*e.height,s=new Uint8Array(o*3*n),[a,c,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(a[l]??0)&255,s[l*3+1]=Number(c[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(a[l]??0),i),f.setUint16(l*6+2,Number(c[l]??0),i),f.setUint16(l*6+4,Number(u[l]??0),i);return s}async function Ra(e,t){let r=await di(e,t),n=r.getHeader(),i=n.frameCount,o=xa(r),s=t?.layout??"cube",a=n.bytesPerSample===1?8:16,c=a===16?fi:void 0,u=[];if(s==="multi-hdu")for(let f=0;f<i;f++){let l=r.getFrame(f),m=Zn(l),d=a===16?qn(m):m,p=W(d,a);u.push(ie({primary:f===0,extensionType:"IMAGE",width:n.width,height:n.height,depth:n.channelCount===3?3:void 0,bitpix:a,bzero:c,bscale:c!==void 0?1:void 0,data:p,extname:f===0?void 0:`SER_FRAME_${f}`,additionalCards:f===0?o:[{key:ui,value:f},{key:Ir,value:i},{key:ti,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=Zn(p),b=a===16?qn(h):h;l.push(...b);}let m=W(l,a);u.push(ie({width:n.width,height:n.height,depth:f,bitpix:a,bzero:c,bscale:c!==void 0?1:void 0,data:m,additionalCards:o}));}return (t?.includeTimestampExtension??true)&&r.parsed.timestamps.length===i&&u.push(Ia(r.parsed.timestamps)),ne(u)}async function Ca(e,t){let r=At(t),n=await pa(e),i=Fa(n),o=i[0];if(!o)throw new _("No FITS image HDU found for SER conversion");let s=o.header,a=o.image,c=St(s,Qn)??0,u=xe[c]??1,f=St(s,ei);if(!f)if(a.bitpix===8)f=8;else if(a.bitpix===16)f=16;else throw new _(`Cannot infer SER pixel depth from FITS BITPIX=${a.bitpix}; metadata is missing`);let l=St(s,Ir),m=Ea(t,i,l),d=f<=8?1:2,p=m==="multi-hdu"?Ta(i,r,t):i,h=(It(s,ni)??"little")!=="big",b=It(s,ii)??"",g=It(s,oi)??"",y=It(s,si)??"",S=St(s,ri)??0,w=Yn(s,ai)??0n,I=Yn(s,ci)??w,A=[],x=l??0;if(m==="cube")if(u===1){x=l??a.depth;for(let R=0;R<x;R++)A.push(await Sr(a,R,d,h));}else {if(x=l??a.depth,!l)if(a.depth%3!==0){if(r)throw new _(`FITS depth ${a.depth} is not divisible by 3 for RGB/BGR SER reconstruction`);x=Math.floor(a.depth/3);}else x=a.depth/3;for(let R=0;R<x;R++)A.push(await Jn(a,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 Sr(R.image,H,d,h));else A.push(await Sr(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 Jn(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);Ar(t,"fits_multi_hdu_rgb_tail_drop",v),C-=C%3;}for(let v=0;v+2<C;v+=3)A.push(await Pa(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 Y&&R.header.getString("EXTNAME","").trim().toUpperCase()===li);if(k&&k.data instanceof Y){let R=k.data.columns?.[0];if(R&&(E=(await k.data.getColumn(R)).map(C=>be(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 wt({header:{colorId:c,width:a.width,height:a.height,pixelDepth:f,frameCount:x,littleEndian:h,luId:S,observer:b,instrument:g,telescope:y,startTime:w,startTimeUtc:I},frames:A,timestamps:E},{strictValidation:r,endiannessPolicy:t?.endiannessPolicy==="spec"?"spec":"compat",onWarning:t?.onWarning})}function Ua(e){return e===1?"UInt8":"UInt16"}function Ba(e){let t=e.getHeader(),r=t.frameCount,i=t.width*t.height*t.channelCount*r;if(t.bytesPerSample===1){let c=new Uint8Array(i),u=0;for(let f=0;f<r;f++){let l=e.getFrame(f),m=wa(l);c.set(m,u),u+=m.length;}return c}let o=new Uint8Array(i*2),s=new DataView(o.buffer),a=0;for(let c=0;c<r;c++){let u=e.getFrame(c),f=Sa(u);for(let l=0;l<f.length;l++)s.setUint16(a*2,f[l],true),a++;}return o}async function Na(e,t){let r=await di(e,t),n=r.getHeader(),i=Ba(r),o={id:"SER_SEQUENCE",geometry:[n.width,n.height,n.frameCount],channelCount:n.channelCount,sampleFormat:Ua(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=Le[n.colorId];s&&(o.colorFilterArray={pattern:s,width:2,height:2});let a=[{id:"XISF:CreatorApplication",type:"String",value:"fitsjs-ng SER conversion"},{id:"XISF:CreationTime",type:"TimePoint",value:new Date().toISOString()}];a=ya(a,r);let c={metadata:a,images:[o],standaloneProperties:[],standaloneTables:[],version:"1.0",signature:{present:false,verified:true}};return t?.distributed?re.toDistributed(c,t.writeOptions):re.toMonolithic(c,t?.writeOptions)}function va(e){if(!e.data)throw new _("XISF image data is not decoded");return e.data}function ka(e,t,r,n){let i=e.geometry[0]??0,o=e.geometry[1]??0,s=i*o,a=e.sampleFormat==="UInt16"?2:1,c=s*r*a,u=va(e),f=s*r*t*a;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(a===1){if(r===1)for(let h=0;h<t;h++){let b=new Uint8Array(c),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(c),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(c);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(c),g=new DataView(b.buffer);for(let y=0;y<s;y++){let S=l.getUint16((h*s+y)*2,m);g.setUint16(y*2,S,n);}d.push(b);}return d}if(e.pixelStorage==="Normal"){for(let h=0;h<t;h++){let b=new Uint8Array(c),g=new DataView(b.buffer);for(let y=0;y<s;y++){let S=(h*s*r+y*r)*2,w=y*r*2;g.setUint16(w,l.getUint16(S,m),n),g.setUint16(w+2,l.getUint16(S+2,m),n),g.setUint16(w+4,l.getUint16(S+4,m),n);}d.push(b);}return d}let p=s*t;for(let h=0;h<t;h++){let b=new Uint8Array(c),g=new DataView(b.buffer);for(let y=0;y<s;y++){let S=l.getUint16((h*s+y)*2,m),w=l.getUint16((p+h*s+y)*2,m),I=l.getUint16((p*2+h*s+y)*2,m),A=y*6;g.setUint16(A,S,n),g.setUint16(A+2,w,n),g.setUint16(A+4,I,n);}d.push(b);}return d}async function La(e,t){let r=At(t),n=e instanceof Z?e:await Z.fromArrayBuffer(await mi(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,a=o.geometry[1]??0;if(!s||!a)throw new _("XISF image must have width and height geometry");let c=ue(n.unit,o,"SER:ColorID"),u=be(c)??BigInt(Aa(o)),f=Number(u),l=xe[f]??(o.channelCount===3?3:1),m=o.geometry[2]??1,d=ue(n.unit,o,"SER:PixelDepth"),p=Number(be(d)??(o.sampleFormat==="UInt8"?8n:16n))||8,h=ue(n.unit,o,"SER:LittleEndian"),b=typeof h=="boolean"?h:String(h??"true").toLowerCase()!=="false",g=ka(o,m,l,b),y=ba(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}`);Ar(t,"xisf_timestamp_length_mismatch",`SER:FrameTimestamps length mismatch: expected ${m}, got ${y.length}; truncating`),y=y.slice(0,m);}let S=Number(be(ue(n.unit,o,"SER:LuID"))??0n),w=String(ue(n.unit,o,"SER:Observer")??""),I=String(ue(n.unit,o,"SER:Instrument")??""),A=String(ue(n.unit,o,"SER:Telescope")??""),x=be(ue(n.unit,o,"SER:StartTime"))??0n,E=be(ue(n.unit,o,"SER:StartTimeUTC"))??x;return wt({header:{colorId:f,width:s,height:a,pixelDepth:p,frameCount:m,littleEndian:b,luId:S,observer:w,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 Da={fits:"fits",png:"png",jpeg:"jpg"};function xr(e){return Da[e]}function pi(e){let t=e.toLowerCase();return t==="fits"?"fits":t==="png"?"png":t==="jpg"||t==="jpeg"?"jpeg":null}function hi(e){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid ipix: ${e}`);return Math.floor(e/1e4)*1e4}function xt(e){if(e.spectralOrder!==void 0||e.spectralIndex!==void 0){let t=e.spectralOrder??0,r=e.spectralIndex??0,n=`${hi(e.ipix)}_${Math.floor(r/10)*10}`;return `Norder${e.order}_${t}/Dir${n}/Npix${e.ipix}_${r}.${xr(e.format)}`}return `Norder${e.order}/Dir${hi(e.ipix)}/Npix${e.ipix}.${xr(e.format)}`}function Ft(e){return `Norder3/Allsky.${xr(e)}`}function Fr(e){let t=e.replaceAll("\\","/"),r=/^Norder(\d+)_(\d+)\/Dir(\d+)_(\d+)\/Npix(\d+)_(\d+)\.(\w+)$/i.exec(t);if(r){let o=pi(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=pi(n[4]);return i?{order:Number(n[1]),ipix:Number(n[3]),frame:"equatorial",format:i}:null}var Oa=["creator_did","obs_title","dataproduct_type","hips_version","hips_frame","hips_order","hips_tile_width","hips_tile_format"],Ma=["hips_cube_depth","hips_cube_firstframe"],Xa=new Set(["equatorial","galactic","ecliptic"]),_a=new Set(["image","cube"]),Ha=new Set(["fits","png","jpeg"]);function gi(e){return e.trim()}var Oe=class e{data=new Map;constructor(t){if(t)for(let[r,n]of Object.entries(t))this.data.set(r.trim(),gi(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(),a=i.slice(o+1).trim();r[s]=a;}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"?gi(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(`
|
|
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
4
|
`)+`
|
|
5
|
-
`}validate(){let t=Oa.filter(l=>!this.data.has(l)),r=[],n=[],i=this.get("hips_frame");i&&!Xa.has(i)&&r.push(`hips_frame=${i}`);let o=this.get("dataproduct_type");o&&!_a.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=>!Ha.has(m)))&&r.push(`hips_tile_format=${s}`),l.includes("jpg")&&n.push("hips_tile_format contains jpg alias; prefer jpeg");}let a=Number(this.get("hips_order"));this.has("hips_order")&&(!Number.isInteger(a)||a<0)&&r.push(`hips_order=${this.get("hips_order")}`);let c=Number(this.get("hips_tile_width"));this.has("hips_tile_width")&&(!Number.isInteger(c)||c<=0)?r.push(`hips_tile_width=${this.get("hips_tile_width")}`):this.has("hips_tile_width")&&Number.isInteger(c)&&(c&c-1)!==0&&n.push(`hips_tile_width=${c} 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(a)&&l>a&&r.push(`hips_order_min=${u} exceeds hips_order=${a}`);}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 Ma)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 bi(e){let t=Oe.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 za(e){let t=e%360;return t<0?t+360:t}function Ga(e,t,r){return Math.max(t,Math.min(r,e))}function ja(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 Et(e){let t=e.crpix1,r=e.crpix2,n=e.crval1,i=e.crval2,o=e.cd11,s=e.cd12,a=e.cd21,c=e.cd22;if(![o,s,a,c].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),S=Math.sin(g);o=h*y,s=-b*S,a=h*S,c=b*y;}let f=o*c-s*a;if(Math.abs(f)<1e-16)throw new Error("WCS matrix is singular");let l=c/f,m=-s/f,d=-a/f,p=o/f;return {definition:e,pixelToWorld(h,b){let g=h+1-t,y=b+1-r;return {lon:za(n+o*g+s*y),lat:Ga(i+a*g+c*y,-90,90)}},worldToPixel(h,b){let g=(h-n+540)%360-180,y=b-i,S=l*g+m*y,w=d*g+p*y;return {x:S+t-1,y:w+r-1}}}}function yi(e){return Et({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 wi(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 Et({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 Si(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 Ii(e,t,r,n){let i=order2nside(e.order),o=(t+.5)/n,s=(r+.5)/n,[a,c,u]=pixcoord2vec_nest(i,e.ipix,o,s),{theta:f,phi:l}=vec2ang([a,c,u]);return {lon:l*180/Math.PI,lat:90-f*180/Math.PI}}function Ka(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 Ai(e,t,r=1){let n=order2nside(e.order),{ctype1:i,ctype2:o}=ja(e.frame),s=45/t/n,a=Ka(e),c=[{key:"CTYPE1",value:i},{key:"CTYPE2",value:o},{key:"CRPIX1",value:t/2+.5},{key:"CRPIX2",value:t/2+.5},{key:"CRVAL1",value:a.lon},{key:"CRVAL2",value:a.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&&c.push({key:"FORDER",value:e.spectralOrder}),e.spectralIndex!==void 0&&c.push({key:"FPIX",value:e.spectralIndex}),r>1&&c.push({key:"NAXIS3",value:r}),c}function Qa(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 ec(e){let[t,r]=Qa(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 a=Math.max(0,Math.min(255,Math.round((s-t)*n)));i[o]=a;}return i}function tc(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function rc(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function xi(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,a=e[s]??0,c=e[s+1]??a,u=e[s+2]??a;i[o]=.299*a+.587*c+.114*u;}return i}async function Fi(e,t){let r=tc(t);if(e.format==="fits"){let s=z.fromArrayBuffer(rc(r)).getDataUnit();if(!(s instanceof J))throw new Error("FITS tile does not contain image data");let a=[],c=s.depth;for(let l=0;l<c;l++)a.push(await s.getFrame(l));let u=s.width*s.height,f=new Float32Array(u*c);for(let l=0;l<c;l++){let m=a[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:c,data:f}}if(e.format==="png"){let o=decode(r),s=xi(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=xi(n.data,n.width,n.height,4);return {meta:e,width:n.width,height:n.height,depth:1,data:i}}function Qe(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 c=W(t,-32),u=Ai(e,r,n),f=ie({primary:true,width:r,height:r,depth:n,bitpix:-32,data:c,additionalCards:u});return new Uint8Array(ne([f]))}let o=ec(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 c=0;c<o.length;c++){let u=o[c],f=c*4;s[f]=u,s[f+1]=u,s[f+2]=u,s[f+3]=255;}let a=encode$1({width:r,height:r,data:s},90);return new Uint8Array(a.data)}function Tt(e){return /^https?:\/\//iu.test(e)}async function Pt(){let[e,t]=await Promise.all([import('fs/promises'),import('path')]);return {fs:e,path:t}}var me=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(Tt(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 Pt();return n.readFile(i.join(r,t),"utf8")}}if(typeof this.source=="string"){if(Tt(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 Pt();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(Tt(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 Pt(),o=await n.readFile(i.join(r,t));return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}}if(typeof this.source=="string"){if(Tt(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 Pt(),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=Oe.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 a={...t,frame:n,format:s},c=await this.readBinary(xt(a));return Fi(a,c)}catch(a){o=a;}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(Ft(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 Me(e,t,r,n,i,o){return n<0||i<0||n>=t||i>=r?o:e[i*t+n]??o}function nc(e,t,r,n,i,o){return Me(e,t,r,Math.round(n),Math.round(i),o)}function Ti(e,t,r,n,i,o){let s=Math.floor(n),a=Math.floor(i),c=s+1,u=a+1,f=n-s,l=i-a,m=Me(e,t,r,s,a,Number.NaN),d=Me(e,t,r,c,a,Number.NaN),p=Me(e,t,r,s,u,Number.NaN),h=Me(e,t,r,c,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[S,w]of y)Number.isFinite(S)&&(b+=S*w,g+=w);return g===0?o:b/g}function Ei(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,a=-0.5*e+.5*r;return ((o*i+s)*i+a)*i+t}function ic(e,t,r,n,i,o){let s=Math.floor(n),a=Math.floor(i),c=n-s,u=i-a,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]=Me(e,t,r,s+d,a+l,Number.NaN);if([m[0],m[1],m[2],m[3]].some(d=>!Number.isFinite(d)))return Ti(e,t,r,n,i,o);f[l+1]=Ei(m[0],m[1],m[2],m[3],c);}return Ei(f[0],f[1],f[2],f[3],u)}function Tr(e,t,r,n,i,o,s){return o==="nearest"?nc(e,t,r,n,i,s):o==="bicubic"?ic(e,t,r,n,i,s):Ti(e,t,r,n,i,s)}function Pi(e,t,r,n={}){let i=n.blankValue??e.blankValue??Number.NaN,o=n.interpolation??"bilinear",s=r*r,a=new Float32Array(s*e.depth);for(let c=0;c<r;c++)for(let u=0;u<r;u++){let{lon:f,lat:l}=Ii(t,u,c,r),m=e.wcs.worldToPixel(f,l);for(let d=0;d<e.depth;d++){let p=e.planes[d],h=Tr(p,e.width,e.height,m.x,m.y,o,i);a[d*s+c*r+u]=h;}}return a}function Ri(e,t,r,n="mean"){let i=Math.max(1,Math.floor(t/2)),o=new Float32Array(i*i*r),s=t*t,a=i*i;for(let c=0;c<r;c++){let u=c*s,f=c*a;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 S=e[u+(p+g)*t+(d+y)];S!==void 0&&Number.isFinite(S)&&(h+=S,b++);}o[f+l*i+m]=b>0?h/b:Number.NaN;}}return o}function Ee(e){return e*Math.PI/180}function uc(e,t,r,n){let i=Ee(e),o=Ee(t),s=Ee(r),a=Ee(n),c=Math.sin(o)*Math.sin(a)+Math.cos(o)*Math.cos(a)*Math.cos(i-s),u=Math.max(-1,Math.min(1,c));return Math.acos(u)*180/Math.PI}function lc(e){return e instanceof ArrayBuffer?e:e.arrayBuffer()}async function fc(e){return e instanceof z?e:z.fromArrayBuffer(await lc(e))}function mc(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 dc(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 pc(e,t,r,n=64){if(t<=n)return e;let i=e,o=t;for(;o>n;)i=Ri(i,o,r,"mean"),o=Math.max(1,Math.floor(o/2));return i}async function hc(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 gc(e){return `<!doctype html>
|
|
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
6
|
<html lang="en">
|
|
7
7
|
<head>
|
|
8
8
|
<meta charset="utf-8" />
|
|
@@ -14,6 +14,6 @@ var ye=80,X=2880,Di=36,Lr=600,Dr=-2147483647,Or=-2147483646,we=1e4,Oi="1.0.1";va
|
|
|
14
14
|
<script>buildLandingPage({alScriptURL:'https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js'})</script>
|
|
15
15
|
</body>
|
|
16
16
|
</html>
|
|
17
|
-
`}function bc(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 yc(e,t){let r=mc(t),i=(await fc(e)).getHDU();if(!i?.data)throw new Error("No image HDU found in FITS input");bc(i.data);let o=i.data,s=yi(i.header),a=o.depth,c=[];for(let w=0;w<a;w++)c.push(dc(await o.getFrame(w)));let u=Si(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 w of p)h=Math.max(h,uc(d.lon,d.lat,w.lon,w.lat));let b=[],g=new Map,y=0;for(let w=m;w<=f;w++){let I=order2nside(w),A=Math.min(Math.PI,Ee(h)+max_pixrad(I)),x=ang2vec(Ee(90-d.lat),Ee(d.lon)),E=[];if(query_disc_inclusive_nest(I,x,A,k=>{E.push(k);}),E.length>r.maxTilesPerOrder)throw new Error(`Order ${w} would generate ${E.length} tiles, above maxTilesPerOrder=${r.maxTilesPerOrder}`);for(let k of E){let R={order:w,ipix:k,frame:r.frame},H=Pi({width:o.width,height:o.height,depth:a,planes:c,wcs:s,blankValue:r.blankValue},{...R},r.tileWidth,{interpolation:r.interpolation,blankValue:r.blankValue});for(let C of r.formats){if(a>1&&C!=="fits")continue;let v=Qe({...R,format:C},H,r.tileWidth,a);await t.output.writeBinary(xt({...R,format:C}),v);}if(y++,w===f&&r.includeMoc){let{theta:C,phi:v}=pix2ang_nest(I,k);b.push(v*180/Math.PI,90-C*180/Math.PI);}w===3&&r.includeAllsky&&g.set(k,pc(H,r.tileWidth,a,64));}}let S=bi({creatorDid:r.creatorDid,obsTitle:r.title,dataproductType:a>1?"cube":"image",frame:r.frame,order:f,tileWidth:r.tileWidth,formats:r.formats,extras:r.propertiesOverrides});if(S.set("hips_order_min",l),r.includeCompatibilityFields&&S.withCompatibilityFields(),a>1&&S.set("hips_cube_depth",a).set("hips_cube_firstframe",0).set("hips_allsky_restriction","non-fits allsky not generated for cube dataproduct"),await t.output.writeText("properties",S.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*a);v.fill(Number.NaN);for(let[P,M]of g.entries()){let K=Math.floor(P/E),T=P%E,N=4096;for(let U=0;U<a;U++){let q=U*N,le=U*C;for(let de=0;de<64;de++){let ki=K*64+de;for(let et=0;et<64;et++){let Li=T*64+et;v[le+ki*R+Li]=M[q+de*64+et]??Number.NaN;}}}}for(let P of r.formats){if(a>1&&P!=="fits")continue;let M=Qe({order:3,ipix:0,frame:r.frame,format:P},v,R,a);await t.output.writeBinary(Ft(P),M);}}if(r.includeMoc){let w=await hc(b,f);w.byteLength>0&&await t.output.writeBinary("Moc.fits",w);}return r.includeIndexHtml&&await t.output.writeText("index.html",gc(r.title)),{properties:S,maxOrder:f,minOrder:l,generatedTiles:y}}async function Pr(e,t){return yc(e,t)}var wc="https://alasky.cds.unistra.fr/hips-image-services/hips2fits",Sc="https://alaskybis.cds.unistra.fr/hips-image-services/hips2fits";function Ic(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 Ac(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 Rr(e,t,r={}){let n=r.timeoutMs??25e3,i=[r.endpoint??wc,r.endpointFallback??Sc],o;for(let s of i)try{let a=new URL(s);Ic(a,e,t);let c=await Ac(a,n);if(!c.ok)throw new Error(`hips2fits request failed (${c.status} ${c.statusText})`);return await c.arrayBuffer()}catch(a){o=a;}throw new Error(`hips2fits unavailable: ${String(o)}`)}function Pc(e){return e==="galactic"?"G":e==="ecliptic"?"E":"C"}function Ui(e,t){return e<0?t- -e%t:e%t}function Bi(e,t,r){return e<t?t:e>r?r:e}function Rc(e,t,r,n){let i=(90-n)*Math.PI/180,o=Ui(r*Math.PI/180,2*Math.PI),s=Math.cos(i),{t:a,u:c}=za2tu(s,o),u=Math.PI/4,f=a/u,l=c/u;f=Ui(f,8),f-=4,l+=5;let m=Bi((l+f)/2,0,5),d=Math.floor(m),p=Bi((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,S=m-d,w=p-h,I=order2nside(e),A=I*S,x=I*w,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 Cc(e){if(e.wcs)return wi(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 Et({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 Uc(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=vc(i.data);return Qe({order:t.order,ipix:t.ipix,frame:n,format:"fits"},o,i.width,i.depth).slice().buffer}function Bc(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 Nc(){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 vc(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 kc(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 Lc(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),a=nside2npix(s),c=new Float32Array(a);c.fill(Number.NaN);for(let l=0;l<a;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;c[b]=h>0?p/h:Number.NaN;}catch{continue}let u=Bc(c),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:a},{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:a-1},{key:"COORDSYS",value:Pc(i)}],data:u};return {fits:ne([Nc(),f]),map:{order:n,nside:s,ordering:o,values:c}}}async function Dc(e,t,r,n,i,o,s,a){let c=Rc(n,i,t,r),u=c.ipix,f=a.get(u);if(!f){let l=await e.readTile({order:n,ipix:u,frame:o});f=kc(l.data),a.set(u,f);}return Tr(f,i,i,c.x,c.y,s,Number.NaN)}async function Ni(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=Cc(t),a=new Float32Array(t.width*t.height),c=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);a[m*t.width+d]=await Dc(e,p.lon,p.lat,i,o,n,u,c);}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:W(a,-32),additionalCards:f});return ne([l])}async function Cr(e,t={}){let r=e instanceof me?e:new me(e),n=t.backend??"local",i;if(t.tile)i=await Uc(r,t.tile);else if(t.map)i=(await Lc(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 Rr(t.cutout?.hipsId??t.hipsId,o,t);}else if(n==="auto")try{i=await Ni(r,o);}catch(s){let a=t.cutout?.hipsId??t.hipsId;if(!a)throw s;i=await Rr(a,o,t);}else i=await Ni(r,o);}return t.output&&await t.output.writeBinary("output.fits",new Uint8Array(i)),i}function Oc(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 Mc(e,t){if(e instanceof Z)return e;let r=e instanceof ArrayBuffer?e:await e.arrayBuffer();return Z.fromArrayBuffer(r,{...t,decodeImageData:true})}async function Xc(e,t){let{imageIndex:r=0,xisfReadOptions:n,...i}=t,o=await Mc(e,n),s=o.unit.images[r];if(!s)throw new j(`XISF imageIndex ${r} is out of range (images=${o.unit.images.length})`);if(s.sampleFormat==="Complex32"||s.sampleFormat==="Complex64")throw new j("Complex XISF images cannot be converted to HiPS image/cube");if(!s.data)throw new j("Selected XISF image has no decoded data");let a={metadata:o.unit.metadata.map(f=>({...f})),images:[Oc(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}},c=await re.toMonolithic(a),u=await pr(c,{strictValidation:n?.strictValidation,includeXisfMetaExtension:false});return Pr(u,i)}async function _c(e,t={}){let{distributed:r,writeOptions:n,conversionOptions:i,...o}=t,s=await Cr(e,o);return hr(s,{...i??{},distributed:r,writeOptions:n})}function vr(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function _e(e){return e.replaceAll("\\","/").replace(/^\/+/u,"")}async function Xe(){let[e,t]=await Promise.all([import('fs/promises'),import('path')]);return {fs:e,path:t}}var Ur=class{constructor(t){this.root=t;}async absolute(t){let{path:r}=await Xe();return r.join(this.root,_e(t))}async writeBinary(t,r){let{fs:n,path:i}=await Xe(),o=await this.absolute(t);await n.mkdir(i.dirname(o),{recursive:true}),await n.writeFile(o,vr(r));}async writeText(t,r){let{fs:n,path:i}=await Xe(),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 Xe(),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 Xe(),n=await this.absolute(t);return r.readFile(n,"utf8")}async exists(t){let{fs:r}=await Xe();try{return await r.access(await this.absolute(t)),!0}catch{return false}}},Br=class{entries=new Map;async writeBinary(t,r){this.entries.set(_e(t),vr(r));}async writeText(t,r){this.entries.set(_e(t),new TextEncoder().encode(r));}async readBinary(t){let r=this.entries.get(_e(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(_e(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 $c(){return typeof navigator<"u"&&!!navigator.storage?.getDirectory}var Nr=class{constructor(t="fitsjs-hips"){this.baseDir=t;}rootHandlePromise;async rootHandle(){if(!$c())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=_e(t).split("/").filter(Boolean);if(n.length===0)throw new Error("Path must not be empty");let i=n.pop(),o=await this.rootHandle();for(let s of n)o=await o.getDirectoryHandle(s,{create:r});return {dir:o,filename:i}}async writeBinary(t,r){let{dir:n,filename:i}=await this.walk(t,true),s=await(await n.getFileHandle(i,{create:true})).createWritable();await s.write(vr(r)),await s.close();}async writeText(t,r){let{dir:n,filename:i}=await this.walk(t,true),s=await(await n.getFileHandle(i,{create:true})).createWritable();await s.write(r),await s.close();}async readBinary(t){let{dir:r,filename:n}=await this.walk(t,false),o=await(await r.getFileHandle(n)).getFile();return new Uint8Array(await o.arrayBuffer())}async readText(t){let r=await this.readBinary(t);return new TextDecoder().decode(r)}async exists(t){try{return await this.readBinary(t),!0}catch{return false}}};function kr(e){return /^https?:\/\//iu.test(e)}async function Vc(e){let t=[],r=await import('fs/promises'),n=await import('path'),i=async o=>{let s=await r.readdir(o,{withFileTypes:true});for(let a of s){let c=n.join(o,a.name),u=n.relative(e,c).replaceAll("\\","/");if(a.isDirectory()){await i(c);continue}u==="properties"||u==="Moc.fits"||u==="index.html"||/^Norder\d+\/Allsky\.(fits|png|jpg)$/iu.test(u)||u.startsWith("Norder")&&(Fr(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 Wc(e,t){let r=[],n=await import('fs/promises'),i=await import('path'),o=t.get("hips_order"),s=o!==void 0?Number(o):void 0,a=t.get("dataproduct_type"),c=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&&c.size>0&&!c.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=Fr(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}),c.size>0&&!c.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}),a==="cube"&&g.spectralOrder===void 0&&r.push({level:"warning",code:"CUBE_TILE_PATTERN_EXPECTED",message:"Cube dataproduct expects spectral tile naming pattern",path:h}),a!=="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 zc(e){let t=new me(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"&&!kr(e))try{let s=await import('fs/promises'),a=await import('path');await s.access(a.join(e,"Moc.fits")),o=!0;}catch{o=!1;}else if(typeof e=="string"&&kr(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"&&!kr(e))try{let n=await new me(e).getProperties();r.push(...await Wc(e,n));}catch{r.push(...await Vc(e));}return {ok:r.every(n=>n.level!=="error"),issues:r}}
|
|
18
|
-
export{X as BLOCK_LENGTH,
|
|
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
|
|
19
19
|
//# sourceMappingURL=index.js.map
|