@graphty/cytoscape-extensions 0.0.29 → 0.0.30

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.
@@ -1,4 +1,4 @@
1
- var graphtyCytoscape=(function(){"use strict";var bu=typeof document<"u"&&document.currentScript&&document.currentScript.src;function vu(n){return bu?import(new URL("cdn/"+n,bu).href):Promise.reject(new Error("graphty: the script-tag bundle loads the file formats from dist/cdn/ next to itself, but it was not loaded by a <script src> tag, so it cannot tell where that is. Load it with <script src>, or use the ES module build: <script type='module'> importing https://cdn.jsdelivr.net/npm/@graphty/cytoscape-extensions/dist/cdn/cytoscape-extensions.js"))}const x=4294967295,Te=4294967294,Mr=1,Au=Symbol.for("@graphty/graph-format/snapshot"),ft=256,Eu=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,zn=1,_u=0,la="graphty-snapshot",ua=[71,83,78,80],da=16909060,C0=Object.freeze({});class P extends Error{constructor(e,t,r){super(t),this.name="GraphFormatError",this.code=e,this.details=r===void 0?C0:Object.freeze({...r})}}const Ur=new WeakMap;function it(n){Ur.set(n,(Ur.get(n)??0)+1)}function Gn(n){Ur.set(n,Math.max(Ur.get(n)??0,1)+1)}function N0(n){return Ur.get(n)??0}function Fr(n){return(Ur.get(n)??0)>1}const T0=32;let Iu=null,ku=null;function Su(){return Iu??=new TextDecoder("utf-8",{ignoreBOM:!0}),Iu}function O0(){return ku??=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),ku}function $0(n){let e=0;const t=n.length;for(let r=0;r<t;r++){const o=n.charCodeAt(r);if(o<128)e+=1;else if(o<2048)e+=2;else if(o>=55296&&o<=56319&&r+1<t){const s=n.charCodeAt(r+1);s>=56320&&s<=57343?(e+=4,r++):e+=3}else e+=3}return e}function R0(n,e,t){let r=t;const o=n.length;for(let s=0;s<o;s++){let i=n.charCodeAt(s);if(i<128){e[r++]=i;continue}if(i<2048){e[r++]=192|i>>6,e[r++]=128|i&63;continue}if(i>=55296&&i<=57343){const a=D0(n,s,i);if(a>=0){s++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63;continue}i=65533}e[r++]=224|i>>12,e[r++]=128|i>>6&63,e[r++]=128|i&63}return r}function D0(n,e,t){if(t>56319||e+1>=n.length)return-1;const r=n.charCodeAt(e+1);return r<56320||r>57343?-1:65536+(t-55296<<10)+(r-56320)}const L0=13;function Ro(n){return n.length<L0?n:` ${n}`.slice(1)}function Pu(n){const e=n.length;for(let t=0;t<e;t++){const r=n.charCodeAt(t);if(r<55296||r>57343)continue;if(r>56319||t+1>=e)return!0;const o=n.charCodeAt(t+1);if(o<56320||o>57343)return!0;t++}return!1}function xu(n,e,t){const r=t-e;if(r===0)return"";if(r<=T0){let o="",s=e;for(;s<t;s++){const i=n[s];if(i>=128)break;o+=String.fromCharCode(i)}if(s===t)return o}return Su().decode(n.subarray(e,t))}function M0(n,e,t){for(let r=e;r<t;r++)if(n[r]>=128)return!1;return!0}function fa(n,e,t,r){const o=new Array(r-t);if(r<=t)return o;const s=e[t],i=e[r];if(M0(n,s,i)){const a=Su().decode(n.subarray(s,i));for(let c=t;c<r;c++)o[c-t]=a.substring(e[c]-s,e[c+1]-s);return o}for(let a=t;a<r;a++)o[a-t]=xu(n,e[a],e[a+1]);return o}function U0(n,e,t){let r=!0;for(let o=e;o<t;o++)if(n[o]>=128){r=!1;break}if(r)return!0;try{return O0().decode(n.subarray(e,t)),!0}catch{return!1}}function Do(n,e){const t=new Uint32Array(e+1);let r=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(r+=$0(a)),t[i+1]=r}const o=new Uint8Array(r);let s=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(s=R0(a,o,s))}return{offsets:t,utf8:o}}function ha(n,e,t,r){if(n.length!==t+1)throw new P("E_BAD_SERIALIZATION",`${r}: expected ${t+1} offsets, found ${n.length}`,{ref:r,reason:"offsets length",expected:t+1,found:n.length});let o=n[0];for(let s=1;s<=t;s++){const i=n[s];if(i<o)throw new P("E_BAD_SERIALIZATION",`${r}: offsets decrease at row ${s-1}`,{ref:r,reason:"offsets not monotonic",row:s-1});o=i}if(o>e.length)throw new P("E_BAD_SERIALIZATION",`${r}: offsets end at ${o} but the byte store has ${e.length} bytes`,{ref:r,reason:"offsets exceed utf8",end:o,byteLength:e.length})}class Wn{constructor(e,t,r){this.length=e,this.source=t,this.cache=null,this.encodedArrays=r}static fromStrings(e,t=e.length){return new Wn(t,e,null)}static fromEncoded(e,t){return new Wn(Math.max(0,e.length-1),null,{offsets:e,utf8:t})}get encoded(){return this.encodedArrays!==null}get decoded(){return this.source!==null}get detached(){return this.source===null&&this.length>0&&this.encodedArrays!==null&&this.encodedArrays.offsets.length===0}get offsets(){return this.ensureEncoded().offsets}get utf8(){return this.ensureEncoded().utf8}at(e){if(!(e>=0&&e<this.length)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`row ${e} out of range (length ${this.length})`,{index:e,size:this.length});if(this.source!==null)return this.source[e];this.cache??=new Array(this.length);const t=this.cache[e];if(t!==void 0)return t;const{offsets:r,utf8:o}=this.ensureEncoded(),s=xu(o,r[e],r[e+1]);return this.cache[e]=s,s}slice(e=0,t=this.length){const[r,o]=Cu(e,t,this.length),{source:s}=this;if(s!==null){const c=new Array(o-r);for(let l=r;l<o;l++)c[l-r]=s[l];return c}const{offsets:i,utf8:a}=this.ensureEncoded();return fa(a,i,r,o)}decodeAll(){return this.slice(0,this.length)}materialiseDecoded(){this.source===null&&(this.source=this.decodeAll(),this.cache=null)}byteLength(){const e=this.encodedArrays;return e===null?0:e.offsets.byteLength+e.utf8.byteLength}firstMalformedRow(){const e=this.encodedArrays;if(this.source!==null||e===null)return-1;const{offsets:t,utf8:r}=e;for(let o=0;o<this.length;o++)if(!U0(r,t[o],t[o+1]))return o;return-1}ensureEncoded(){let e=this.encodedArrays;return e===null&&(e=Do(this.source,this.length),this.encodedArrays=e,it(e.offsets.buffer),it(e.utf8.buffer)),e}}function Cu(n,e,t){let r=Math.trunc(n),o=Math.trunc(e);return Number.isNaN(r)&&(r=0),Number.isNaN(o)&&(o=0),r=r<0?Math.max(t+r,0):Math.min(r,t),o=o<0?Math.max(t+o,0):Math.min(o,t),[r,Math.max(r,o)]}function F0(){try{const n=new ArrayBuffer(0,{maxByteLength:64});return!n.resizable||typeof n.resize!="function"?!1:(n.resize(64),n.byteLength===64&&n.maxByteLength===64)}catch{return!1}}const ga=F0(),wa=16,B0=64,Nu=1024*1024,z0=16,G0=256*1024*1024;function Lo(n,e){const t=n%e;return t===0?n:n+e-t}function Mo(n){return Lo(n,4)}function W0(n){return Math.ceil(n/4)}function hr(n,e=ft){return Lo(n,e)}function V0(n,e=ft){const t=[],r=[];let o=0,s=0;for(const i of n){if(i===0){t.push(null),r.push(null);continue}const a=hr(o,e);s+=a-o,t.push(a),o=a+i,r.push(o)}return{offsets:t,ends:r,byteLength:o,padding:s}}function j0(n){return n.byteOffset%4===0&&n.byteLength%4===0}function pa(n){const{buffer:e}=n;return e instanceof ArrayBuffer&&!e.resizable}function Ds(n){return n.byteOffset%4===0&&n.byteOffset+Mo(n.byteLength)<=n.buffer.byteLength}function q0(n){if(!Ds(n))throw new P("E_COLUMN_ALIGNMENT",`u8 array at byteOffset ${n.byteOffset} with byteLength ${n.byteLength} has no zero-copy padded u32 view`,{byteOffset:n.byteOffset,byteLength:n.byteLength,bufferByteLength:n.buffer.byteLength});return new Uint32Array(n.buffer,n.byteOffset,W0(n.byteLength))}function H0(n){const e=new Uint8Array(new ArrayBuffer(Mo(n.byteLength)),0,n.byteLength);return e.set(n),e}function K0(n){throw new P("E_UNSUPPORTED",`unsupported dtype ${String(n)}`,{dtype:n})}function Y0(n,e){return Lo(Math.max(e,n*2,wa),wa)}function Tu(n,e){return Lo(n*e,B0)}function Ou(n,e=ga,t=Nu){if(!e)return new ArrayBuffer(n);const r=Math.max(n,t);try{return new ArrayBuffer(n,{maxByteLength:r})}catch(o){if(o instanceof RangeError&&r>n)return new ArrayBuffer(n,{maxByteLength:n});throw o}}function $u(n,e,t,r=ga){if(t<=n.length)return n;const o=e.BYTES_PER_ELEMENT,s=Tu(Y0(n.length,t),o),i=s/o,{buffer:a}=n;if(a.resizable&&n.byteOffset===0&&s<=a.maxByteLength)return a.resize(s),new e(a,0,i);const c=Math.max(a.maxByteLength*2,Math.min(a.maxByteLength*z0,G0),Nu),l=new e(Ou(s,r,c),0,i);return l.set(n),l}const ma=4294967295;function Fe(n){return Math.ceil(n/32)}function Ru(n){const e=n%32;return e===0?ma:ma>>>32-e}function ya(n,e){const t=Fe(e);t>0&&t<=n.length&&e%32!==0&&(n[t-1]&=Ru(e)),t<n.length&&n.fill(0,t)}function In(n,e=!1){const t=new Uint32Array(Fe(n));return e&&(t.fill(ma),ya(t,n)),t}function Le(n,e){return(n[e>>>5]>>>(e&31)&1)===1}function Ht(n,e){n[e>>>5]|=1<<(e&31)}function Kt(n,e){n[e>>>5]&=~(1<<(e&31))}function ba(n,e,t){t?Ht(n,e):Kt(n,e)}function Du(n){let e=n-(n>>>1&1431655765);return e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,Math.imul(e,16843009)>>>24}function gr(n,e){const t=Math.floor(e/32);let r=0;for(let o=0;o<t;o++)r+=Du(n[o]);return e%32!==0&&(r+=Du(n[t]&Ru(e))),r}function X0(n,e){const t=new Uint32Array(gr(n,e));let r=0;for(let o=0;o<e;o++)(n[o>>>5]>>>(o&31)&1)===1&&(t[r++]=o);return t}function Lu(n,e,t){const r=Math.max(0,t-e),o=In(r);if(r===0)return o;const s=e>>>5,i=e&31;if(i===0)o.set(n.subarray(s,s+o.length));else{const a=32-i;for(let c=0;c<o.length;c++){const l=s+c,u=l<n.length?n[l]>>>i:0,d=l+1<n.length?n[l+1]<<a:0;o[c]=u|d}}return ya(o,r),o}function wr(n,e){if(Pu(n))throw new P("E_COLUMN_TYPE","string value contains a lone surrogate",{...e,reason:"lone surrogate"})}function Q0(n){const e=new Map;for(let t=0;t<n.length;t++){const r=n[t];e.has(r)||e.set(r,t)}return e}class J0{constructor(e){if(this.values=[],this.codes=new Map,e!==void 0)for(const t of e)this.intern(t)}get size(){return this.values.length}intern(e){const t=this.codes.get(e);if(t!==void 0)return t;wr(e);const r=this.values.length,o=Ro(e);return this.values.push(o),this.codes.set(o,r),r}codeOf(e){const t=this.codes.get(e);return t===void 0?x:t}has(e){return this.codes.has(e)}}const Z0=["bool","i32","f64","string","json"],ey=/^-?(0|[1-9]\d*)$/,ty=/^[+-]?((0|[1-9]\d*)(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/,Mu=-2147483648,Uu=2147483647;function pr(n){return Z0.indexOf(n)}function Fu(n,e){return n===null?e:e===null?n:pr(e)>pr(n)?e:n}function ny(n){if(n==="true"||n==="false")return"bool";if(ey.test(n)){const e=Number(n);return e>=Mu&&e<=Uu?"i32":Number.isFinite(e)?"f64":"string"}return ty.test(n)&&Number.isFinite(Number(n))?"f64":"string"}function Ls(n){if(n==null)return null;switch(typeof n){case"boolean":return"bool";case"number":return Number.isInteger(n)&&n>=Mu&&n<=Uu?"i32":"f64";case"string":return"string";case"object":return"json";default:throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a column`,{reason:"unsupported value type",found:typeof n})}}function Br(n,e){switch(e){case"bool":if(typeof n=="boolean")return n;break;case"i32":case"f64":if(typeof n=="number")return n;if(typeof n=="boolean")return n?1:0;break;case"string":if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);break;case"json":return n;default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a ${e} column`,{dtype:e,found:typeof n})}function Bu(n){let e=null;for(const t of n)if(e=Fu(e,Ls(t)),e==="json")break;return e}class zu{constructor(){this.current=null}get dtype(){return this.current}observeValue(e){return this.apply(Ls(e))}observeText(e){return this.apply(ny(e))}widenTo(e){return this.apply(e)}apply(e){const t=Fu(this.current,e);return t===this.current?!1:(this.current=t,!0)}}const Gu=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),ry=new Set(["f32","f64","i32","u32","u8"]),Wu=16,Vu=256,oy=-2147483648,sy=2147483647,iy=4294967295,ay=255,cy=new TextDecoder,Ms=new WeakMap;function mr(n){return new Uint8Array(new ArrayBuffer(Mo(n)),0,n)}function ly(n){switch(n){case"f32":case"i32":case"u32":case"dict":return"direct";case"u8":case"bool":return"packed";case"f64":return"convert";case"string":case"list":case"json":return"none";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function uy(n){return n!=="list"&&Gu.has(n)}function kn(n){if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function cn(n,e,t=0){if(!(n===null||typeof n=="boolean"||typeof n=="number")){if(typeof n=="string"){wr(n,{field:e});return}if(t>Vu)throw new P("E_COLUMN_TYPE",`${e} is nested deeper than ${Vu} levels`,{field:e,reason:"nesting"});if(Array.isArray(n)){for(const r of n)cn(r,e,t+1);return}if(kn(n)){for(const r of Object.keys(n))cn(n[r],e,t+1);return}throw new P("E_COLUMN_TYPE",`${e} is not a JSON value`,{field:e,found:n===void 0?"undefined":typeof n})}}function Vn(n){if(Array.isArray(n))return n.map(e=>Vn(e));if(kn(n)){const e={};for(const t of Object.keys(n))t==="__proto__"?Object.defineProperty(e,t,{value:Vn(n[t]),enumerable:!0,writable:!0,configurable:!0}):e[t]=Vn(n[t]);return e}return n}function yr(n,e){switch(n){case"f32":case"f64":return!0;case"i32":return Number.isInteger(e)&&e>=oy&&e<=sy;case"u32":return Number.isInteger(e)&&e>=0&&e<=iy;case"u8":return Number.isInteger(e)&&e>=0&&e<=ay;default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function ju(n,e,t){if(typeof t=="number")return yr(n,t)?t:null;if(e>1&&Array.isArray(t)&&t.length===e){const r=t[0];if(typeof r!="number"||!yr(n,r))return null;for(let o=1;o<e;o++)if(!Object.is(t[o],r))return null;return r}return null}function Qe(n,e,t){return new P("E_COLUMN_TYPE",e,{...t,field:n})}function dy(n){if(n===void 0)return null;if(!kn(n))throw Qe("origin","origin must be a plain object");const e=t=>{const r=n[t];if(r==null)return null;if(typeof r!="string")throw Qe("origin",`origin.${t} must be a string or null`,{found:typeof r});return r};return{format:e("format"),id:e("id"),title:e("title"),type:e("type"),namespace:e("namespace")}}function qu(n,e,t){if(e===void 0)return 1;if(!Number.isInteger(e)||e<1||e>Wu)throw Qe(n,`${n} must be an integer in 1..${Wu}, found ${e}`,{found:e});if(e>1&&!ry.has(t))throw Qe(n,`${n} > 1 is only allowed for f32 / f64 / i32 / u32 / u8, not ${t}`,{found:e,dtype:t});return e}function fy(n,e,t,r,o,s){switch(n){case"f32":case"f64":case"i32":case"u32":case"u8":{if(t!==void 0){if(typeof t!="number")throw Qe("fill",`fill of a ${n} column must be a number`,{found:typeof t});return t}return s!==null?x:ju(n,e,r)??0}case"bool":{if(t!==void 0){if(typeof t!="boolean")throw Qe("fill","fill of a bool column must be a boolean",{found:typeof t});return t}return typeof r=="boolean"?r:!1}case"dict":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a dict column must be a string",{found:typeof t});return t}return typeof r=="string"&&(o===null||o.includes(r))?r:o!==null&&o.length>0&&typeof o[0]=="string"?o[0]:""}case"string":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a string column must be a string",{found:typeof t});return t}return""}case"list":case"json":{if(t!==void 0&&t!=="")throw Qe("fill",`a ${n} column takes no fill value`,{found:t});return""}default:{const i=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}function ht(n,e,t){const{dtype:r}=t;if(r===void 0||!Gu.has(r))throw Qe("dtype",`column "${n}" has no valid dtype`,{name:n,found:r});const o=qu("components",t.components,r);let s=null,i=null;if(r==="list"){const{itemDtype:h}=t;if(h===void 0||!uy(h))throw Qe("itemDtype",`list column "${n}" needs a scalar itemDtype`,{name:n,found:h});s=h,i=qu("itemComponents",t.itemComponents,h)}else if(t.itemDtype!==void 0||t.itemComponents!==void 0)throw Qe("itemDtype",`itemDtype / itemComponents are only allowed on list columns, not ${r}`,{name:n,dtype:r});const a=t.refersTo??null;if(a!==null){if(a!=="node"&&a!=="edge")throw Qe("refersTo",'refersTo must be "node" or "edge"',{found:a});if(!(r==="u32"&&o===1||r==="list"&&s==="u32"&&i===1))throw Qe("refersTo",`refersTo requires a u32 column or a list of u32, not ${r}`,{name:n,dtype:r})}const c=t.default;c!==void 0&&cn(c,"default");let l=null;if(t.options!==void 0){if(!Array.isArray(t.options))throw Qe("options","options must be an array");if(cn(t.options,"options"),r==="dict"){for(const h of t.options)if(typeof h!="string")throw Qe("options","options of a dict column must be strings",{found:typeof h})}l=Object.freeze(Vn([...t.options]))}const u=t.extra??{};if(!kn(u))throw Qe("extra","extra must be a plain object");cn(u,"extra");const d=t.role??null;if(d!==null&&typeof d!="string")throw Qe("role","role must be a string",{found:typeof d});const f=fy(r,o,t.fill,c,l,a);return Object.freeze({name:n,domain:e,dtype:r,components:o,itemDtype:s,itemComponents:i,nullable:t.nullable??!0,mutable:t.mutable??!1,role:d,refersTo:a,unique:t.unique??!1,default:Vn(c),fill:f,options:l,origin:dy(t.origin),dynamic:t.dynamic??!1,extra:Object.freeze(Vn({...u}))})}function Sn(n){return{name:n.name,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype??void 0,itemComponents:n.itemComponents??void 0,nullable:n.nullable,mutable:n.mutable,role:n.role??void 0,refersTo:n.refersTo??void 0,unique:n.unique,default:n.default,fill:n.fill,options:n.options??void 0,origin:n.origin??void 0,dynamic:n.dynamic,extra:n.extra}}class br{constructor(e,t,r,o,s){this.versionValue=0,this.defaultCache=null,this.dtype=e,this.meta=t,this.length=r,this.gpu=ly(e),this.validityWords=o,this.nullCountValue=s,this.defaultValue=Vn(t.default)}get validity(){return this.validityWords}get nullCount(){return this.nullCountValue}get version(){return this.versionValue}get paddedByteLength(){return this.byteLength}get validityByteLength(){return this.validityWords===null?0:this.validityWords.byteLength}get detached(){if(this.length===0)return!1;const e=this.validityWords;return e!==null&&e.length===0||this.storageDetached()}isSet(e){if(!(e>=0&&e<this.length))return!1;const t=this.validityWords;if(t===null)return!0;if(t.length===0)throw this.detachedError();return Le(t,e)}value(e){if(this.assertAttached(),!(Number.isInteger(e)&&e>=0&&e<this.length))throw new P("E_INDEX_RANGE",`row ${e} is out of range for a column of ${this.length} rows`,{row:e,length:this.length,column:this.meta.name});const t=this.validityWords;if(t!==null&&!Le(t,e)){const{defaultValue:r}=this;return r===void 0?void 0:Vn(r)}return this.readValue(e)}materializeDefault(){if(this.assertAttached(),this.meta.default===void 0)throw new P("E_NO_DEFAULT",`column "${this.meta.name}" declares no default`,{column:this.meta.name});return this.nullCountValue===0||this.fillIsDefault()?this.self():(this.defaultCache??=this.withDefaults(),this.defaultCache)}paddedU32View(){throw new P("E_GPU_INELIGIBLE",`a ${this.dtype} column has no u32 view`,{column:this.meta.name,dtype:this.dtype})}markDirty(){this.assertMutable("markDirty"),this.assertAttached(),this.versionValue++,this.defaultCache=null,Ms.delete(this);const e=this.validityWords;e!==null&&(this.nullCountValue=this.length-gr(e,this.length))}mutableValidity(){return this.assertMutable("mutableValidity"),this.validityWords}setAll(){this.assertMutable("setAll"),this.validityWords=null,this.nullCountValue=0,this.versionValue++,this.defaultCache=null}assertAttached(){if(this.detached)throw this.detachedError()}detachedError(){return new P("E_DETACHED",`column "${this.meta.name}" was transferred away`,{column:this.meta.name})}assertMutable(e){if(!this.meta.mutable)throw new P("E_COLUMN_IMMUTABLE",`${e}() on immutable column "${this.meta.name}"`,{column:this.meta.name,operation:e})}checkRange(e,t){if(this.assertAttached(),!(Number.isInteger(e)&&Number.isInteger(t)&&e>=0&&e<=t&&t<=this.length))throw new P("E_INDEX_RANGE",`row range [${e}, ${t}) is invalid for ${this.length} rows`,{start:e,end:t,length:this.length,column:this.meta.name})}sliceValidity(e,t){const r=this.validityWords;if(r===null)return{validity:null,nullCount:0};const o=t-e,s=e%32===0?zr(r.subarray(e>>>5,(e>>>5)+Fe(o))):Lu(r,e,t);return{validity:s,nullCount:o-gr(s,o)}}cloneValidity(){return this.assertAttached(),this.validityWords===null?null:this.validityWords.slice()}}function zr(n){return Gn(n.buffer),n}class Uo extends br{constructor(e,t,r,o,s,i){super(e,t,r,s,i),this.data=o}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}storageDetached(){return this.data.length===0&&this.length*this.meta.components>0}slice(e,t){this.checkRange(e,t);const{components:r}=this.meta,o=this.sliceData(e*r,t*r),{validity:s,nullCount:i}=this.sliceValidity(e,t);return this.wrap(this.meta,t-e,o,s,i)}clone(){return this.assertAttached(),this.wrap(this.meta,this.length,this.copyData(),this.cloneValidity(),this.nullCountValue)}readValue(e){const{components:t}=this.meta;return t===1?this.data[e]:this.data.subarray(e*t,(e+1)*t)}fillIsDefault(){const{fill:e,default:t,components:r}=this.meta;return typeof e!="number"?!1:ju(this.dtype,r,t)===e}withDefaults(){const{components:e,default:t}=this.meta,r=this.copyData(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||Hu(this.dtype,r,s*e,e,t,this.meta.name,s);return this.wrap(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}sliceData(e,t){return zr(this.data.subarray(e,t))}copyData(){return this.data.slice()}}function Hu(n,e,t,r,o,s,i){if(typeof o=="number"){Ku(n,o,s,i),r===1?e[t]=o:e.fill(o,t,t+r);return}if(r===1||!Yu(o,r))throw new P("E_COLUMN_TYPE",`row ${i} of ${n} column "${s}" is not ${r} number(s)`,{column:s,row:i,components:r,found:typeof o});for(let a=0;a<r;a++)Ku(n,o[a],s,i);for(let a=0;a<r;a++)e[t+a]=o[a]}function Ku(n,e,t,r){if(!yr(n,e))throw new P("E_COLUMN_TYPE",`row ${r} of ${n} column "${t}": ${e} is not representable`,{column:t,row:r,value:e})}function Yu(n,e){if(typeof n!="object"||n===null)return!1;const t=n;if(t.length!==e)return!1;for(let r=0;r<e;r++)if(typeof t[r]!="number")return!1;return!0}class va extends Uo{constructor(e,t,r,o,s){super("f32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new va(e,t,r,o,s)}}class Aa extends Uo{constructor(e,t,r,o,s){super("f64",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Aa(e,t,r,o,s)}}class Ea extends Uo{constructor(e,t,r,o,s){super("i32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Ea(e,t,r,o,s)}}class _a extends Uo{constructor(e,t,r,o,s){super("u32",e,t,r,o,s)}paddedU32View(){return this.data}self(){return this}wrap(e,t,r,o,s){return new _a(e,t,r,o,s)}}class Ia extends Uo{constructor(e,t,r,o,s){super("u8",e,t,r,o,s)}get paddedByteLength(){return Mo(this.data.byteLength)+this.validityByteLength}paddedU32View(){return q0(this.data)}self(){return this}wrap(e,t,r,o,s){return new Ia(e,t,r,o,s)}sliceData(e,t){if(e%4===0)return zr(this.data.subarray(e,t));const r=mr(t-e);return r.set(this.data.subarray(e,t)),r}copyData(){const e=mr(this.data.length);return e.set(this.data),e}}class Fo extends br{constructor(e,t,r,o,s){super("bool",e,t,o,s),this.data=r}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}paddedU32View(){return this.assertAttached(),this.data}slice(e,t){this.checkRange(e,t);const r=t-e,o=e%32===0?zr(this.data.subarray(e>>>5,(e>>>5)+Fe(r))):Lu(this.data,e,t),{validity:s,nullCount:i}=this.sliceValidity(e,t);return new Fo(this.meta,r,o,s,i)}clone(){return this.assertAttached(),new Fo(this.meta,this.length,this.data.slice(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.data.length===0}self(){return this}readValue(e){return Le(this.data,e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="boolean")throw new P("E_COLUMN_TYPE",`default of bool column "${t}" is not a boolean`,{column:t,field:"default"});const r=this.data.slice(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(e?Ht(r,s):Kt(r,s));return new Fo(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}}class Bo extends br{constructor(e,t,r,o,s,i){super("dict",e,t,s,i),this.codeMap=null,this.codes=r,this.dictionary=o}get byteLength(){return this.codes.byteLength+this.validityByteLength}codeOf(e){this.codeMap??=Q0(this.dictionary);const t=this.codeMap.get(e);return t===void 0?x:t}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.codes}paddedU32View(){return this.assertAttached(),this.codes}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Bo(this.meta,t-e,zr(this.codes.subarray(e,t)),this.dictionary,r,o)}storageDetached(){return this.codes.length===0}clone(){return this.assertAttached(),new Bo(this.meta,this.length,this.codes.slice(),[...this.dictionary],this.cloneValidity(),this.nullCountValue)}self(){return this}readValue(e){return this.dictionary[this.codes[e]]}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of dict column "${t}" is not a string`,{column:t,field:"default"});let r=this.dictionary,o=this.codeOf(e);o===x&&(o=r.length,r=[...r,e]);const s=this.codes.slice(),i=this.validityWords;if(i!==null)for(let a=0;a<this.length;a++)Le(i,a)||(s[a]=o);return new Bo(this.meta,this.length,s,r,this.cloneValidity(),this.nullCountValue)}}function hy(n){const e=Do(n,n.length),t=mr(e.utf8.length);return t.set(e.utf8),{offsets:e.offsets,utf8:t}}class ln extends br{constructor(e,t,r,o,s,i,a){super("string",e,t,i,a),this.offsetsStore=r,this.utf8Store=o,this.strings=s}get offsets(){return this.store(),this.offsetsStore}get utf8(){return this.store(),this.utf8Store}get byteLength(){return this.store(),this.offsetsStore.byteLength+this.utf8Store.byteLength+this.validityByteLength}valueAt(e){const t=this.strings?.[e];if(t!==void 0)return t;this.assertAttached(),this.store();const r=this.offsetsStore,o=this.utf8Store,s=cy.decode(o.subarray(r[e],r[e+1]));return this.strings??=new Array(this.length),this.strings[e]=s,s}decodeAll(){const e=new Array(this.length);for(let t=0;t<this.length;t++)e[t]=this.valueAt(t);return e}slice(e,t){this.checkRange(e,t);const r=t-e,{validity:o,nullCount:s}=this.sliceValidity(e,t),i=this.strings===null?null:this.strings.slice(e,t);if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,r,null,null,i,o,s);const a=this.offsetsStore[e],c=new Uint32Array(r+1);for(let u=0;u<=r;u++)c[u]=this.offsetsStore[e+u]-a;const l=zr(this.utf8Store.subarray(a,this.offsetsStore[t]));return new ln(this.meta,r,c,l,i,o,s)}clone(){this.assertAttached();const e=this.strings===null?null:[...this.strings];if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,this.length,null,null,e,this.cloneValidity(),this.nullCountValue);const t=mr(this.utf8Store.length);return t.set(this.utf8Store),new ln(this.meta,this.length,this.offsetsStore.slice(),t,e,this.cloneValidity(),this.nullCountValue)}hasStore(){return this.offsetsStore!==null}decodedCache(){return this.strings}self(){return this}storageDetached(){return this.offsetsStore!==null&&this.offsetsStore.length===0}readValue(e){return this.valueAt(e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of string column "${t}" is not a string`,{column:t,field:"default"});const r=this.decodeAll(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(r[s]=e);return new ln(this.meta,this.length,null,null,r,this.cloneValidity(),this.nullCountValue)}store(){if(this.offsetsStore!==null&&this.utf8Store!==null){this.assertAttached();return}const e=this.strings??[],t=new Array(this.length);for(let o=0;o<this.length;o++)t[o]=e[o]??"";const r=hy(t);this.offsetsStore=r.offsets,this.utf8Store=r.utf8,it(r.offsets.buffer),it(r.utf8.buffer)}}class zo extends br{constructor(e,t,r,o,s,i){super("list",e,t,s,i),this.offsets=r,this.child=o}get byteLength(){return this.offsets.byteLength+this.child.byteLength+this.validityByteLength}sliceOf(e){this.assertAttached();const t=this.offsets[e],r=this.offsets[e+1],o=new Array(r-t);for(let s=t;s<r;s++)o[s-t]=this.child.value(s);return o}slice(e,t){this.checkRange(e,t);const r=t-e,o=this.offsets[e],s=new Uint32Array(r+1);for(let c=0;c<=r;c++)s[c]=this.offsets[e+c]-o;const{validity:i,nullCount:a}=this.sliceValidity(e,t);return new zo(this.meta,r,s,this.child.slice(o,this.offsets[t]),i,a)}clone(){return this.assertAttached(),new zo(this.meta,this.length,this.offsets.slice(),this.child.clone(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.offsets.length===0||ka(this.child)}self(){return this}readValue(e){return this.sliceOf(e)}fillIsDefault(){return!1}withDefaults(){const{default:e,name:t}=this.meta;if(!Array.isArray(e))throw new P("E_COLUMN_TYPE",`default of list column "${t}" is not an array`,{column:t,field:"default"});const r=new Array(this.length),o=this.validityWords;for(let i=0;i<this.length;i++)r[i]=o!==null&&!Le(o,i)?e:this.sliceOf(i);const s=Qu(this.meta,r);return new zo(this.meta,this.length,s.offsets,s.child,this.cloneValidity(),this.nullCountValue)}}class Go extends br{constructor(e,t,r,o,s){super("json",e,t,o,s),this.values=r}get byteLength(){return this.validityByteLength}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Go(this.meta,t-e,this.values.slice(e,t),r,o)}clone(){return this.assertAttached(),new Go(this.meta,this.length,[...this.values],this.cloneValidity(),this.nullCountValue)}storageDetached(){return!1}self(){return this}readValue(e){return this.values[e]}fillIsDefault(){return!1}withDefaults(){const{default:e}=this.meta,t=[...this.values],r=this.validityWords;if(r!==null)for(let o=0;o<this.length;o++)Le(r,o)||(t[o]=e);return new Go(this.meta,this.length,t,this.cloneValidity(),this.nullCountValue)}}function gy(n){return n instanceof br}function ka(n){return n.detached}function un(n,e,t,r){return new P("E_COLUMN_LENGTH",`column "${n.name}": ${e} has length ${r}, expected ${t}`,{column:n.name,what:e,expected:t,found:r})}function dn(n,e){return new P("E_COLUMN_TYPE",`column "${n.name}": ${e}`,{column:n.name})}function Tt(n){const{meta:e,length:t}=n;if(!(Number.isInteger(t)&&t>=0))throw new P("E_COLUMN_LENGTH",`column "${e.name}": invalid row count ${t}`,{column:e.name,found:t});const{validity:r}=n;let o=null;if(r!==null){if(!e.nullable)throw dn(e,"a non-nullable column cannot carry a validity bitmap");if(!(r instanceof Uint32Array))throw dn(e,"validity must be a Uint32Array");if(r.length!==Fe(t))throw un(e,"validity",Fe(t),r.length);o=r}const s=o===null?0:t-gr(o,t),{dtype:i}=e;switch(i){case"f32":return new va(e,t,Wo(n,Float32Array),o,s);case"f64":return new Aa(e,t,Wo(n,Float64Array),o,s);case"i32":return new Ea(e,t,Wo(n,Int32Array),o,s);case"u32":return new _a(e,t,Wo(n,Uint32Array),o,s);case"u8":{const a=Wo(n,Uint8Array);if(!Ds(a))throw new P("E_COLUMN_ALIGNMENT",`column "${e.name}": no padded u32 view over the u8 data`,{column:e.name,byteOffset:a.byteOffset,byteLength:a.byteLength});return new Ia(e,t,a,o,s)}case"bool":{if(!(n.data instanceof Uint32Array))throw dn(e,"bool data must be packed Uint32Array words");if(n.data.length!==Fe(t))throw un(e,"data",Fe(t),n.data.length);return new Fo(e,t,n.data,o,s)}case"dict":{if(!(n.data instanceof Uint32Array))throw dn(e,"dict codes must be a Uint32Array");if(n.data.length!==t)throw un(e,"codes",t,n.data.length);if(n.dictionary===null)throw dn(e,"dict column needs a dictionary");return new Bo(e,t,n.data,n.dictionary,o,s)}case"string":{if(n.offsets===null||n.utf8===null){const{strings:a}=n;if(a?.length!==t)throw un(e,"strings",t,a===null?-1:a.length);for(let c=0;c<t;c++)if(typeof a[c]!="string")throw dn(e,`row ${c} is not a decoded string and no Utf8 store is present`);return new ln(e,t,null,null,a,o,s)}if(n.offsets.length!==t+1)throw un(e,"offsets",t+1,n.offsets.length);if(n.offsets[t]!==n.utf8.length)throw un(e,"utf8",n.offsets[t],n.utf8.length);return new ln(e,t,n.offsets,n.utf8,n.strings,o,s)}case"list":{if(n.offsets?.length!==t+1)throw un(e,"offsets",t+1,n.offsets===null?-1:n.offsets.length);const{child:a}=n;if(a===null||a.dtype==="list")throw dn(e,"list column needs a non-list child column");if(a.validity!==null||a.meta.nullable)throw dn(e,"list child must be non-nullable");if(a.dtype!==e.itemDtype||a.meta.components!==e.itemComponents)throw dn(e,`list child is ${a.dtype} x${a.meta.components}, declared ${String(e.itemDtype)} x${String(e.itemComponents)}`);if(n.offsets[t]!==a.length)throw un(e,"child",n.offsets[t],a.length);return new zo(e,t,n.offsets,a,o,s)}case"json":{if(n.values?.length!==t)throw un(e,"values",t,n.values===null?-1:n.values.length);return new Go(e,t,n.values,o,s)}default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}function Wo(n,e){const{meta:t,length:r}=n;if(!(n.data instanceof e))throw dn(t,`${t.dtype} data must be a ${e.name}`);const o=r*t.components;if(n.data.length!==o)throw un(t,"data",o,n.data.length);return n.data}function Us(n){const e={meta:n.meta,length:n.length,data:null,validity:n.validity,nullCount:n.nullCount,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null},{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return e.data=n.data,e;case"dict":return e.data=n.codes,e.dictionary=n.dictionary,e;case"string":return n instanceof ln?(e.strings=n.decodedCache(),n.hasStore()&&(e.offsets=n.offsets,e.utf8=n.utf8),e):(e.offsets=n.offsets,e.utf8=n.utf8,e);case"list":return e.offsets=n.offsets,e.child=n.child,e;case"json":return e.values=n.values,e;default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function Sa(n){const e=new Set,t=r=>{r!==null&&e.add(r.buffer)};switch(t(n.validity),n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":t(n.data);break;case"dict":t(n.codes);break;case"string":(!(n instanceof ln)||n.hasStore())&&(t(n.offsets),t(n.utf8));break;case"list":t(n.offsets);for(const r of Sa(n.child))e.add(r);break;case"json":break;default:{const r=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${r.dtype}`,{})}}return[...e]}function Xu(n,e){const t=n.meta;if(e.dtype!==t.dtype||e.components!==t.components||e.itemDtype!==t.itemDtype||e.itemComponents!==t.itemComponents)throw new P("E_COLUMN_TYPE",`column "${t.name}" is ${t.dtype} x${t.components}; a patch cannot change its dtype`,{column:t.name,field:"dtype"});if(e.fill!==t.fill)throw new P("E_COLUMN_TYPE",`the fill of existing column "${t.name}" cannot change`,{column:t.name,field:"fill"});const r=Us(n);if(!e.nullable&&n.validity!==null){if(n.nullCount>0)throw new P("E_COLUMN_TYPE",`column "${t.name}" has ${n.nullCount} unset rows and cannot become non-nullable`,{column:t.name,field:"nullable",nullCount:n.nullCount});r.validity=null}return r.meta=e,Tt(r)}function wy(n){Ms.delete(n)}function py(n){const{dtype:e}=n;switch(e){case"f32":case"i32":case"u32":case"bool":return n.data;case"u8":return n.paddedU32View();case"dict":return n.codes;case"f64":{let t=Ms.get(n);return t===void 0&&(t=new Float32Array(n.data),Ms.set(n,t)),t}case"string":case"list":case"json":throw new P("E_GPU_INELIGIBLE",`a ${e} column cannot be bound by the GPU`,{column:n.meta.name,dtype:e});default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function my(n,e,t){const r=typeof e=="string"?e:"",o=n.codeOf(r);return o===x?0:o}function Pa(n){const e=new J0(n.options===null?void 0:n.options);return typeof n.fill=="string"&&n.fill!==""&&e.intern(n.fill),e}function Gr(n,e,t){return{meta:n,length:e,data:null,validity:t,nullCount:t===null?0:e,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null}}function yy(n){if(n.itemDtype===null||n.itemComponents===null)throw new P("E_COLUMN_TYPE",`column "${n.name}" is not a list`,{column:n.name,field:"itemDtype"});return ht(`${n.name}.item`,n.domain,{dtype:n.itemDtype,components:n.itemComponents,nullable:!1,refersTo:n.refersTo??void 0})}function by(n,e){return n===void 0||n===null&&e!=="json"}function Qu(n,e){const t=new Uint32Array(e.length+1),r=[];for(let s=0;s<e.length;s++){for(const i of e[s])r.push(i);t[s+1]=r.length}const o=Vo(yy(n),r);return{offsets:t,child:o}}function Vo(n,e){const{length:t}=e,{dtype:r,components:o,fill:s,name:i}=n;let a=null,c=0;for(let d=0;d<t;d++)if(by(e[d],r)){if(!n.nullable)throw new P("E_COLUMN_TYPE",`row ${d} of non-nullable column "${i}" is unset`,{column:i,row:d});a??=In(t,!0),Kt(a,d),c++}const l=Gr(n,t,a);l.nullCount=c;const u=d=>a===null||Le(a,d);switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const d=Ju(r,t*o);s!==0&&d.fill(s);for(let f=0;f<t;f++){if(!u(f))continue;const h=e[f],g=typeof h=="boolean"?Number(h):h;Hu(r,d,f*o,o,g,i,f)}l.data=d;break}case"bool":{const d=In(t,s===!0);for(let f=0;f<t;f++){if(!u(f))continue;Br(e[f],"bool")===!0?Ht(d,f):Kt(d,f)}l.data=d;break}case"dict":{const d=Pa(n),f=new Uint32Array(t);a!==null&&f.fill(my(d,s));for(let h=0;h<t;h++){if(!u(h))continue;const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of dict column "${i}" is not a string`,{column:i,row:h});f[h]=d.intern(g)}l.data=f,l.dictionary=d.values;break}case"string":{const d=typeof s=="string"?s:"",f=new Array(t);for(let h=0;h<t;h++){if(!u(h)){f[h]=d;continue}const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of string column "${i}" is not a string`,{column:i,row:h});wr(g,{column:i,row:h}),f[h]=g}l.strings=f;break}case"list":{const d=new Array(t);for(let h=0;h<t;h++){if(!u(h)){d[h]=[];continue}const g=e[h];if(!Array.isArray(g))throw new P("E_COLUMN_TYPE",`row ${h} of list column "${i}" is not an array`,{column:i,row:h});d[h]=g}const f=Qu(n,d);l.offsets=f.offsets,l.child=f.child;break}case"json":{const d=new Array(t);for(let f=0;f<t;f++){if(!u(f)){d[f]=void 0;continue}cn(e[f],`row ${f}`),d[f]=e[f]}l.values=d;break}default:{const d=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${d}`,{dtype:d})}}return Tt(l)}function Ju(n,e){switch(n){case"f32":return new Float32Array(e);case"f64":return new Float64Array(e);case"i32":return new Int32Array(e);case"u32":return new Uint32Array(e);case"u8":return mr(e);default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function vy(n){let e=!1,t=!1;for(const r of n)r!=null&&(Array.isArray(r)?e=!0:t=!0);return e&&!t?{dtype:"list",itemDtype:Bu(Ay(n))??"json"}:{dtype:Bu(n)??"json",itemDtype:void 0}}function Ay(n){const e=[];for(const t of n)if(Array.isArray(t))for(const r of t)e.push(r);return e}function xa(n,e,t,r,o){if(r.length!==e)throw new P("E_COLUMN_LENGTH",`column "${t}": ${r.length} values for ${e} rows`,{column:t,expected:e,found:r.length});let s={nullable:!0,...o};if(s.dtype===void 0){const a=vy(r);s={...s,dtype:a.dtype},a.dtype==="list"&&s.itemDtype===void 0&&(s={...s,itemDtype:a.itemDtype})}const i=ht(t,n,s);return Vo(i,r)}function Zu(n){return n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":n instanceof Int32Array?"i32":n instanceof Uint32Array?"u32":"u8"}function Ey(n,e,t,r,o,s="copy"){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=ht(t,n,{nullable:!1,...o,dtype:a}),u=Gr(l,e,null),d=_y(t,a,e,l.components);if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});if(!pa(r)){const h=r.buffer instanceof ArrayBuffer?"resizable ArrayBuffer":"SharedArrayBuffer";throw new P("E_UNSUPPORTED",`column "${t}": a view over a ${h} cannot be adopted`,{column:t,reason:h})}let f=r;if(r instanceof Uint8Array&&!Ds(r)){if(s==="strict")throw new P("E_COLUMN_ALIGNMENT",`column "${t}": no zero-copy padded u32 view over the u8 array`,{column:t,byteOffset:r.byteOffset,byteLength:r.byteLength,bufferByteLength:r.buffer.byteLength});const h=mr(r.length);h.set(r),f=h}return u.data=f,a==="dict"&&(u.dictionary=Iy(l,r,e)),Tt(u)}function _y(n,e,t,r){switch(e){case"bool":return Fe(t);case"dict":return t;case"f32":case"f64":case"i32":case"u32":case"u8":return t*r;default:{const o=e;throw new P("E_COLUMN_TYPE",`column "${n}": a ${o} column cannot adopt a typed array`,{column:n,field:"dtype"})}}}function Iy(n,e,t){const{name:r}=n,o=Pa(n);for(let s=0;s<t;s++){const i=e[s];if(i>=o.size)throw new P("E_COLUMN_TYPE",`column "${r}": code ${i} at row ${s} is outside the ${o.size} declared options`,{column:r,row:s,code:i})}return o.values}function zt(n,e,t){if(e!==void 0){if(typeof e!="string"||!t.includes(e))throw new P("E_UNSUPPORTED",`option ${n} has an unsupported value ${ky(e)}`,{field:n,found:e,reason:"unsupported option"});return e}}function ky(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):`a ${typeof n}`}const Fs=["first","last","sum","min","max"],Sy=[...Fs,"mean","count","drop"];function Pn(n){if(typeof n=="number")return String(n);if(typeof n=="string"){const e=n.length>40?`${n.slice(0,37)}...`:n;return JSON.stringify(e)}return n===null?"null":typeof n=="bigint"?`${String(n)}n`:`a value of type ${typeof n}`}function jn(n){if(typeof n=="number"){if(!Number.isFinite(n))throw new P("E_INVALID_ID",`invalid node id ${String(n)}: not a finite number`,{id:n,reason:"non-finite"});return n===0?0:n}if(typeof n=="string"){if(Pu(n))throw new P("E_INVALID_ID",`invalid node id ${Pn(n)}: lone surrogate`,{id:n,reason:"lone surrogate"});return n}throw new P("E_INVALID_ID",`invalid node id: ${Pn(n)} is not a string or a number`,{reason:"unsupported type",type:typeof n})}const Bs=new WeakMap;function Py(n){const e=Bs.get(n);if(e===void 0)throw new P("E_UNSUPPORTED","not a NodeIdMap of this package",{reason:"foreign id map"});return e}function fn(n,e,t={}){return{kind:n,size:e,offset:0,denseValues:null,denseInverse:null,decoded:null,numbers:null,tags:null,strings:null,map:null,stringIndex:null,...t}}function ed(n){return n.size===0?!1:n.denseValues!==null&&n.denseValues.length===0||n.decoded===null&&n.numbers!==null&&n.numbers.length===0||n.decoded===null&&n.tags!==null&&n.tags.length===0||n.decoded===null&&n.strings?.detached===!0}function xy(n){const e=Bs.get(n);return e!==void 0&&ed(e)}function jo(n){return n===0?0:n}function Ca(n,e,t){return new P("E_DUPLICATE_ID",`duplicate node id ${Pn(n)} at indices ${e} and ${t}`,{id:n,indices:[e,t]})}function Wr(n,e){return new P("E_INVALID_SNAPSHOT",`id map violates invariant I11: ${n}`,{invariant:"I11",reason:n,...e})}function hn(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function td(n,e,t){const r=new Uint32Array(e+1).fill(x);for(let o=0;o<n.length;o++){const s=n[o];if(r[s]!==x)throw t(s,r[s],o);r[s]=o}return r}function qo(n,e,t){const r=new Map;for(let o=0;o<e;o++){const s=n[o],i=r.get(s);if(i!==void 0)throw t(s,i,o);r.set(s,o)}return r}function Cy(n,e){let t=!0,r=!0,o=!0,s=-1,i=0,a=!0;if(e>0){const c=n[0];typeof c=="number"&&Number.isSafeInteger(c)?i=c:a=!1}for(let c=0;c<e;c++){const l=n[c];typeof l=="number"?(r=!1,a&&l!==c+i&&(a=!1),o&&(Number.isInteger(l)&&l>=0&&l<Te?l>s&&(s=l):o=!1)):(t=!1,a=!1,o=!1)}return t||(s=-1),{allNumbers:t,allStrings:r,identity:a,offset:i,allDenseIntegers:o,maxId:s}}function Ny(n,e){return e===0||n.identity?"identity":n.allDenseIntegers&&n.maxId+1<=2*e?"dense":n.allNumbers?"numeric":n.allStrings?"string":"mixed"}function Ty(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++){const o=n[r];t[r]=typeof o=="number"?o:x}return t}class Yt{constructor(e){this.kind=e.kind,this.size=e.size,this.offset=e.kind==="identity"?e.offset:0,this.storage=e,Bs.set(this,e),Object.freeze(this)}idOf(e){if(!(e>=0&&e<this.size)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`node index ${e} out of range (size ${this.size})`,{index:e,size:this.size});return this.idAt(e)}indexOf(e){const{storage:t}=this;switch(t.kind){case"identity":{if(typeof e!="number")return x;const r=e-t.offset;return!Number.isInteger(r)||r<0||r>=t.size?x:r===0?0:r}case"dense":{const r=t.denseInverse;return typeof e!="number"||!Number.isInteger(e)||e<0||e>=r.length?x:r[e]}case"numeric":case"string":case"mixed":{const r=this.reverseMap().get(e);return r===void 0||r>=t.size?x:r}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}has(e){return this.indexOf(e)!==x}requireIndex(e){const t=this.indexOf(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return t}indicesOf(e,t="invalid"){zt("onMissing",t,["invalid","throw"]);const r=t==="throw"?i=>this.requireIndex(i):i=>this.indexOf(i);if(Array.isArray(e)){const i=e,a=new Uint32Array(i.length);for(let c=0;c<i.length;c++)a[c]=r(i[c]);return a}let o=new Uint32Array(16),s=0;for(const i of e){if(s===o.length){const a=new Uint32Array(o.length*2);a.set(o),o=a}o[s++]=r(i)}return o.slice(0,s)}idsSlice(e=0,t=this.size){const[r,o]=Cu(e,t,this.size),{storage:s}=this;switch(this.assertAttached(),s.kind){case"identity":{const i=new Array(o-r);for(let a=r;a<o;a++)i[a-r]=a+s.offset;return i}case"dense":return Array.from(s.denseValues.subarray(r,o));case"numeric":return s.decoded!==null?s.decoded.slice(r,o):Array.from(s.numbers.subarray(r,o),jo);case"string":return s.strings.slice(r,o);case"mixed":{if(s.decoded!==null)return s.decoded.slice(r,o);const i=s.tags,a=s.numbers,c=s.strings,l=new Array(o-r);for(let u=r;u<o;u++)l[u-r]=i[u]===0?jo(a[u]):c.at(u);return l}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(s.kind)}`,{kind:s.kind})}}toArray(){return this.idsSlice(0,this.size)}*[Symbol.iterator](){for(let e=0;e<this.size;e++)yield this.idAt(e)}toMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(this.idAt(r),e[r]);return t}toStringMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(String(this.idAt(r)),e[r]);return t}toRecord(e){const t=Object.create(null);for(let r=0;r<this.size;r++)t[String(this.idAt(r))]=e[r];return t}*entries(e){for(let t=0;t<this.size;t++)yield[this.idAt(t),e[t]]}stringIndex(){const{storage:e}=this;if(e.stringIndex===null){const t=new Map;for(let r=0;r<e.size;r++){const o=this.idAt(r),s=String(o);(typeof o=="string"||!t.has(s))&&t.set(s,r)}e.stringIndex=t}return e.stringIndex}byteLength(){const{storage:e}=this;let t=0;return e.denseValues!==null&&(t+=e.denseValues.byteLength),e.denseInverse!==null&&(t+=e.denseInverse.byteLength),e.numbers!==null&&(t+=e.numbers.byteLength),e.tags!==null&&(t+=e.tags.byteLength),e.strings!==null&&(t+=e.strings.byteLength()),t}idAt(e){const{storage:t}=this;switch(this.assertAttached(),t.kind){case"identity":return e+t.offset;case"dense":return t.denseValues[e];case"numeric":return t.decoded!==null?t.decoded[e]:jo(t.numbers[e]);case"string":return t.strings.at(e);case"mixed":return t.decoded!==null?t.decoded[e]:t.tags[e]===0?jo(t.numbers[e]):t.strings.at(e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}assertAttached(){if(ed(this.storage))throw new P("E_DETACHED","the id map's storage was transferred away",{kind:this.storage.kind})}reverseMap(){const{storage:e}=this;if(e.map===null){this.assertAttached(),e.decoded===null&&e.strings!==null&&e.strings.materialiseDecoded();const t=new Map;for(let r=0;r<e.size;r++)t.set(this.idAt(r),r);e.map=t}return e.map}}function nd(n,e=0){if(!Number.isInteger(n)||n<0||n>Te)throw new P("E_TOO_LARGE",`node count ${n} is not an integer in [0, MAX_COUNT]`,{count:n,max:Te});if(!Number.isSafeInteger(e))throw new P("E_INVALID_ID",`identity offset ${e} is not a safe integer`,{offset:e,reason:"non-integer offset"});return new Yt(fn("identity",n,{offset:e}))}function rd(n,e=n.length,t={}){if(!Number.isInteger(e)||e<0||e>Te)throw new P("E_TOO_LARGE",`node count ${e} is not an integer in [0, MAX_COUNT]`,{count:e,max:Te});const r=t.map!==void 0||t.validate===!1;let o=n;if(!r){const a=new Array(e);for(let c=0;c<e;c++)a[c]=jn(n[c]);o=a}const s=Cy(o,e),i=Ny(s,e);switch(i){case"identity":return new Yt(fn("identity",e,{offset:e===0?0:s.offset}));case"dense":{const a=Ty(o,e),c=td(a,s.maxId,Ca);return new Yt(fn("dense",e,{denseValues:a,denseInverse:c}))}case"numeric":case"mixed":{const a=t.map??(r?null:qo(o,e,Ca));return new Yt(fn(i,e,{decoded:o,map:a}))}case"string":{const a=t.map??(r?null:qo(o,e,Ca)),c=Wn.fromStrings(o,e);return new Yt(fn("string",e,{strings:c,map:a}))}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(i)}`,{kind:i})}}function Oy(n){const e=Bs.get(n),t=new Set;if(e===void 0)return[];for(const r of[e.denseValues,e.denseInverse,e.numbers,e.tags])r!==null&&t.add(r.buffer);return e.strings?.encoded&&(t.add(e.strings.offsets.buffer),t.add(e.strings.utf8.buffer)),[...t]}function $y(n,e="structure"){const{kind:t,size:r}=n;if(e!=="none"&&(!Number.isInteger(r)||r<0||r>Te))throw hn("ids.size",`size ${r} is not an integer in [0, MAX_COUNT]`,{found:r});switch(t){case"identity":return Ry(n,e);case"dense":return Dy(n,e);case"numeric":return Ly(n,e);case"string":return My(n,e);case"mixed":return By(n,e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Na(n,e,t){return Wr(`duplicate id ${Pn(n)}`,{id:n,indices:[e,t]})}function zs(n,e,t,r){if(t!==r)throw hn(n,`expected ${r} ${e}, found ${t}`,{expected:r,found:t})}function od(n){const e=n.firstMalformedRow();if(e!==-1)throw Wr(`malformed UTF-8 in id at index ${e}`,{index:e})}function Ry(n,e){const{offset:t,size:r}=n;if(!Number.isSafeInteger(t)||r>0&&!Number.isSafeInteger(t+r-1)){const o=`offset ${t} with ${r} ids leaves the safe-integer range`;throw e==="full"?Wr(o,{found:t,size:r}):hn("ids.offset",o,{found:t,size:r})}return new Yt(fn("identity",r,{offset:jo(t)}))}function Dy(n,e){const{values:t,size:r}=n;if(!(t instanceof Uint32Array))throw hn("ids.values","a dense id map needs u32 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=-1;for(let i=0;i<t.length;i++)t[i]>o&&(o=t[i]);if(o>=Te)throw hn("ids.values",`dense id ${o} is not below MAX_COUNT`,{found:o});if(o+1>2*Math.max(r,t.length))throw hn("ids.values",`dense bound violated: max id ${o} with ${r} nodes`,{maxId:o,size:r});const s=td(t,o,(i,a,c)=>Wr(`duplicate id ${i}`,{id:i,indices:[a,c]}));return new Yt(fn("dense",r,{denseValues:t,denseInverse:s}))}function Ly(n,e){const{values:t,size:r}=n;if(!(t instanceof Float64Array))throw hn("ids.values","a numeric id map needs f64 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=null;if(e==="full"){for(let s=0;s<r;s++)if(!Number.isFinite(t[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:t[s]});o=qo(t,r,Na)}return new Yt(fn("numeric",r,{numbers:t,map:o}))}function My(n,e){const{offsets:t,utf8:r,size:o}=n;if(t===null||r===null)throw hn("ids.offsets","a string id map needs offsets and utf8");e!=="none"&&ha(t,r,o,"ids.offsets");const s=Wn.fromEncoded(t,r);let i=null;return e==="full"&&(od(s),i=qo(s.decodeAll(),o,Na)),new Yt(fn("string",o,{strings:s,map:i}))}function Uy(n,e,t,r,o){zs("ids.tags","tags",n.length,o),zs("ids.numbers","numbers",e.length,o);for(let s=0;s<o;s++)if(n[s]>1)throw hn("ids.tags",`tag ${n[s]} at index ${s} is not 0 or 1`,{index:s,found:n[s]});ha(t,r,o,"ids.offsets")}function Fy(n,e,t,r){const o=new Array(r);for(let s=0;s<r;s++)if(n[s]===0){if(!Number.isFinite(e[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:e[s]});o[s]=e[s]}else o[s]=t.at(s);return o}function By(n,e){const{tags:t,numbers:r,offsets:o,utf8:s,size:i}=n;if(t===null||r===null||o===null||s===null)throw hn("ids.tags","a mixed id map needs tags, numbers, offsets and utf8");e!=="none"&&Uy(t,r,o,s,i);const a=Wn.fromEncoded(o,s);let c=null;return e==="full"&&(od(a),c=qo(Fy(t,r,a,i),i,Na)),new Yt(fn("mixed",i,{tags:t,numbers:r,strings:a,map:c}))}function zy(n){const e=Py(n),{kind:t,size:r}=e;switch(t){case"identity":return{kind:t,size:r,offset:e.offset,values:null,tags:null,numbers:null,offsets:null,utf8:null};case"dense":return{kind:t,size:r,offset:0,values:e.denseValues,tags:null,numbers:null,offsets:null,utf8:null};case"numeric":{if(e.numbers===null){const o=e.decoded,s=new Float64Array(r);for(let i=0;i<r;i++){const a=o[i];if(typeof a!="number")throw new P("E_INVALID_ID",`numeric id map holds a ${typeof a} at index ${i}`,{index:i,found:typeof a});s[i]=a}e.numbers=s,it(s.buffer)}return{kind:t,size:r,offset:0,values:e.numbers,tags:null,numbers:null,offsets:null,utf8:null}}case"string":{const o=e.strings;return{kind:t,size:r,offset:0,values:null,tags:null,numbers:null,offsets:o.offsets,utf8:o.utf8}}case"mixed":{if(e.tags===null||e.numbers===null||e.strings===null){const o=e.decoded,s=new Uint8Array(r),i=new Float64Array(r);for(let l=0;l<r;l++){const u=o[l];typeof u=="number"?i[l]=u:s[l]=1}const{offsets:a,utf8:c}=Do(o,r);e.tags=s,e.numbers=i,e.strings=Wn.fromEncoded(a,c);for(const l of[s.buffer,i.buffer,a.buffer,c.buffer])it(l)}return{kind:t,size:r,offset:0,values:null,tags:e.tags,numbers:e.numbers,offsets:e.strings.offsets,utf8:e.strings.utf8}}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Gy(n,e){const t=e.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n.idOf(e[o]);return rd(r,t,{validate:!1})}const Wy=new Set(["string","integer","mixed"]),Vy=new Set(["integer","double","date","dateTime"]),jy=new Set(["interval","timestamp"]),qy=new Set(["static","dynamic","slice"]),Ta=Object.freeze({name:null,description:null,creator:null,created:null,modified:null,keywords:Object.freeze([]),sourceFormat:null,sourceVersion:null,idType:null,timeFormat:null,timeRepresentation:null,mode:null,declaredMultigraph:null,weightOrigin:null,extra:Object.freeze({})});function Vr(n,e){return new P("E_COLUMN_TYPE",`meta.${n} has an unsupported value`,{field:n,found:typeof e})}function vr(n,e){if(e===null||typeof e=="string")return e;throw Vr(n,e)}function Gs(n,e,t){if(e===null)return null;if(typeof e=="string"&&t.has(e))return e;throw Vr(n,e)}function Hy(n){if(n===null)return null;if(typeof n!="object")throw Vr("weightOrigin",n);const e=n,t=r=>{const o=e[r];if(o==null)return null;if(typeof o!="string")throw Vr(`weightOrigin.${r}`,o);return o};return Object.freeze({format:t("format"),id:t("id"),title:t("title"),type:t("type"),namespace:t("namespace")})}function Ky(n,e){const t=(r,o)=>{const s=e[r];return s===void 0?n[r]:o(s)};return Object.freeze({name:t("name",r=>vr("name",r)),description:t("description",r=>vr("description",r)),creator:t("creator",r=>vr("creator",r)),created:t("created",r=>vr("created",r)),modified:t("modified",r=>vr("modified",r)),keywords:t("keywords",r=>{if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw Vr("keywords",r);return Object.freeze([...r])}),sourceFormat:t("sourceFormat",r=>vr("sourceFormat",r)),sourceVersion:t("sourceVersion",r=>vr("sourceVersion",r)),idType:t("idType",r=>Gs("idType",r,Wy)),timeFormat:t("timeFormat",r=>Gs("timeFormat",r,Vy)),timeRepresentation:t("timeRepresentation",r=>Gs("timeRepresentation",r,jy)),mode:t("mode",r=>Gs("mode",r,qy)),declaredMultigraph:t("declaredMultigraph",r=>{if(r===null||typeof r=="boolean")return r;throw Vr("declaredMultigraph",r)}),weightOrigin:t("weightOrigin",r=>Hy(r)),extra:t("extra",r=>ht("meta","graph",{dtype:"json",extra:r}).extra)})}const Yy=4294967295;class bt{constructor(e,t){this.used=0,this.ctor=e,this.resizable=t?.resizable??ga,this.backing=this.allocate(t?.capacity??0)}get length(){return this.used}get capacity(){return this.backing.length}get array(){return this.backing}push(e){const t=this.used;return t>=this.backing.length&&(this.backing=$u(this.backing,this.ctor,t+1,this.resizable)),this.backing[t]=e,this.used=t+1,t}pushAll(e){const t=this.used,r=t+e.length;return this.ensureCapacity(r),this.backing.set(e,t),this.used=r,t}get(e){return this.backing[e]}set(e,t){this.backing[e]=t}ensureCapacity(e){e>this.backing.length&&(this.backing=$u(this.backing,this.ctor,e,this.resizable))}resize(e,t=0){e>this.used&&(this.ensureCapacity(e),this.backing.fill(t,this.used,e)),this.used=e}view(){return new this.ctor(this.backing.buffer,0,this.used)}trim(){const e=new this.ctor(new ArrayBuffer(this.used*this.ctor.BYTES_PER_ELEMENT),0,this.used);return e.set(this.view()),e}clear(){this.used=0}release(){this.used=0,this.backing=this.allocate(0)}allocate(e){const t=this.ctor.BYTES_PER_ELEMENT,r=e===0?0:Tu(Lo(e,wa),t);return new this.ctor(Ou(r,this.resizable),0,r/t)}}class xn{constructor(e){this.bits=0,this.words=new bt(Uint32Array,{capacity:Fe(e?.capacity??0),resizable:e?.resizable})}get length(){return this.bits}push(e){const t=this.bits;return t%32===0&&this.words.push(0),e&&ba(this.words.array,t,!0),this.bits=t+1,t}get(e){return Le(this.words.array,e)}set(e,t){ba(this.words.array,e,t)}count(){return gr(this.words.array,this.bits)}resize(e,t=!1){const r=this.bits;this.words.resize(Fe(e),0),e<r?ya(this.words.array,e):t&&e>r&&this.setRange(r,e),this.bits=e}setRange(e,t){const{array:r}=this.words;let o=e;for(;o<t&&o%32!==0;)Ht(r,o++);const s=t-t%32;for(o<s&&(r.fill(Yy,o/32,s/32),o=s);o<t;)Ht(r,o++)}view(){return this.words.view()}trim(){return this.words.trim()}clear(){this.bits=0,this.words.clear()}release(){this.bits=0,this.words.release()}}const Xy=Object.freeze([]),Oa=2**24;function $a(n){if(n>Oa)throw new P("E_TOO_LARGE",`node count ${n} exceeds the ${Oa} nodes with explicit ids one builder can hold`,{count:n,max:Oa})}function gn(n,e,t,r){return new P("E_COLUMN_TYPE",`row ${e} of ${n.dtype} column "${n.name}": ${t}`,{column:n.name,domain:n.domain,row:e,found:r})}function Ra(n){const e=Ls(n);if(e===null)throw new P("E_COLUMN_TYPE","an unset value cannot start an inferred column",{reason:"unset"});return e}function Da(n){switch(n){case"bool":return"bool";case"i32":case"u8":return"i32";case"u32":case"f32":case"f64":return"f64";case"dict":case"string":return"string";case"list":case"json":return"json";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function Qy(n,e,t){const r=n.itemDtype,o=n.itemComponents??1;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":Jy(n,e,t,r,o);return;case"bool":if(typeof t!="boolean")throw gn(n,e,"list item is not a boolean",typeof t);return;case"dict":case"string":if(typeof t!="string")throw gn(n,e,"list item is not a string",typeof t);wr(t,{column:n.name,row:e});return;case"json":cn(t,n.name);return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Jy(n,e,t,r,o){if(o===1){if(typeof t!="number"||!yr(r,t))throw gn(n,e,`list item is not a representable ${r}`,typeof t);return}if(!Array.isArray(t)||t.length!==o)throw gn(n,e,`list item is not ${o} numbers`,typeof t);for(const s of t)if(typeof s!="number"||!yr(r,s))throw gn(n,e,`list item component is not a representable ${r}`,typeof s)}class Ws{constructor(e,t,r,o){this.length=0,this.typed=null,this.bits=null,this.values=null,this.dictionary=null,this.validity=null,this.meta=e,this.resizable=r,t?(this.inferrer=new zu,this.inferrer.widenTo(Da(e.dtype))):this.inferrer=null,this.allocate(o)}get inferred(){return this.inferrer!==null}get inferredDtype(){return this.inferrer===null?null:this.inferrer.dtype}ensureLength(e){if(e<=this.length)return;const{meta:t}=this;if(this.typed!==null)this.typed.resize(e*t.components,this.fillNumber());else if(this.bits!==null)this.bits.resize(e,t.fill===!0);else if(this.values!==null){const r=this.fillValue();for(let o=this.length;o<e;o++)this.values.push(r)}this.validity!==null&&this.validity.resize(e,!1),this.length=e}isSet(e){return e>=this.length?!1:this.validity===null||this.validity.get(e)}write(e,t){if(this.ensureLength(e+1),t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json"))return this.unset(e),null;let r=null;if(this.inferrer!==null){const o=this.meta.dtype;if(this.inferrer.observeValue(t)){const s=this.inferrer.dtype;this.widenTo(s),r={from:o,to:s}}this.storeRaw(e,t)}else this.store(e,t);return this.validity!==null&&this.validity.set(e,!0),r}checkValue(e,t){if(t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json")){if(this.validity===null)throw this.unsetError(e);return}if(this.inferrer!==null){Ls(t),this.checkRaw(e,t);return}this.coerce(e,t)}unset(e){if(this.ensureLength(e+1),this.validity===null)throw this.unsetError(e);this.validity.set(e,!1),this.writeFill(e)}unsetError(e){return new P("E_COLUMN_TYPE",`row ${e} of non-nullable column "${this.meta.name}" cannot be unset`,{column:this.meta.name,row:e,field:"nullable"})}read(e){if(!this.isSet(e))return;if(this.inferrer!==null)return Br(this.values[e],this.inferrer.dtype);const{meta:t}=this,{dtype:r,components:o}=t;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(o===1)return s.get(e);const i=new Array(o);for(let a=0;a<o;a++)i[a]=s.get(e*o+a);return i}case"bool":return this.bits.get(e);case"dict":{const s=this.typed.get(e);return this.dictionary.values[s]}case"string":case"list":case"json":return this.values[e];default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}widenTo(e){const{meta:t}=this,r=ht(t.name,t.domain,{dtype:e,nullable:!0,role:t.role??void 0,extra:t.extra});if(this.inferrer!==null){this.inferrer.widenTo(e),this.meta=r;return}const o=this.length,s=new Array(o),i=new xn({capacity:o,resizable:this.resizable});i.resize(o,!1);for(let a=0;a<o;a++)this.isSet(a)&&(s[a]=this.read(a),i.set(a,!0));this.meta=r,this.inferrer=new zu,this.inferrer.widenTo(e),this.typed=null,this.bits=null,this.dictionary=null,this.values=s,this.validity=i}gather(e,t){const r=e===null?this.length:e.length,o=new Ws(this.meta,this.inferred,this.resizable,this.dictionary??void 0);o.ensureLength(r);const{components:s}=this.meta,i=t!==null&&this.meta.refersTo!==null;for(let a=0;a<r;a++){const c=e===null?a:e[a];if(this.isSet(c)){if(o.typed!==null&&this.typed!==null)if(i){const l=sd(this.typed.get(c),t);if(l===x){o.unsetDangling(a);continue}o.typed.set(a,l)}else for(let l=0;l<s;l++)o.typed.set(a*s+l,this.typed.get(c*s+l));else if(o.bits!==null&&this.bits!==null)o.bits.set(a,this.bits.get(c));else if(o.values!==null&&this.values!==null){let l=this.values[c];if(i){const u=l,d=[];for(const f of u){const h=sd(f,t);h!==x&&d.push(h)}if(d.length===0&&u.length>0){o.unsetDangling(a);continue}l=d}o.values[a]=l}o.validity!==null&&o.validity.set(a,!0)}}return o}unsetDangling(e){if(this.validity!==null)return;const{meta:t}=this;this.meta=ht(t.name,t.domain,{...Sn(t),nullable:!0});const r=new xn({capacity:this.length,resizable:this.resizable});r.resize(this.length,!1);const{typed:o}=this;for(let s=0;s<e;s++)o?.get(s)!==x&&r.set(s,!0);this.validity=r}toColumn(e){this.ensureLength(e);const{meta:t}=this,{dtype:r,components:o}=t;if(this.inferrer!==null){const a=this.values,c=new Array(e);for(let l=0;l<e;l++)c[l]=this.isSet(l)?a[l]:void 0;return Vo(t,c)}let s=null;this.validity!==null&&this.validity.count()!==e&&(s=this.validity.trim());const i={meta:t,length:e,data:null,validity:s,nullCount:s===null?0:e-this.validity.count(),dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null};switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const a=Ju(r,e*o);return a.set(this.typed.view().subarray(0,e*o)),i.data=a,t.refersTo!==null&&this.validity===null&&Zy(i,a,e),Tt(i)}case"bool":return i.data=this.bits.trim(),Tt(i);case"dict":{const a=new Uint32Array(e);return a.set(this.typed.view().subarray(0,e)),i.data=a,i.dictionary=[...this.dictionary.values],Tt(i)}case"string":case"list":case"json":{const a=this.values,c=new Array(e);for(let l=0;l<e;l++){const u=this.isSet(l)?a[l]:void 0;c[l]=u===void 0?this.unsetEntry():u}return Vo(t,c)}default:{const a=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}byteLength(){let e=0;return this.typed!==null&&(e+=this.typed.array.byteLength),this.bits!==null&&(e+=Fe(this.bits.length)*4),this.validity!==null&&(e+=Fe(this.validity.length)*4),e}allocate(e){const{meta:t}=this,{dtype:r}=t,o={resizable:this.resizable};if(this.inferrer!==null){this.values=[],this.validity=new xn(o);return}switch(r){case"f32":this.typed=new bt(Float32Array,o);break;case"f64":this.typed=new bt(Float64Array,o);break;case"i32":this.typed=new bt(Int32Array,o);break;case"u32":this.typed=new bt(Uint32Array,o);break;case"u8":this.typed=new bt(Uint8Array,o);break;case"bool":this.bits=new xn(o);break;case"dict":{this.typed=new bt(Uint32Array,o),this.dictionary=e??Pa(t);break}case"string":case"list":case"json":this.values=[];break;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}this.validity=t.nullable?new xn(o):null}fillNumber(){const{meta:e}=this;if(e.dtype==="dict"){const t=this.dictionary,r=typeof e.fill=="string"?e.fill:"";if(this.validity===null)return t.intern(r);const o=t.codeOf(r);return o===x?0:o}return typeof e.fill=="number"?e.fill:0}fillValue(){if(this.inferrer===null)switch(this.meta.dtype){case"string":return typeof this.meta.fill=="string"?this.meta.fill:"";case"list":return Xy;default:return}}unsetEntry(){if(!this.meta.nullable)return this.meta.dtype==="json"?null:this.fillValue()}writeFill(e){const{components:t}=this.meta;if(this.typed!==null){const r=this.fillNumber();for(let o=0;o<t;o++)this.typed.set(e*t+o,r)}else this.bits!==null?this.bits.set(e,this.meta.fill===!0):this.values!==null&&(this.values[e]=this.fillValue())}storeRaw(e,t){this.checkRaw(e,t),this.values[e]=typeof t=="string"?Ro(t):t}checkRaw(e,t){const{meta:r}=this;typeof t=="string"?wr(t,{column:r.name,row:e}):typeof t=="object"&&cn(t,`${r.name}[${e}]`)}store(e,t){this.put(e,this.coerce(e,t))}coerce(e,t){const{meta:r}=this,{dtype:o,components:s}=r;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":{const i=typeof t=="boolean"?Number(t):t;if(typeof i=="number"){if(!yr(o,i))throw gn(r,e,`${i} is not representable`,i);return i}if(s===1||!Yu(i,s))throw gn(r,e,`not ${s} number(s)`,typeof i);for(let a=0;a<s;a++)if(!yr(o,i[a]))throw gn(r,e,`${i[a]} is not representable`,i[a]);return i}case"bool":return Br(t,"bool")===!0;case"dict":case"string":{const i=Br(t,"string");if(typeof i!="string")throw gn(r,e,"not a string",typeof t);return wr(i,{column:r.name,row:e}),Ro(i)}case"list":{if(!Array.isArray(t))throw gn(r,e,"not an array",typeof t);for(const i of t)Qy(r,e,i);return t.map(i=>typeof i=="string"?Ro(i):i)}case"json":return cn(t,`${r.name}[${e}]`),t;default:{const i=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}put(e,t){const{dtype:r,components:o}=this.meta;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(typeof t=="number"){if(o===1)s.set(e,t);else for(let a=0;a<o;a++)s.set(e*o+a,t);return}const i=t;for(let a=0;a<o;a++)s.set(e*o+a,i[a]);return}case"bool":this.bits.set(e,t===!0);return;case"dict":this.typed.set(e,this.dictionary.intern(t));return;case"string":case"list":case"json":this.values[e]=t;return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}}function sd(n,e){return n<e.length?e[n]:x}function Zy(n,e,t){let r=null;for(let o=0;o<t;o++)e[o]===x&&(r??=In(t,!0),Kt(r,o),n.nullCount++);if(r!==null){const{meta:o}=n;n.meta=ht(o.name,o.domain,{...Sn(o),nullable:!0}),n.validity=r}}function jr(n,e,t,r,o){return new Ws(ht(n,e,t),r,o)}class id{constructor(e,t){this.lists=e,this.alive=t,this.found=[],this.list=0,this.edge=e[0][0]}step(){for(;this.edge===x;){if(this.list++,this.list===this.lists.length)return!0;this.edge=this.lists[this.list][0]}const[,e,t,r]=this.lists[this.list];return this.alive.get(this.edge)&&t.get(this.edge)===r&&this.found.push(this.edge),this.edge=e.get(this.edge),!1}}class La{constructor(e){this.ids=null,this.idToIndex=null,this.weight=null,this.weightSet=null,this.weightMode="none",this.liveNodeCount=0,this.liveEdgeCount=0,this.selfLoopCount=0,this.nodeColumns=[],this.edgeColumns=[],this.extensions=[],this.options=e;const{resizable:t}=e,r=e.expectedNodes??0,o=e.expectedEdges??0;this.nodeAlive=new xn({capacity:r,resizable:t}),this.firstOut=new bt(Uint32Array,{capacity:r,resizable:t}),this.firstIn=new bt(Uint32Array,{capacity:r,resizable:t}),this.src=new bt(Uint32Array,{capacity:o,resizable:t}),this.dst=new bt(Uint32Array,{capacity:o,resizable:t}),this.edgeAlive=new xn({capacity:o,resizable:t}),this.nextOut=new bt(Uint32Array,{capacity:o,resizable:t}),this.nextIn=new bt(Uint32Array,{capacity:o,resizable:t}),e.weighted&&(this.weight=this.allocateWeights(o))}get nodeBound(){return this.nodeAlive.length}get edgeBound(){return this.edgeAlive.length}get hasTombstones(){return this.liveNodeCount<this.nodeBound||this.liveEdgeCount<this.edgeBound}reserve(e,t){e>0&&(this.firstOut.ensureCapacity(e),this.firstIn.ensureCapacity(e)),t>0&&(this.src.ensureCapacity(t),this.dst.ensureCapacity(t),this.nextOut.ensureCapacity(t),this.nextIn.ensureCapacity(t),this.weight!==null&&this.weight.ensureCapacity(t))}materialiseIds(){if(this.ids!==null&&this.idToIndex!==null)return;const e=this.nodeBound;$a(e);const t=new Array(e),r=new Map;for(let o=0;o<e;o++)t[o]=o,r.set(o,o);this.ids=t,this.idToIndex=r}pushNode(e){this.idToIndex!==null&&$a(this.idToIndex.size+1);const t=this.nodeAlive.push(!0);if(this.firstOut.push(x),this.firstIn.push(x),this.ids!==null&&this.idToIndex!==null){const r=e??t;this.ids.push(r),this.idToIndex.set(r,t)}return this.liveNodeCount++,t}pushAnonymousNodes(e){if(this.idToIndex!==null){for(let r=0;r<e;r++)this.pushNode(null);return}const t=this.nodeBound+e;this.nodeAlive.resize(t,!0),this.firstOut.resize(t,x),this.firstIn.resize(t,x),this.liveNodeCount+=e}ensureWeights(){return this.weight===null&&(this.weight=this.allocateWeights(this.edgeBound),this.weight.resize(this.edgeBound,1)),this.weight}trackWeight(e,t){if(this.weightSet!==null){e>=this.weightSet.length&&this.weightSet.resize(e+1,!1),this.weightSet.set(e,t);return}switch(this.weightMode){case"none":this.weightMode=t?"explicit":"omitted";return;case"explicit":t||this.allocateWeightSet(!0,e);return;case"omitted":t&&this.allocateWeightSet(!1,e);return;case"mixed":return;default:{const r=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${r}`,{mode:r})}}}weightExplicit(e){return this.weightSet===null?this.weightMode==="explicit":e<this.weightSet.length&&this.weightSet.get(e)}pushEdge(e,t,r){const o=this.src.push(e);return this.dst.push(t),r!==void 0?this.ensureWeights().push(r):this.weight!==null&&this.weight.push(1),this.trackWeight(o,r!==void 0),this.edgeAlive.push(!0),this.nextOut.push(this.firstOut.get(e)),this.firstOut.set(e,o),this.nextIn.push(this.firstIn.get(t)),this.firstIn.set(t,o),this.liveEdgeCount++,e===t&&this.selfLoopCount++,o}pushEdges(e,t,r){const o=e.length,s=this.edgeBound,i=s+o;return o===0||(this.src.pushAll(e),this.dst.pushAll(t),r!==null?this.ensureWeights().pushAll(r):this.weight!==null&&this.weight.resize(i,1),this.trackWeights(s,o,r!==null),this.edgeAlive.resize(i,!0),this.nextOut.resize(i),this.nextIn.resize(i),this.selfLoopCount+=tb(this.src.array,this.dst.array,s,i,{firstOut:this.firstOut.array,firstIn:this.firstIn.array,nextOut:this.nextOut.array,nextIn:this.nextIn.array}),this.liveEdgeCount+=o),s}trackWeights(e,t,r){const o=e+t;let s=this.weightSet;if(s===null)switch(this.weightMode){case"none":this.weightMode=r?"explicit":"omitted";return;case"explicit":if(r)return;s=this.allocateWeightSet(!0,e);break;case"omitted":if(!r)return;s=this.allocateWeightSet(!1,e);break;case"mixed":return;default:{const i=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${i}`,{mode:i})}}s.length<e&&s.resize(e,!1),s.resize(o,r)}killEdge(e){this.edgeAlive.set(e,!1),this.liveEdgeCount--,this.src.get(e)===this.dst.get(e)&&this.selfLoopCount--}outEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}inEdges(e){const t=[];for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}incidentEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&this.src.get(r)!==e&&t.push(r);return Uint32Array.from(t).sort()}edgesBetween(e,t,r){const o=(u,d)=>[this.firstOut.get(u),this.nextOut,this.dst,d],s=(u,d)=>[this.firstIn.get(u),this.nextIn,this.src,d],i=r||e===t?[o(e,t)]:[o(e,t),s(e,t)],a=r?[s(t,e)]:[o(t,e),s(t,e)],c=new id(i,this.edgeAlive),l=e===t?c:new id(a,this.edgeAlive);for(;;){if(c.step())return Uint32Array.from(c.found).sort();if(l.step())return Uint32Array.from(l.found).sort()}}byteLength(){let e=this.firstOut.array.byteLength+this.firstIn.array.byteLength+this.src.array.byteLength+this.dst.array.byteLength+this.nextOut.array.byteLength+this.nextIn.array.byteLength+Fe(this.nodeAlive.length)*4+Fe(this.edgeAlive.length)*4;this.weight!==null&&(e+=this.weight.array.byteLength),this.weightSet!==null&&(e+=Fe(this.weightSet.length)*4);for(const t of this.nodeColumns)e+=t.byteLength();for(const t of this.edgeColumns)e+=t.byteLength();for(const t of this.extensions)for(const r of t.columns)e+=r.byteLength();return e}allocateWeights(e){const{resizable:t}=this.options;return this.options.weightDtype==="f64"?new bt(Float64Array,{capacity:e,resizable:t}):new bt(Float32Array,{capacity:e,resizable:t})}allocateWeightSet(e,t){const r=new xn({capacity:t+1,resizable:this.options.resizable});return r.resize(t,e),r.push(!e),this.weightSet=r,this.weightMode="mixed",r}}function ad(n,e){const t=new Uint32Array(n);let r=0;for(let s=0;s<n;s++)(e[s>>>5]>>>(s&31)&1)===1?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<n;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function eb(n){const e=n.length,t=new Uint32Array(e);let r=0;for(let s=0;s<e;s++)n[s]===s?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<e;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function tb(n,e,t,r,o){const{firstOut:s,firstIn:i,nextOut:a,nextIn:c}=o;let l=0;for(let u=t;u<r;u++){const d=n[u],f=e[u];a[u]=s[d],s[d]=u,c[u]=i[f],i[f]=u,d===f&&l++}return l}function nb(n,e,t,r,o,s,i){const{firstOut:a,firstIn:c,nextOut:l,nextIn:u}=i,d=t.length;let f=0;for(let h=0;h<d;h++){const g=t[h],w=r[n[g]],p=r[e[g]];o[h]=w,s[h]=p,l[h]=a[w],a[w]=h,u[h]=c[p],c[p]=h,w===p&&f++}return f}function rb(n,e,t){const r=e.length;for(let o=0;o<r;o++)t[o]=n[e[o]]}function ob(n,e,t,r){for(let o=0;o<r;o++)Le(e,o)&&(t[o]=n[o])}function cd(n,e){const{nodes:t,edges:r}=e,o=new La({...n.options,weighted:n.weight!==null||e.mergedWeights!==null,expectedNodes:t.count,expectedEdges:r.count});if(o.nodeAlive.resize(t.count,!0),o.firstOut.resize(t.count,x),o.firstIn.resize(t.count,x),o.liveNodeCount=t.count,n.ids!==null){const l=new Array(t.count),u=new Map;for(let d=0;d<t.count;d++){const f=n.ids[t.origin[d]];l[d]=f,u.set(f,d)}o.ids=l,o.idToIndex=u}const{remap:s}=t,i=r.count,{origin:a}=r;if(o.weightMode=n.weightMode,(n.weightSet!==null||e.mergedWeightSet!==null)&&(o.weightSet=new xn({capacity:i,resizable:n.options.resizable}),o.weightMode="mixed"),o.src.resize(i),o.dst.resize(i),o.nextOut.resize(i),o.nextIn.resize(i),o.edgeAlive.resize(i,!0),o.liveEdgeCount=i,o.selfLoopCount=nb(n.src.array,n.dst.array,a,s,o.src.array,o.dst.array,{firstOut:o.firstOut.array,firstIn:o.firstIn.array,nextOut:o.nextOut.array,nextIn:o.nextIn.array}),o.weight!==null){o.weight.resize(i);const l=o.weight.array;n.weight===null?l.fill(1,0,i):rb(n.weight.array,a,l),e.mergedWeights!==null&&e.mergedWeightStored!==null&&ob(e.mergedWeights,e.mergedWeightStored,l,i)}if(o.weightSet!==null){o.weightSet.resize(i,!1);for(let l=0;l<i;l++){let u=n.weightExplicit(a[l]);e.mergedWeightSet!==null&&Le(e.mergedWeightSet,l)&&(u=!0),u&&o.weightSet.set(l,!0)}}const c={node:s,edge:e.edgeValues??r.remap};return o.nodeColumns=n.nodeColumns.map(l=>l.gather(t.origin,Ma(l,c))),o.edgeColumns=n.edgeColumns.map(l=>l.gather(r.origin,Ma(l,c))),o.extensions=n.extensions.map(l=>({name:l.name,rowCount:l.rowCount,columns:l.columns.map(u=>u.gather(null,Ma(u,c)))})),o}function Ma(n,e){switch(n.meta.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ua(n){return n instanceof Uint32Array||n instanceof Int32Array||n instanceof Float32Array||n instanceof Float64Array||n instanceof Uint8Array}function sb(n){if(typeof n!="object"||n===null||Array.isArray(n)||Ua(n))return!1;const e=n;return typeof e.dtype=="string"&&typeof e.meta=="object"&&typeof e.length=="number"}function ib(n){return n.mutations}function Vs(n){n.sealed=!0}function ab(n){it(n);for(const e of Sa(n))it(e)}class wn{constructor(e){this.mutations=0,this.sealed=!1;const{domain:t,rowCount:r}=e;if(!(Number.isInteger(r)&&r>=0))throw new P("E_COLUMN_LENGTH",`invalid row count ${r} for a ${t} table`,{domain:t,found:r});this.domain=t,this.rowCount=r,this.columns=new Map;for(const o of e.columns){const{name:s}=o.meta;if(this.columns.has(s))throw new P("E_COLUMN_EXISTS",`column "${s}" is declared twice`,{column:s});this.checkColumn(s,o),this.checkRole(s,o.meta.role,!1),this.columns.set(s,o),ab(o)}}names(){return[...this.columns.keys()]}has(e){return this.columns.has(e)}get(e){return this.columns.get(e)??null}require(e){const t=this.columns.get(e);if(t===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${this.domain} column named "${e}"`,{column:e,domain:this.domain});return t}typed(e,t){const r=this.columns.get(e);return r?.dtype!==t?null:r}requireTyped(e,t){const r=this.require(e);if(r.dtype!==t)throw new P("E_COLUMN_TYPE",`column "${e}" is ${r.dtype}, expected ${t}`,{column:e,expected:t,found:r.dtype});return r}byRole(e){for(const t of this.columns.values())if(t.meta.role===e)return t;return null}value(e,t){return this.require(e).value(t)}isSet(e,t){return this.require(e).isSet(t)}set(e,t,r,o){this.assertWritable(e);const s=r??{};let i;if(Ua(t)){const c=zt("adopt",o?.adopt,["copy","strict"])??"copy";i=Ey(this.domain,this.rowCount,e,t,s,c)}else if(Array.isArray(t))i=xa(this.domain,this.rowCount,e,t,s);else if(sb(t)){if(!gy(t))throw new P("E_COLUMN_TYPE",`column "${e}": not a Column of this package`,{column:e,reason:"foreign column"});i=this.adoptColumn(e,t,r),i!==t&&N0(t)>0&&Gn(i)}else throw new P("E_COLUMN_TYPE",`column "${e}": unsupported data (${typeof t})`,{column:e,found:typeof t});this.checkRole(e,i.meta.role,o?.replaceRole??!1);const a=this.columns.get(e);if(a!==i&&(it(i),a!==t))for(const c of Sa(i))it(c);return this.columns.set(e,i),this.mutations++,i}remove(e){this.assertWritable(e);const t=this.columns.delete(e);return t&&this.mutations++,t}rename(e,t){this.assertWritable(e);const r=this.require(e);if(e===t)return;if(this.columns.has(t))throw new P("E_COLUMN_EXISTS",`cannot rename "${e}": a column named "${t}" exists`,{column:t});const o=Xu(r,ht(t,this.domain,Sn(r.meta)));it(o),Fr(r)&&Gn(o);const s=[...this.columns.entries()];this.columns.clear();for(const[i,a]of s)i===e?this.columns.set(t,o):this.columns.set(i,a);this.mutations++}gpuView(e){return py(this.require(e))}clone(){return new wn({domain:this.domain,rowCount:this.rowCount,columns:[...this.columns.values()]})}[Symbol.iterator](){return this.columns.values()}adoptColumn(e,t,r){this.checkColumn(e,t);const{meta:o}=t;if(r===void 0&&o.name===e&&o.domain===this.domain)return t;const i={...Sn(o),...r};return r?.fill===void 0&&(i.fill=o.fill),Xu(t,ht(e,this.domain,i))}assertWritable(e){if(this.sealed)throw new P("E_FROZEN",`the ${this.domain} table is sealed: its column set cannot change (column "${e}")`,{domain:this.domain,column:e})}checkColumn(e,t){if(t.length!==this.rowCount)throw new P("E_COLUMN_LENGTH",`column "${e}" has ${t.length} rows; the ${this.domain} table has ${this.rowCount}`,{column:e,expected:this.rowCount,found:t.length})}checkRole(e,t,r){if(t!==null){for(const[o,s]of this.columns)if(o!==e&&s.meta.role===t){if(!r)throw new P("E_DUPLICATE_ROLE",`role "${t}" is already held by column "${o}" in the ${this.domain} table`,{role:t,column:e,holder:o});this.columns.delete(o);return}}}}function ld(n,e){const t=n.clone();for(const r of Object.keys(e)){const o=e[r];Ua(o)?t.set(r,o):t.set(r,o.data,o.decl)}return t}function cb(n,e){const{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":return n.meta.components===1?n.data[e]:Array.from(n.data.subarray(e*n.meta.components,(e+1)*n.meta.components)).join(",");case"bool":return Le(n.data,e);case"dict":return n.codes[e];case"string":return n.valueAt(e);case"list":return JSON.stringify(n.sliceOf(e));case"json":return JSON.stringify(n.values[e]);default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function ud(n){if(!n.meta.unique)return;const e=new Map;for(let t=0;t<n.length;t++){if(!n.isSet(t))continue;const r=cb(n,t),o=e.get(r);if(o!==void 0){const s=n.meta.domain==="edge"?"E_DUPLICATE_EDGE_ID":"E_DUPLICATE_ID";throw new P(s,`column "${n.meta.name}" is unique but rows ${o} and ${t} hold the same value`,{column:n.meta.name,domain:n.meta.domain,rows:[o,t],value:n.value(t)})}e.set(r,t)}}function lb(n){for(const e of n)ud(e)}function js(n){return new P("E_COLUMN_TYPE",`column ${JSON.stringify(n.meta.name)} of dtype ${n.dtype} cannot hold edge ids`,{column:n.meta.name,dtype:n.dtype,reason:"edge id dtype"})}function ub(n,e){switch(n.dtype){case"string":return n.valueAt(e);case"dict":return n.dictionary[n.codes[e]];case"f32":case"f64":case"i32":case"u32":case"u8":return n.data[e*n.meta.components];case"bool":case"list":case"json":throw js(n);default:throw js(n)}}function dd(n){switch(n.dtype){case"string":case"dict":case"f32":case"f64":case"i32":case"u32":case"u8":return!0;case"bool":case"list":case"json":return!1;default:return!1}}function db(n){if(!dd(n))throw js(n);const e=new Map,t=n.length;for(let r=0;r<t;r++){if(!n.isSet(r))continue;const o=ub(n,r);e.has(o)||e.set(o,r)}return e}class fb{constructor(e){if(!dd(e))throw js(e);this.column=e,this.map=null,this.builtVersion=-1}get built(){return this.map!==null&&this.builtVersion===this.column.version}get size(){return this.ensure().size}indexOf(e){const t=this.ensure().get(e);return t===void 0?x:t}has(e){return this.ensure().has(e)}ensure(){const{version:e}=this.column;return(this.map===null||this.builtVersion!==e)&&(this.map=db(this.column),this.builtVersion=e),this.map}}const Ho=["rowPtr","colIdx","weights","arcToEdge","edgeToArc"];function hb(n){const e=n.identity?0:n.arcCount,t=n.identity?0:n.edgeCount;return[4*(n.nodeCount+1),4*n.arcCount,n.weighted?4*n.arcCount:0,4*e,4*t]}function gb(n){return{rowPtr:new Uint32Array(n.nodeCount+1),colIdx:new Uint32Array(n.arcCount),weights:n.weighted?new Float32Array(n.arcCount):null,arcToEdge:n.identity?null:new Uint32Array(n.arcCount),edgeToArc:n.identity?null:new Uint32Array(n.edgeCount),arena:null}}function fd(n){const e=hb(n),t=V0(e,ft),r=new ArrayBuffer(t.byteLength),o={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let s=0;for(let l=0;l<Ho.length;l++){const u=t.offsets[l];if(u===null)continue;const d=Object.freeze({byteOffset:u,byteLength:e[l]});o[Ho[l]]=d,l<=2&&(s=u+e[l])}const i=(l,u)=>{const d=o[l];return d===null?new Uint32Array(0):new Uint32Array(r,d.byteOffset,u)};let a=null;if(n.weighted){const l=o.weights;a=l===null?new Float32Array(0):new Float32Array(r,l.byteOffset,n.arcCount)}const c=Object.freeze({buffer:r,byteOffset:0,byteLength:t.byteLength,alignment:ft,segments:Object.freeze(o),hotByteLength:s});return{rowPtr:i("rowPtr",n.nodeCount+1),colIdx:i("colIdx",n.arcCount),weights:a,arcToEdge:n.identity?null:i("arcToEdge",n.arcCount),edgeToArc:n.identity?null:i("edgeToArc",n.edgeCount),arena:c}}function wb(n,e){return e?fd(n):gb(n)}function pb(n){return{nodeCount:n.rowPtr.length-1,arcCount:n.colIdx.length,edgeCount:n.edgeToArc===null?n.colIdx.length:n.edgeToArc.length,weighted:n.weights!==null,identity:n.arcToEdge===null}}function mb(n){const e=fd(pb(n));return e.rowPtr.set(n.rowPtr),e.colIdx.set(n.colIdx),e.weights!==null&&n.weights!==null&&e.weights.set(n.weights),e.arcToEdge!==null&&n.arcToEdge!==null&&e.arcToEdge.set(n.arcToEdge),e.edgeToArc!==null&&n.edgeToArc!==null&&e.edgeToArc.set(n.edgeToArc),e}function Fa(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<r?o=i+1:s=i}return o}function hd(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<=r?o=i+1:s=i}return o}function yb(n,e,t,r){const o=n[t+1],s=Fa(e,n[t],o,r);return s<o&&e[s]===r?s:x}function qs(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r),a=hd(e,i,s,r);return[i,a]}function gd(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r);return hd(e,i,s,r)-i}function bb(n,e){let t=0,r=n.length;for(;t<r;){const o=t+Math.floor((r-t)/2);n[o]<=e?t=o+1:r=o}return t-1}function vb(n,e,t){return gd(n,e,t,t)}const wd=1024,pd=32,Ab=1;function Ba(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return e}class Ko{constructor(e,t,r,o,s){this.source=e,this.directed=e.directed,this.nodeCount=e.nodeCount,this.arcCount=e.arcCount,this.rowPtr=t,this.colIdx=r,this.weights=o,this.fwdArcCache=s,this.fwdArcIsIdentity=s===null,this.arcToEdgeCache=null,this.arcToEdgeOwned=!1}get fwdArc(){return this.fwdArcCache??=Ba(this.arcCount),this.fwdArcCache}get arcToEdge(){if(this.arcToEdgeCache===null)if(this.fwdArcIsIdentity)this.arcToEdgeCache=this.source.arcToEdge;else if(this.source.flags.arcToEdgeIsIdentity)this.arcToEdgeCache=this.fwdArc;else{const{fwdArc:e}=this,t=this.source.arcToEdge,r=new Uint32Array(this.arcCount);for(let o=0;o<r.length;o++)r[o]=t[e[o]];this.arcToEdgeCache=r,this.arcToEdgeOwned=!0}return this.arcToEdgeCache}get ownedByteLength(){let e=0;return this.directed&&(e+=this.rowPtr.byteLength+this.colIdx.byteLength,this.weights!==null&&(e+=this.weights.byteLength)),this.fwdArcCache!==null&&(e+=this.fwdArcCache.byteLength),this.arcToEdgeOwned&&this.arcToEdgeCache!==null&&(e+=this.arcToEdgeCache.byteLength),e}materialised(){const e={rowPtr:this.rowPtr,colIdx:this.colIdx};return this.weights!==null&&(e.weights=this.weights),this.fwdArcCache!==null&&(e.fwdArc=this.fwdArcCache),this.arcToEdgeCache!==null&&(e.arcToEdge=this.arcToEdgeCache),e}}function Eb(n){const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o,weights:s}=n;if(!n.directed)return new Ko(n,r,o,s,null);const i=new Uint32Array(e+1);for(let d=0;d<t;d++)i[o[d]+1]++;for(let d=0;d<e;d++)i[d+1]+=i[d];const a=new Uint32Array(t),c=new Uint32Array(t),l=s===null?null:new Float32Array(t),u=i.slice(0,e);for(let d=0;d<e;d++){const f=r[d+1];for(let h=r[d];h<f;h++){const g=o[h],w=u[g]++;a[w]=d,c[w]=h,l!==null&&s!==null&&(l[w]=s[h])}}return new Ko(n,i,a,l,c)}function md(n,e,t){const r=new Uint32Array(t);for(let o=0;o<e;o++){const s=n[o+1];for(let i=n[o];i<s;i++)r[i]=o}return r}function _b(n){return yd(n,md(n.rowPtr,n.nodeCount,n.arcCount))}function yd(n,e){return Object.freeze({src:e,dst:n.colIdx,weights:n.weights,get arcToEdge(){return n.arcToEdge}})}function bd(n){const{nodeCount:e,edgeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;if(n.flags.arcToEdgeIsIdentity)return za(n,md(o,e,r),s,i);const{arcToEdge:a,edgeToArc:c}=n,l=new Uint32Array(t),u=new Uint32Array(t);for(let f=0;f<e;f++){const h=o[f+1];for(let g=o[f];g<h;g++){const w=a[g];c[w]===g&&(l[w]=f,u[w]=s[g])}}let d=null;if(i!==null){d=new Float32Array(t);for(let f=0;f<t;f++)d[f]=i[c[f]]}return za(n,l,u,d)}function za(n,e,t,r){return Object.freeze({src:e,dst:t,weights:r,get arc(){return n.edgeToArc}})}function Ar(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++)t[r]=n[r+1]-n[r];return t}function Ib(n,e){const t=new Uint32Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function vd(n,e,t){const r=new Float64Array(t);for(let o=0;o<t;o++){const s=n[o+1];let i=0;for(let a=n[o];a<s;a++)i+=e[a];r[o]=i}return r}function Ga(n){return new Float64Array(n)}function kb(n,e){const t=new Float64Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function Sb(n){const{weights:e,edgeCount:t}=n;if(e===null)return t;let r=0;if(n.flags.arcToEdgeIsIdentity){for(let s=0;s<e.length;s++)r+=e[s];return r}const{edgeToArc:o}=n;for(let s=0;s<t;s++)r+=e[o[s]];return r}function Pb(n){const{nodeCount:e,rowPtr:t,colIdx:r,selfLoopCount:o}=n,s=new Uint32Array(e),i=new Uint32Array(o);let a=0;for(let c=0;c<e;c++){const[l,u]=qs(t,r,c,c);s[c]=u-l;for(let d=l;d<u&&a<o;d++)i[a++]=d}return{selfLoopArcs:i,selfLoopsPerNode:s}}function xb(n,e){const{weights:t,nodeCount:r,rowPtr:o,colIdx:s}=n;if(t===null)return Ga(e.selfLoopsPerNode);const i=new Float64Array(r);for(let a=0;a<r;a++){if(e.selfLoopsPerNode[a]===0)continue;const[c,l]=qs(o,s,a,a);let u=0;for(let d=c;d<l;d++)u+=t[d];i[a]=u}return i}function Cb(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant I7 violated: arc ${t} in row ${n} targeting ${e} has no mate in row ${e}`,{invariant:"I7",row:n,arc:t,target:e})}function Nb(n){if(n.directed)throw new P("E_DIRECTED","mate() is defined for undirected snapshots only",{directed:!0});const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o}=n,s=new Uint32Array(t),i=r.slice(0,e);for(let a=0;a<e;a++){const c=r[a+1];let l=i[a];for(;l<c;){const u=o[l];let d=l+1;for(;d<c&&o[d]===u;)d++;const f=d-l;if(u===a)for(let h=0;h<f;h++)s[l+h]=l+h;else{const h=i[u];if(u<a||h+f>r[u+1]||o[h]!==a||o[h+f-1]!==a)throw Cb(a,u,l);for(let g=0;g<f;g++)s[l+g]=h+g,s[h+g]=l+g;i[u]=h+f}l=d}i[a]=c}return s}function Ad(n,e){const t=Ar(n,e);let r=0;for(let d=0;d<e;d++)t[d]>r&&(r=t[d]);const o=new Uint32Array(r+1);for(let d=0;d<e;d++)o[t[d]]++;let s=0;for(let d=r;d>=0;d--){const f=o[d];o[d]=s,s+=f}const i=new Uint32Array(e);let a=0,c=0,l=0;for(let d=0;d<e;d++){const f=t[d];i[o[f]++]=d,f>=wd?a++:f>=pd?c++:f>=Ab&&l++}const u=new Uint32Array([0,a,a+c,a+c+l,e]);return Object.freeze({perm:i,segmentOffsets:u})}function Tb(n,e){if(!n.directed)return!0;const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;for(let u=0;u<=t;u++)if(o[u]!==e.rowPtr[u])return!1;const a=e.colIdx;for(let u=0;u<r;u++)if(s[u]!==a[u])return!1;const c=e.weights;if(i===null||c===null)return!0;if(!n.flags.multigraph){for(let u=0;u<r;u++)if(i[u]!==c[u])return!1;return!0}let l=0;for(;l<r;){let u=l+1;for(;u<r&&s[u]===s[l]&&u<o[Ob(o,t,l)+1];)u++;if(u-l===1){if(i[l]!==c[l])return!1}else if(!$b(i,c,l,u))return!1;l=u}return!0}function Ob(n,e,t){let r=0,o=e;for(;o-r>1;){const s=r+o>>>1;n[s]<=t?r=s:o=s}return r}function $b(n,e,t,r){const o=n.slice(t,r).sort(),s=e.slice(t,r).sort();for(let i=0;i<o.length;i++)if(o[i]!==s[i]&&!(Number.isNaN(o[i])&&Number.isNaN(s[i])))return!1;return!0}function Rb(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.ownedByteLength:0;case"coo":return t.src.byteLength;case"edgeList":{const r=t;let o=r.src.byteLength;return r.dst!==n.colIdx&&(o+=r.dst.byteLength),r.weights!==null&&r.weights!==n.weights&&(o+=r.weights.byteLength),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return t.byteLength;case"degreeOrder":case"reverseDegreeOrder":{const r=t;return r.perm.byteLength+r.segmentOffsets.byteLength}case"totalWeight":case"symmetric":return 0;default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Wa(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.materialised():{};case"coo":return{src:t.src};case"edgeList":{const r=t,o={src:r.src};return r.dst!==n.colIdx&&(o.dst=r.dst),r.weights!==null&&r.weights!==n.weights&&(o.weights=r.weights),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return{data:t};case"degreeOrder":case"reverseDegreeOrder":{const r=t;return{perm:r.perm,segmentOffsets:r.segmentOffsets}}case"totalWeight":case"symmetric":return{};default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Ed(n,e){return n instanceof Float64Array?new Float64Array(e):n instanceof Float32Array?new Float32Array(e):n instanceof Int32Array?new Int32Array(e):new Uint32Array(e)}function Db(n,e,t,r){const{edgeCount:o,arcCount:s}=n;if(zt("reducer",t,["first","sum","max","min"]),e.length!==s)throw new P("E_COLUMN_LENGTH",`perArc has ${e.length} entries, expected ${s}`,{expected:s,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const i=Ed(e,o),{edgeToArc:a,arcToEdge:c}=n;for(let l=0;l<o;l++)i[l]=e[a[l]];switch(t){case"first":break;case"sum":for(let l=0;l<s;l++){const u=c[l];a[u]!==l&&(i[u]+=e[l])}break;case"max":for(let l=0;l<s;l++){const u=c[l];e[l]>i[u]&&(i[u]=e[l])}break;case"min":for(let l=0;l<s;l++){const u=c[l];e[l]<i[u]&&(i[u]=e[l])}break;default:{const l=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(l)}`,{reducer:l})}}return i}function Va(n,e,t){const{edgeCount:r,arcCount:o}=n;if(e.length!==r)throw new P("E_COLUMN_LENGTH",`perEdge has ${e.length} entries, expected ${r}`,{expected:r,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const s=t??Ed(e,o),{arcToEdge:i}=n;for(let a=0;a<o;a++)s[a]=e[i[a]];return s}function ie(n,e,t={}){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function Lb(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Mb(n,e,t){let r=0;for(let o=0;o<t;o++){const s=n[o+1];for(let i=n[o];i<s;i++)e[i]===o&&r++}return r}function qr(n){for(let e=0;e<n.length;e++)if(n[e]!==e)return!1;return!0}function _d(n){const{directed:e,nodeCount:t,rowPtr:r,colIdx:o,weights:s,arcToEdge:i}=n;let a=!0,c=!0,l=!0;if(s!==null)for(let u=0;u<s.length;u++){const d=s[u];d!==1&&(a=!1),d>=0||(c=!1),Number.isFinite(d)||(l=!1)}return{multigraph:Lb(r,o,t),hasSelfLoops:n.selfLoopCount>0,arcToEdgeIsIdentity:e&&(i===null||qr(i)),weighted:s!==null,allWeightsOne:a,nonNegativeWeights:c,finiteWeights:l}}function Ub(n){const{rowPtr:e,colIdx:t,nodeCount:r,arcCount:o}=n;if(e.length!==r+1)throw ie("I1",`rowPtr has ${e.length} entries, expected ${r+1}`,{expected:r+1,found:e.length});if(e[0]!==0)throw ie("I1",`rowPtr[0] is ${e[0]}, expected 0`,{row:0,found:e[0]});for(let s=0;s<r;s++)if(e[s+1]<e[s])throw ie("I1",`rowPtr decreases at row ${s}: ${e[s]} -> ${e[s+1]}`,{row:s});if(e[r]!==o||t.length!==o)throw ie("I1",`rowPtr[${r}] = ${e[r]}, colIdx.length = ${t.length}, arcCount = ${o}`,{row:r,found:e[r],expected:o,colIdxLength:t.length})}function Fb(n){const{colIdx:e,nodeCount:t}=n;for(let r=0;r<e.length;r++)if(e[r]>=t)throw ie("I2",`colIdx[${r}] = ${e[r]} is not below nodeCount ${t}`,{arc:r,found:e[r]})}function Bb(n){const e=[["nodeCount",n.nodeCount],["edgeCount",n.edgeCount],["arcCount",n.arcCount],["selfLoopCount",n.selfLoopCount]];for(const[t,r]of e)if(!Number.isInteger(r)||r<0||r>Te)throw ie("I3",`${t} = ${r} is not an integer in [0, MAX_COUNT]`,{count:t,found:r});if(n.edgeCount>n.arcCount)throw ie("I3",`edgeCount ${n.edgeCount} exceeds arcCount ${n.arcCount}`,{edgeCount:n.edgeCount,arcCount:n.arcCount});if(n.selfLoopCount>n.edgeCount)throw ie("I3",`selfLoopCount ${n.selfLoopCount} exceeds edgeCount ${n.edgeCount}`,{selfLoopCount:n.selfLoopCount,edgeCount:n.edgeCount})}function zb(n){const{rowPtr:e,colIdx:t,nodeCount:r}=n,s=n.flags.arcToEdgeIsIdentity?null:n.arcToEdge;for(let i=0;i<r;i++){const a=e[i+1];for(let c=e[i]+1;c<a;c++){if(t[c]<t[c-1])throw ie("I4",`row ${i} is not sorted at arc ${c}`,{row:i,arc:c});if(t[c]===t[c-1]&&s!==null&&s[c]<=s[c-1])throw ie("I4",`parallel arcs ${c-1} and ${c} in row ${i} are not in edge order`,{row:i,arc:c})}}}function Gb(n){const{arcCount:e,edgeCount:t}=n;if(n.flags.arcToEdgeIsIdentity){if(!n.directed||e!==t)throw ie("I5","identity permutation claimed on a snapshot where it cannot hold",{directed:n.directed,arcCount:e,edgeCount:t});return}const{arcToEdge:r,edgeToArc:o}=n;if(r.length!==e)throw ie("I5",`arcToEdge has ${r.length} entries, expected ${e}`,{expected:e,found:r.length});if(o.length!==t)throw ie("I5",`edgeToArc has ${o.length} entries, expected ${t}`,{expected:t,found:o.length});for(let s=0;s<e;s++)if(r[s]>=t)throw ie("I5",`arcToEdge[${s}] = ${r[s]} is not below edgeCount ${t}`,{arc:s,found:r[s]});for(let s=0;s<t;s++)if(o[s]>=e)throw ie("I5",`edgeToArc[${s}] = ${o[s]} is not below arcCount ${e}`,{edge:s,found:o[s]})}function Wb(n){if(n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:e,edgeToArc:t,edgeCount:r}=n;for(let o=0;o<r;o++)if(e[t[o]]!==o)throw ie("I5",`arcToEdge[edgeToArc[${o}]] = ${e[t[o]]}, expected ${o}`,{edge:o,arc:t[o]})}function Id(n,e){if(!n.directed)return;const{arcCount:t,edgeCount:r}=n;if(t!==r)throw ie("I6",`directed snapshot has arcCount ${t} but edgeCount ${r}`,{arcCount:t,edgeCount:r});if(!e||n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:o}=n,s=new Uint8Array(r);for(let i=0;i<t;i++){const a=o[i];if(a>=r||s[a]===1)throw ie("I6",`edge ${a} appears more than once in arcToEdge (arc ${i})`,{arc:i,edge:a});s[a]=1}}function Vb(n){if(n.directed)return;const e=2*n.edgeCount-n.selfLoopCount;if(n.arcCount!==e)throw ie("I7",`undirected snapshot has arcCount ${n.arcCount}, expected 2 * ${n.edgeCount} - ${n.selfLoopCount} = ${e}`,{arcCount:n.arcCount,expected:e})}function jb(n){if(n.directed)return;const{nodeCount:e,arcCount:t,edgeCount:r,rowPtr:o,colIdx:s,weights:i,arcToEdge:a}=n,c=new Uint8Array(r);for(let u=0;u<t;u++){const d=a[u];if(c[d]===2)throw ie("I7",`edge ${d} appears more than twice in arcToEdge (arc ${u})`,{arc:u,edge:d});c[d]++}const l=o.slice(0,e);for(let u=0;u<e;u++){const d=o[u+1];let f=l[u];if(f<o[u]||f>d)throw ie("I7",`row ${u} was over-consumed by mates from earlier rows`,{row:u});for(;f<d;){const h=s[f];let g=f+1;for(;g<d&&s[g]===h;)g++;const w=g-f;if(h===u){for(let p=f;p<g;p++)if(c[a[p]]!==1)throw ie("I7",`self-loop edge ${a[p]} has more than one arc`,{row:u,arc:p,edge:a[p]})}else{if(h<u)throw ie("I7",`arc ${f} in row ${u} targets ${h} but row ${h} holds no mate`,{row:u,arc:f,target:h});const p=l[h],m=o[h+1];for(let y=0;y<w;y++){const b=f+y,v=p+y;if(v>=m||s[v]!==u)throw ie("I7",`arc ${b} in row ${u} targeting ${h} has no mate in row ${h}`,{row:u,arc:b,target:h});if(a[v]!==a[b])throw ie("I7",`arcs ${b} and ${v} should share a logical edge but hold ${a[b]} and ${a[v]}`,{row:u,arc:b,mate:v});if(c[a[b]]!==2)throw ie("I7",`edge ${a[b]} of arc ${b} does not have two arcs`,{row:u,arc:b,edge:a[b]});if(i!==null&&i[b]!==i[v])throw ie("I7",`arcs ${b} and ${v} carry different weights ${i[b]} and ${i[v]}`,{row:u,arc:b,mate:v})}if(p+w<m&&s[p+w]===u)throw ie("I7",`row ${h} holds more arcs to ${u} than row ${u} holds to ${h}`,{row:h,arc:p+w,target:u});l[h]=p+w}f=g}l[u]=d}}function qb(n){const{weights:e,arcCount:t}=n;if(e!==null&&e.length!==t)throw ie("I8",`weights has ${e.length} entries, expected ${t}`,{expected:t,found:e.length})}function Hb(n){const{weights:e}=n;if(e!==null){for(let t=0;t<e.length;t++)if(Number.isNaN(e[t]))throw ie("I8",`weights[${t}] is NaN`,{arc:t})}}function Kb(n){const e=Mb(n.rowPtr,n.colIdx,n.nodeCount);if(e!==n.selfLoopCount)throw ie("I9",`selfLoopCount is ${n.selfLoopCount} but ${e} loop arcs exist`,{reason:"selfLoopCount",expected:e,found:n.selfLoopCount});const t=_d({directed:n.directed,nodeCount:n.nodeCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:n.flags.arcToEdgeIsIdentity?null:n.arcToEdge,selfLoopCount:n.selfLoopCount}),r=["multigraph","hasSelfLoops","arcToEdgeIsIdentity","weighted","allWeightsOne","nonNegativeWeights","finiteWeights"];for(const o of r)if(n.flags[o]!==t[o])throw ie("I9",`flag ${o} is ${n.flags[o]} but the arrays say ${t[o]}`,{flag:o,found:n.flags[o],expected:t[o]})}function Yb(n,e,t){const r=n.segments[e];if(r===null)return;if(t===null)throw ie("I10",`arena names a segment for absent core array ${e}`,{array:e});const o=r.byteOffset-n.byteOffset;if(o<0||o%ft!==0||o+r.byteLength>n.byteLength)throw ie("I10",`arena segment ${e} at ${r.byteOffset} is not 256-aligned inside the arena`,{array:e,byteOffset:r.byteOffset});if(t.buffer!==n.buffer||t.byteOffset!==r.byteOffset||t.byteLength!==r.byteLength)throw ie("I10",`core array ${e} is not the view its arena segment describes`,{array:e,byteOffset:t.byteOffset,byteLength:t.byteLength})}function Xb(n,e){if(!j0(e))throw ie("I10",`core array ${n} is not 4-byte aligned`,{array:n,byteOffset:e.byteOffset,byteLength:e.byteLength});if(!pa(e))throw ie("I10",`core array ${n} is not a view over a plain ArrayBuffer`,{array:n,reason:"buffer"})}function Qb(n){const e=n.flags.arcToEdgeIsIdentity,t=[["rowPtr",n.rowPtr],["colIdx",n.colIdx],["weights",n.weights],["arcToEdge",e?null:n.arcToEdge],["edgeToArc",e?null:n.edgeToArc]];for(const[i,a]of t)a!==null&&Xb(i,a);const{arena:r}=n;if(r===null)return;const{alignment:o}=r;if(o!==ft)throw ie("I10",`arena alignment is ${o}, expected ${ft}`,{found:o});for(const[i,a]of t)Yb(r,i,a);let s=0;for(const i of["rowPtr","colIdx","weights"]){const a=r.segments[i];a!==null&&(s=a.byteOffset+a.byteLength-r.byteOffset)}if(r.hotByteLength!==s)throw ie("I10",`arena.hotByteLength is ${r.hotByteLength}, expected ${s}`,{reason:"hotByteLength",found:r.hotByteLength,expected:s})}function Jb(n){if(n.ids.size!==n.nodeCount)throw ie("I11",`ids.size is ${n.ids.size}, expected nodeCount ${n.nodeCount}`,{expected:n.nodeCount,found:n.ids.size})}function Zb(n){const{ids:e,nodeCount:t}=n;for(let r=0;r<t;r++){const o=e.idOf(r);if(typeof o=="number"&&Number.isNaN(o))throw ie("I11",`id of node ${r} is NaN`,{index:r});const s=e.indexOf(o);if(s!==r)throw ie("I11",`ids.indexOf(ids.idOf(${r})) is ${s}`,{index:r,found:s})}}function Ke(n,e,t,r={}){return ie("I12",`column "${e.meta.name}" of table ${n}: ${t}`,{table:n,column:e.meta.name,...r})}function kd(n,e,t,r,o){if(t.length!==r+1)throw Ke(n,e,`offsets has ${t.length} entries, expected ${r+1}`,{expected:r+1,found:t.length});if(t[0]!==0)throw Ke(n,e,`offsets[0] is ${t[0]}`,{row:0});for(let s=0;s<r;s++)if(t[s+1]<t[s])throw Ke(n,e,`offsets decrease at row ${s}`,{row:s});if(t[r]!==o)throw Ke(n,e,`offsets[${r}] is ${t[r]}, expected ${o}`,{row:r,found:t[r],expected:o})}function Sd(n,e,t,r,o,s){for(let i=0;i<t.length;i++){const a=t[i];if(a===x){const c=Math.floor(i/r);if(s!==void 0&&(s===null||Le(s,c)))throw Ke(n,e,`row ${c} is set but holds INVALID_INDEX`,{row:c});continue}if(a>=o)throw Ke(n,e,`value ${a} at ${i} is not below ${o}`,{row:Math.floor(i/r),found:a,expected:o})}}function Pd(n,e,t){switch(e.dtype){case"u32":Sd(n,e,e.data,e.meta.components,t,e.validity);return;case"list":{const{child:r}=e;if(r.dtype!=="u32")throw Ke(n,e,`refersTo list requires a u32 child, found ${r.dtype}`);Sd(n,e,r.data,1,t,void 0);return}default:throw Ke(n,e,`refersTo requires dtype u32, found ${e.dtype}`)}}function xd(n){switch(n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return[["data",n.data],["validity",n.validity]];case"dict":return[["codes",n.codes],["validity",n.validity]];case"string":return[["offsets",n.offsets],["utf8",n.utf8],["validity",n.validity]];case"list":return[["offsets",n.offsets],["validity",n.validity],...xd(n.child).map(([e,t])=>[`child.${e}`,t])];case"json":return[["validity",n.validity]];default:throw ie("I12",`unknown dtype ${n.dtype}`)}}function e1(n,e,t,r){if(e.length!==t)throw Ke(n,e,`has ${e.length} rows, expected ${t}`,{expected:t,found:e.length});const{validity:o,meta:s}=e,i=Math.ceil(t/32);if(o!==null&&o.length!==i)throw Ke(n,e,`validity has ${o.length} words, expected ${i}`,{expected:i,found:o.length});const a=o===null?0:t-gr(o,t);if(e.nullCount!==a)throw Ke(n,e,`nullCount is ${e.nullCount}, the validity bitmap says ${a}`,{expected:a,found:e.nullCount,reason:"nullCount"});for(const[u,d]of xd(e))if(d!==null&&!pa(d))throw Ke(n,e,`${u} is not a view over a plain ArrayBuffer`,{array:u,reason:"buffer"});const c=s.refersTo==="node"?r.nodeCount:r.edgeCount,{dtype:l}=e;switch(l){case"f32":case"f64":case"i32":case"u32":case"u8":{const u=t*s.components;if(e.data.length!==u)throw Ke(n,e,`data has ${e.data.length} values, expected ${u}`,{expected:u,found:e.data.length});s.refersTo!==null&&Pd(n,e,c);break}case"bool":if(e.data.length!==i)throw Ke(n,e,`bool data has ${e.data.length} words, expected ${i}`,{expected:i,found:e.data.length});break;case"dict":{if(e.codes.length!==t)throw Ke(n,e,`codes has ${e.codes.length} entries, expected ${t}`,{expected:t,found:e.codes.length});const u=e.dictionary.length;for(let d=0;d<t;d++)if(e.codes[d]>=u&&(o===null||Le(o,d)))throw Ke(n,e,`code ${e.codes[d]} at row ${d} is not below ${u}`,{row:d,found:e.codes[d]});break}case"string":kd(n,e,e.offsets,t,e.utf8.length);break;case"list":{const{child:u}=e;if(kd(n,e,e.offsets,t,u.length),u.validity!==null)throw Ke(n,e,"list child column has a validity bitmap");s.refersTo!==null&&Pd(n,e,c);break}case"json":if(e.values.length!==t)throw Ke(n,e,`values has ${e.values.length} entries, expected ${t}`,{expected:t,found:e.values.length});break;default:throw Ke(n,e,`unknown dtype ${String(l)}`)}}function Cd(n,e,t,r){for(const o of e)e1(n,o,t,r)}function t1(n){const e=[["nodes",n.nodes,n.nodeCount],["edges",n.edges,n.edgeCount],["graph",n.graph,1]];for(const[t,r,o]of e){if(r.rowCount!==o)throw ie("I12",`table ${t} has ${r.rowCount} rows, expected ${o}`,{table:t,expected:o,found:r.rowCount});Cd(t,r,o,n)}for(const[t,r]of n.extensions)Cd(`extensions[${t}]`,r,r.rowCount,n)}function n1(n){if(n.edges.rowCount!==n.edgeCount)throw ie("I13",`edge table has ${n.edges.rowCount} rows, expected edgeCount ${n.edgeCount}`,{expected:n.edgeCount,found:n.edges.rowCount})}function Nd(n){Bb(n),Ub(n),Fb(n),Gb(n),Id(n,!1),Vb(n),qb(n),Qb(n),Jb(n),n1(n),t1(n)}function r1(n){Nd(n),zb(n),Wb(n),Id(n,!0),Hb(n),jb(n),Kb(n),Zb(n);const e=[["nodes",n.nodes],["edges",n.edges],["graph",n.graph],...[...n.extensions].map(([t,r])=>[`extensions[${t}]`,r])];for(const[t,r]of e)for(const o of r)o1(t,o)}function o1(n,e){try{ud(e)}catch(t){throw t instanceof P&&(t.code==="E_DUPLICATE_ID"||t.code==="E_DUPLICATE_EDGE_ID")?Ke(n,e,t.message,{...t.details,reason:"unique",cause:t.code}):t}}class s1{constructor(e){const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,directed:i}=e,a=new Uint32Array(r),c=new Uint32Array(t),l=i?new Uint32Array(t):Ar(o,t);for(let u=0;u<t;u++){const d=o[u+1];for(let f=o[u];f<d;f++){a[f]=u;const h=s[f];h===u&&c[u]++,i&&l[h]++}}this.arcRow=a,this.loops=c,this.inDegree=l}inDegreePrefix(){const e=this.inDegree.length,t=new Uint32Array(e+1);for(let r=0;r<e;r++)t[r+1]=t[r]+this.inDegree[r];return t}}function Ot(n,e,t,r){return ie(r,`carried view ${n}.${e} disagrees with the core at ${t}`,{view:n,member:e,index:t,reason:"view"})}function Er(n,e,t,r,o){for(let s=0;s<r.length;s++)if(!Object.is(t[s],r[s])&&t[s]!==r[s])throw Ot(n,e,s,o)}function Td(n,e,t){const r=new Uint8Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s>=t.length||r[s]===1)throw Ot(n,e,o,"I2");r[s]=1}}function i1(n,e){Er("outDegree","data",e,Ar(n.rowPtr,n.nodeCount),"I2")}function a1(n,e){Er("inDegree","data",e,n.inDegree,"I2")}function c1(n,e,t){const r=Ar(n.rowPtr,n.nodeCount),o=n.directed?e.inDegree:e.loops;for(let s=0;s<r.length;s++)if(t[s]!==r[s]+o[s])throw Ot("degree","data",s,"I2")}function l1(n,e){Er("selfLoopsPerNode","data",e,n.loops,"I2")}function u1(n,e,t){const{colIdx:r,arcCount:o}=n;for(let s=0;s<t.length;s++){const i=t[s];if(i>=o||r[i]!==e.arcRow[i]||s>0&&i<=t[s-1])throw Ot("selfLoopArcs","data",s,"I2")}}function d1(n,e){Er("coo","src",e,n.arcRow,"I2")}function f1(n,e,t,r,o){const{edgeCount:s,edgeToArc:i,colIdx:a,arcCount:c}=n,l=n.weights;for(let u=0;u<s;u++){const d=i[u];if(d>=c||t[u]!==e.arcRow[d])throw Ot("edgeList","src",u,"I2");if(r!==null&&r[u]!==a[d])throw Ot("edgeList","dst",u,"I2");if(o!==null&&l!==null&&!Object.is(o[u],l[d]))throw Ot("edgeList","weights",u,"I17")}}function h1(n,e,t){const{arcCount:r,arcToEdge:o,colIdx:s}=n;for(let i=0;i<r;i++){const a=t[i],c=s[i]===e.arcRow[i];if(a>=r||t[a]!==i||o[a]!==o[i]||a===i!==c)throw Ot("mate","data",i,"I2")}}function g1(n,e,t,r){Td(n,"perm",t);let o=0,s=0,i=0;for(let c=0;c<t.length;c++){const l=e[t[c]];if(c>0){const u=e[t[c-1]];if(l>u||l===u&&t[c]<t[c-1])throw Ot(n,"perm",c,"I2")}l>=wd?o++:l>=pd?s++:l>=1&&i++}const a=[0,o,o+s,o+s+i,t.length];Er(n,"segmentOffsets",r,a,"I2")}function w1(n,e,t,r,o){const s=n[t-1],i=e[s];if(o<i||o===i&&r<=s)throw Ot("reverse","fwdArc",t,"I2")}function p1(n,e,t){const{nodeCount:r,arcCount:o,colIdx:s}=n,i=n.weights,{rowPtr:a,fwdArc:c}=t,l=t.colIdx,u=t.weights;if(a[0]!==0||a[r]!==o)throw Ot("reverse","rowPtr",0,"I2");Er("reverse","rowPtr",a,e.inDegreePrefix(),"I2"),Td("reverse","fwdArc",c);for(let d=0;d<r;d++){const f=a[d+1];for(let h=a[d];h<f;h++){const g=c[h],w=e.arcRow[g];if(s[g]!==d||l[h]!==w)throw Ot("reverse","colIdx",h,"I2");if(h>a[d]&&w1(c,e.arcRow,h,g,w),u!==null&&i!==null&&!Object.is(u[h],i[g]))throw Ot("reverse","weights",h,"I17")}}}function m1(n,e,t){Er(n,"data",e,t,"I17")}const y1="@graphty/graph-format@8bb237cb7ec4",b1=new Set(["totalWeight","symmetric"]),v1=new TextEncoder;function A1(n=Eu){if(!n)throw new P("E_UNSUPPORTED","the wire format cannot be written on a big-endian host",{reason:"big-endian host"})}const Yo="$num",Od="$esc";function E1(n){return Number.isNaN(n)?{[Yo]:"NaN"}:n===1/0?{[Yo]:"Infinity"}:n===-1/0?{[Yo]:"-Infinity"}:Object.is(n,-0)?{[Yo]:"-0"}:n}function qn(n){if(typeof n=="number")return E1(n);if(Array.isArray(n))return n.map(e=>qn(e));if(kn(n)){const e=Object.keys(n),t={};for(const r of e)$d(t,r,qn(n[r]));return e.length===1&&(e[0]===Yo||e[0]===Od)?{[Od]:t}:t}return n}function $d(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}class ja{constructor(e,t=!1){this.buffers=[],this.copied=[],this.segments=[],this.bufferIndex=new Map,this.placed=new Map,this.cursor=0,this.mode=e,this.transfer=t}get regionLength(){return hr(this.cursor,ft)}indexOf(e){return this.bufferIndex.get(e)??null}ref(e,t,r=!1){if(r&&Gn(e.buffer),this.mode==="reference")return{buffer:this.bufferIndexOf(e.buffer),byteOffset:e.byteOffset,byteLength:e.byteLength,dtype:t,length:e.length};const o=`${this.bufferIndexOf(e.buffer)}:${e.byteOffset}:${e.byteLength}:${t}`,s=this.placed.get(o);if(s!==void 0)return s;const i=hr(this.cursor,ft);this.cursor=i+e.byteLength;const a={buffer:0,byteOffset:i,byteLength:e.byteLength,dtype:t,length:e.length};return this.placed.set(o,a),this.segments.push({view:e,ref:a}),a}finalise(){if(!(this.mode!=="reference"||!this.transfer))for(let e=0;e<this.buffers.length;e++){const t=this.buffers[e];Fr(t)&&(this.buffers[e]=t.slice(0),this.copied.push(e))}}bufferIndexOf(e){const t=this.bufferIndex.get(e);if(t!==void 0)return t;const r=this.buffers.length;return this.bufferIndex.set(e,r),this.buffers.push(e),r}}function qa(n){return n instanceof Uint32Array?"u32":n instanceof Int32Array?"i32":n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":"u8"}const Rd=new WeakMap,Dd=new WeakMap;function Ld(n,e){return n.offsets.length===e+1}function _1(n){const e=Rd.get(n);if(e!==void 0&&Ld(e,n.length))return e;const t=Do(n,n.length);return Rd.set(n,t),t}function I1(n){const e=Dd.get(n);if(e?.version===n.version&&Ld(e.encoded,n.length))return e.encoded;const t=new Array(n.length);for(let o=0;o<n.length;o++){const s=n.values[o];t[o]=s===void 0||!n.isSet(o)?"":JSON.stringify(qn(s))}const r=Do(t,t.length);return Dd.set(n,{version:n.version,encoded:r}),r}function Md(n,e,t){return{offsets:n.ref(e.offsets,"u32",t),utf8:n.ref(e.utf8,"utf8",t)}}function k1(n){return{name:n.name,domain:n.domain,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype,itemComponents:n.itemComponents,nullable:n.nullable,mutable:n.mutable,role:n.role,refersTo:n.refersTo,unique:n.unique,default:qn(n.default),fill:qn(n.fill),options:n.options===null?null:qn(n.options),origin:n.origin===null?null:{...n.origin},dynamic:n.dynamic,extra:qn(n.extra)}}function Ud(n,e,t){const r=t||Fr(e),o={meta:k1(e.meta),data:null,validity:e.validity===null?null:n.ref(e.validity,"u32",r),nullCount:e.nullCount,dictionary:null,strings:null,offsets:null,child:null,jsonText:null},{dtype:s}=e;switch(s){case"f32":case"f64":case"i32":case"u32":case"u8":o.data=n.ref(e.data,s,r);break;case"bool":o.data=n.ref(e.data,"u32",r);break;case"dict":o.data=n.ref(e.codes,"u32",r),o.dictionary=Md(n,_1(e.dictionary),r);break;case"string":o.strings={offsets:n.ref(e.offsets,"u32",r),utf8:n.ref(e.utf8,"utf8",r)};break;case"list":o.offsets=n.ref(e.offsets,"u32",r),o.child=Ud(n,e.child,r);break;case"json":o.jsonText=Md(n,I1(e),r);break;default:{const i=s;throw new P("E_UNSUPPORTED",`unknown dtype ${i}`,{dtype:i})}}return o}function Hs(n,e){const t=[],r=Fr(e);for(const o of e)t.push(Ud(n,o,r));return t}function S1(n,e){const{ids:t}=e;if(!(t instanceof Yt))throw new P("E_UNSUPPORTED","the snapshot's id map is not a NodeIdMap of this package",{reason:"foreign id map"});const r=zy(t),o=Fr(t);return{kind:r.kind,size:r.size,offset:r.offset,values:r.values===null?null:n.ref(r.values,qa(r.values),o),tags:r.tags===null?null:n.ref(r.tags,"u8",o),numbers:r.numbers===null?null:n.ref(r.numbers,"f64",o),offsets:r.offsets===null?null:n.ref(r.offsets,"u32",o),utf8:r.utf8===null?null:n.ref(r.utf8,"utf8",o)}}function P1(n){return{name:n.name,description:n.description,creator:n.creator,created:n.created,modified:n.modified,keywords:[...n.keywords],sourceFormat:n.sourceFormat,sourceVersion:n.sourceVersion,idType:n.idType,timeFormat:n.timeFormat,timeRepresentation:n.timeRepresentation,mode:n.mode,declaredMultigraph:n.declaredMultigraph,weightOrigin:n.weightOrigin===null?null:{...n.weightOrigin},extra:qn(n.extra)}}function x1(n,e,t){if(t===void 0||t.length===0)return null;const r={};let o=0;for(const s of new Set(t)){if(b1.has(s))continue;const i=_v(e,s);if(i===null)continue;const a={};let c=!1;for(const[l,u]of Object.entries(Wa(e,s,i))){const d=u;a[l]=n.ref(d,qa(d)),c=!0}c&&(r[s]=a,o++)}return o===0?null:r}function Ha(n,e,t,r=!0){A1();const o=n.flags.arcToEdgeIsIdentity,s={rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:o?null:n.arcToEdge,edgeToArc:o?null:n.edgeToArc},i={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null},a=e.ref(n.rowPtr,"u32");i.rowPtr=a;for(const p of Ho){const m=s[p];p!=="rowPtr"&&m!==null&&m.length>0&&(i[p]=e.ref(m,qa(m)))}const c=C1(n,e,i),l=S1(e,n),u=r?Hs(e,n.nodes):[],d=r?Hs(e,n.edges):[],f=r?Hs(e,n.graph):[],h=[];if(r)for(const[p,m]of n.extensions)h.push({name:p,rowCount:m.rowCount,columns:Hs(e,m)});const g=x1(e,n,t);return e.finalise(),{manifest:{format:la,wire:[zn,_u],producer:y1,formatVersion:Mr,directed:n.directed,counts:{nodes:n.nodeCount,edges:n.edgeCount,arcs:n.arcCount,selfLoops:n.selfLoopCount},flags:{...n.flags},core:{rowPtr:a,colIdx:i.colIdx,weights:i.weights,arcToEdge:i.arcToEdge,edgeToArc:i.edgeToArc},arena:c,ids:l,nodeColumns:u,edgeColumns:d,graphColumns:f,extensions:h,meta:P1(n.meta),views:g,copied:e.copied,label:n.label},layout:e}}function C1(n,e,t){if(e.mode==="container"){let s=0,i=0;for(const a of Ho){const c=t[a];c!==null&&(s=c.byteOffset+c.byteLength,(a==="rowPtr"||a==="colIdx"||a==="weights")&&(i=s))}return{buffer:0,byteOffset:0,byteLength:s,hotByteLength:i}}const{arena:r}=n;if(r===null)return null;const o=e.indexOf(r.buffer);return o===null?null:{buffer:o,byteOffset:r.byteOffset,byteLength:r.byteLength,hotByteLength:r.hotByteLength}}function N1(n,e={}){const t=e.transfer===!0,r=new ja("reference",t),{manifest:o}=Ha(n,r,e.includeViews,e.includeColumns!==!1);return t&&Fd.set(n,[...r.buffers]),{manifest:o,buffers:r.buffers}}const Fd=new WeakMap;function T1(n){const e=Fd.get(n);if(e!==void 0)return[...e];const t=new ja("reference",!1);return Ha(n,t,void 0,!0),t.buffers.filter(r=>!Fr(r))}function O1(n){return v1.encode(JSON.stringify(n))}const $1=new Set(["u32","i32","f32","f64","u8","utf8"]),R1=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),D1=new Set(["identity","dense","numeric","string","mixed"]),L1=new Set(["string","integer","mixed"]),M1=new Set(["integer","double","date","dateTime"]),U1=new Set(["interval","timestamp"]),F1=new Set(["static","dynamic","slice"]),Bd=new Set(["__proto__","constructor","prototype"]),zd="$num",Gd="$esc",Wd=256;function Hr(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):n===void 0?"undefined":`a ${typeof n}`}const B1="graphty.skippedColumns";function re(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function vt(n,e){if(!kn(n))throw re(e,"expected an object");return n}function Ks(n,e){if(!Array.isArray(n))throw re(e,"expected an array");return n}function Xo(n,e){if(typeof n!="string")throw re(e,"expected a string");return n}function Cn(n,e){return n==null?null:Xo(n,e)}function _r(n,e){if(typeof n!="boolean")throw re(e,"expected a boolean");return n}function z1(n,e){return n==null?null:_r(n,e)}function Nn(n,e){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>Te)throw re(e,`expected an integer in [0, ${Te}]`,{found:n});return n===0?0:n}function Ys(n,e,t){if(n==null)return null;if(typeof n!="string"||!t.has(n))throw re(e,`unexpected value ${Hr(n)}`,{found:n});return n}function Vd(n){return typeof n=="string"&&R1.has(n)}function Hn(n,e,t=0){if(t>Wd)throw re(e,`JSON nesting deeper than ${Wd}`,{reason:"nesting"});if(Array.isArray(n))return n.map((o,s)=>Hn(o,`${e}[${s}]`,t+1));if(!kn(n))return n;const r=Object.keys(n);if(r.length===1&&r[0]===zd){const o=n[zd];switch(o){case"NaN":return Number.NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;case"-0":return-0;default:throw re(e,`unknown number tag ${Hr(o)}`,{found:o})}}if(r.length===1&&r[0]===Gd){const o=n[Gd];if(!kn(o))throw re(e,"an escaped object must hold a plain object",{found:typeof o});return jd(o,e,t)}return jd(n,e,t)}function jd(n,e,t){const r={};for(const o of Object.keys(n)){if(Bd.has(o))throw re(e,`forbidden key "${o}"`,{key:o});$d(r,o,Hn(n[o],`${e}.${o}`,t+1))}return r}function G1(n){const e=[n];for(;e.length>0;){const t=e.pop();if(Array.isArray(t))for(const r of t)e.push(r);else if(typeof t=="object"&&t!==null)for(const r of Object.keys(t)){if(Bd.has(r))throw re("manifest",`forbidden key "${r}"`,{key:r});e.push(t[r])}}}function qd(n,e){let t;try{t=JSON.parse(n)}catch(r){throw re(e,`not valid JSON (${r instanceof Error?r.message:String(r)})`)}return G1(t),t}function W1(n,e){return{level:e,copy:!1,unknownColumns:"error"}}function Hd(n,e,t){return{byteLength:t,locate(r){return{buffer:n,byteOffset:e+r}},read(r,o){const s=new Uint8Array(new ArrayBuffer(Mo(o)),0,o);return s.set(new Uint8Array(n,e+r,o)),s}}}function V1(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function j1(n){switch(n){case"u32":case"i32":case"f32":return 4;case"f64":return 8;case"u8":case"utf8":return 1;default:{const e=n;throw re("dtype",`unknown wire dtype ${e}`,{dtype:e})}}}function Kd(n,e,t,r){switch(n){case"u32":return new Uint32Array(e,t,r);case"i32":return new Int32Array(e,t,r);case"f32":return new Float32Array(e,t,r);case"f64":return new Float64Array(e,t,r);case"u8":case"utf8":return new Uint8Array(e,t,r);default:{const o=n;throw re("dtype",`unknown wire dtype ${o}`,{dtype:o})}}}function Xs(n,e){const t=vt(n,e),{dtype:r}=t;if(typeof r!="string"||!$1.has(r))throw re(e,`unknown wire dtype ${Hr(r)}`,{found:r});const o=["buffer","byteOffset","byteLength","length"];for(const s of o){const i=t[s];if(typeof i!="number"||!Number.isInteger(i)||i<0)throw re(`${e}.${s}`,"expected a non-negative integer",{found:i})}return{buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,dtype:r,length:t.length}}function Ka(n,e){return n instanceof P&&(n.code.startsWith("E_COLUMN")||n.code==="E_DUPLICATE_ROLE")?new P("E_BAD_SERIALIZATION",`${e}: ${n.message}`,{ref:e,reason:n.message,cause:n.code,...n.details}):n instanceof Error?n:re(e,String(n))}class q1{constructor(e,t){this.ranges=[],this.skipped=[],this.regions=e,this.options=t}get structure(){return this.options.level!=="none"}get full(){return this.options.level==="full"}array(e,t,r,o){const s=Xs(e,t);if(s.dtype!==r)throw re(t,`expected dtype ${r}, found ${s.dtype}`,{expected:r,found:s.dtype});const i=this.regions[s.buffer];if(i===void 0)throw re(t,`buffer index ${s.buffer} is out of range (${this.regions.length} buffers)`,{found:s.buffer,buffers:this.regions.length});const a=j1(s.dtype);if(s.byteOffset%a!==0)throw re(t,`byteOffset ${s.byteOffset} is not a multiple of ${a}`,{byteOffset:s.byteOffset,elementSize:a});if(s.byteLength!==s.length*a)throw re(t,`byteLength ${s.byteLength} is not length ${s.length} * ${a}`,{byteLength:s.byteLength,length:s.length,elementSize:a});if(s.byteOffset+s.byteLength>i.byteLength)throw re(t,`range [${s.byteOffset}, ${s.byteOffset+s.byteLength}) exceeds the buffer`,{byteOffset:s.byteOffset,byteLength:s.byteLength,bufferByteLength:i.byteLength});const c=i.locate(s.byteOffset,s.byteLength);if(c!==null&&c.byteOffset%a===0)return this.ranges.push({buffer:c.buffer,start:c.byteOffset,end:c.byteOffset+s.byteLength,kind:o,path:t}),Kd(s.dtype,c.buffer,c.byteOffset,s.length);const l=i.read(s.byteOffset,s.byteLength);return Kd(s.dtype,l.buffer,0,s.length)}u32(e,t,r){return this.array(e,t,"u32",r)}utf8(e,t,r,o,s=!1){const i=vt(e,t),a=this.u32(i.offsets,`${t}.offsets`,o),c=this.array(i.utf8,`${t}.utf8`,"utf8",o);if(a.length===0)throw re(`${t}.offsets`,"a Utf8 store needs at least one offset");if((this.structure||s)&&ha(a,c,r??a.length-1,t),this.full){const l=Wn.fromEncoded(a,c).firstMalformedRow();if(l!==-1)throw re(t,`malformed UTF-8 in row ${l}`,{row:l})}return{offsets:a,utf8:c}}checkOverlaps(){const e=this.ranges.filter(t=>(t.kind==="core"||t.kind==="immutable")&&t.end>t.start);for(const t of this.ranges)if(!(t.kind!=="mutable"||t.end===t.start)){for(const r of e)if(r.buffer===t.buffer&&t.start<r.end&&r.start<t.end)throw re(t.path,`mutable column overlaps ${r.path}`,{overlaps:r.path})}}column(e,t,r,o,s){const i=vt(e,s),a=vt(i.meta,`${s}.meta`),c=Xo(a.name,`${s}.meta.name`);if(this.skipUnknownDtype(a,c,t,r,s))return null;const l=this.columnMeta(a,c,t,s),u=l.mutable?"mutable":"immutable",d=Gr(l,o,i.validity===null||i.validity===void 0?null:this.u32(i.validity,`${s}.validity`,u)),f=i.nullCount;switch(l.dtype){case"f32":case"f64":case"i32":case"u32":d.data=this.array(i.data,`${s}.data`,l.dtype,u);break;case"u8":{const g=this.array(i.data,`${s}.data`,"u8",u);d.data=Ds(g)?g:H0(g);break}case"bool":d.data=this.u32(i.data,`${s}.data`,u);break;case"dict":{d.data=this.u32(i.data,`${s}.data`,u);const g=this.utf8(i.dictionary,`${s}.dictionary`,null,u,!0);d.dictionary=fa(g.utf8,g.offsets,0,g.offsets.length-1);break}case"string":{const g=this.utf8(i.strings,`${s}.strings`,o,u);d.offsets=g.offsets,d.utf8=g.utf8;break}case"list":{const g=this.u32(i.offsets,`${s}.offsets`,u);if(g.length!==o+1)throw re(`${s}.offsets`,`expected ${o+1} offsets, found ${g.length}`,{expected:o+1,found:g.length});d.offsets=g;const w=this.column(i.child,t,r,g[o],`${s}.child`);if(w===null||w.dtype==="list")throw re(`${s}.child`,"a list column needs a non-list child column");d.child=w;break}case"json":d.values=this.jsonRows(i.jsonText,o,`${s}.jsonText`,u);break;default:{const g=l.dtype;throw re(`${s}.meta.dtype`,`unknown dtype ${g}`,{dtype:g})}}let h;try{h=Tt(d)}catch(g){throw Ka(g,s)}if(this.structure&&h.nullCount!==f)throw re(`${s}.nullCount`,`manifest says ${String(f)}, the bitmap says ${h.nullCount}`,{expected:h.nullCount,found:f});return h}skipUnknownDtype(e,t,r,o,s){const{dtype:i,itemDtype:a}=e;if(!(!Vd(i)||i==="list"&&!Vd(a)))return!1;const l=i==="list"?a:i;if(this.options.unknownColumns==="skip")return this.skipped.push({domain:r,table:o,name:t,dtype:String(l)}),!0;throw new P("E_UNSUPPORTED",`column "${t}" has unknown dtype ${String(l)}`,{dtype:l,column:t,ref:s})}columnMeta(e,t,r,o){const s=`${o}.meta`,i=(l,u)=>{const d=e[l];return d==null?void 0:u(d,`${s}.${l}`)},a=(l,u)=>{if(typeof l!="number")throw re(u,"expected a number",{found:l});return l},c={name:t,dtype:e.dtype,components:i("components",a),itemDtype:i("itemDtype",l=>l),itemComponents:i("itemComponents",a),nullable:i("nullable",_r),mutable:i("mutable",_r),role:i("role",Xo),refersTo:i("refersTo",l=>l),unique:i("unique",_r),default:Hn(e.default,`${s}.default`),fill:Hn(e.fill,`${s}.fill`),options:i("options",(l,u)=>Hn(l,u)),origin:i("origin",l=>l),dynamic:i("dynamic",_r),extra:i("extra",(l,u)=>Hn(l,u))};try{return ht(t,r,c)}catch(l){throw Ka(l,o)}}jsonRows(e,t,r,o){const s=this.utf8(e,r,t,o,!0),i=fa(s.utf8,s.offsets,0,t),a=new Array(t);for(let c=0;c<t;c++){const l=i[c];a[c]=l===""?void 0:Hn(qd(l,`${r}[${c}]`),`${r}[${c}]`)}return a}table(e,t,r,o,s){const i=Ks(e,s),a=[],c=new Set;for(let l=0;l<i.length;l++){const u=this.column(i[l],t,r,o,`${s}[${l}]`);if(u!==null){if(c.has(u.meta.name))throw re(`${s}[${l}].meta.name`,`column "${u.meta.name}" is declared twice`,{column:u.meta.name});c.add(u.meta.name),a.push(u)}}try{return new wn({domain:t,rowCount:o,columns:a})}catch(l){throw Ka(l,s)}}ids(e){const t=vt(e,"ids"),r=t.kind;if(typeof r!="string"||!D1.has(r))throw new P("E_UNSUPPORTED",`unknown id map kind ${Hr(r)}`,{kind:r,ref:"ids.kind"});const o=r,s=Nn(t.size,"ids.size"),i=t.offset??0;if(typeof i!="number")throw re("ids.offset","expected a number",{found:i});const c={kind:o,size:s,offset:o==="identity"?i:0,values:null,tags:null,numbers:null,offsets:null,utf8:null};switch(o){case"identity":break;case"dense":c.values=this.u32(t.values,"ids.values","immutable");break;case"numeric":c.values=this.array(t.values,"ids.values","f64","immutable");break;case"string":{c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}case"mixed":{c.tags=this.array(t.tags,"ids.tags","u8","immutable"),c.numbers=this.array(t.numbers,"ids.numbers","f64","immutable"),c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}default:{const l=o;throw new P("E_UNSUPPORTED",`unknown id map kind ${l}`,{kind:l})}}return $y(c,this.options.level)}views(e){const t=new Map;if(e==null)return t;const r=vt(e,"views");for(const o of Object.keys(r)){const s=vt(r[o],`views.${o}`),i=new Map;for(const a of Object.keys(s)){const c=`views.${o}.${a}`,l=Xs(s[a],c);i.set(a,this.array(l,c,l.dtype,"view"))}t.set(o,i)}return t}}function Xt(n,e,t,r,o,s){const i=`views.${e}.${t}`,a=n.get(t);if(a===void 0){if(s)throw re(i,"the carried view is missing this member");return null}if(!(a instanceof r))throw re(i,`expected ${r.name}, found ${a.constructor.name}`,{expected:r.name,found:a.constructor.name});if(a.length!==o)throw re(i,`expected ${o} entries, found ${a.length}`,{expected:o,found:a.length});return a}function Yd(n,e,t,r){return Xt(n,e,"data",t,r,!0)}function H1(n,e,t){let r=null;const o={snapshot:n,verify:t,facts:()=>(r??=new s1(n),r)};for(const[s,i]of e)Y1(s,n.directed)||X1(o,s,i)}const K1=new Set(["reverse","inDegree","weightedInDegree","reverseDegreeOrder"]);function Y1(n,e){return e?n==="mate":K1.has(n)}function X1(n,e,t){const{snapshot:r}=n;switch(e){case"reverse":Q1(n,t);break;case"coo":J1(n,t);break;case"edgeList":Z1(n,t);break;case"outDegree":Kr(n,"outDegree",t,r.nodeCount,o=>{i1(r,o)});break;case"degree":Kr(n,"degree",t,r.nodeCount,o=>{c1(r,n.facts(),o)});break;case"selfLoopsPerNode":Kr(n,"selfLoopsPerNode",t,r.nodeCount,o=>{l1(n.facts(),o)});break;case"inDegree":Kr(n,"inDegree",t,r.nodeCount,o=>{a1(n.facts(),o)});break;case"selfLoopArcs":Kr(n,"selfLoopArcs",t,r.selfLoopCount,o=>{u1(r,n.facts(),o)});break;case"mate":Kr(n,"mate",t,r.arcCount,o=>{h1(r,n.facts(),o)});break;case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":e2(n,e,t);break;case"degreeOrder":case"reverseDegreeOrder":t2(n,e,t);break}}function Xd(n,e,t){if(t!==null&&n.weights===null)throw re(`views.${e}.weights`,"weights carried for an unweighted snapshot")}function Q1(n,e){const{snapshot:t}=n,{nodeCount:r,arcCount:o}=t,s=Xt(e,"reverse","rowPtr",Uint32Array,r+1,!0),i=Xt(e,"reverse","colIdx",Uint32Array,o,!0),a=Xt(e,"reverse","fwdArc",Uint32Array,o,!0),c=Xt(e,"reverse","weights",Float32Array,o,t.weights!==null);Xd(t,"reverse",c);const l=new Ko(t,s,i,c,a);n.verify&&p1(t,n.facts(),l),Yr(t,"reverse",l)}function J1(n,e){const{snapshot:t}=n,r=Xt(e,"coo","src",Uint32Array,t.arcCount,!0);n.verify&&d1(n.facts(),r),Yr(t,"coo",yd(t,r))}function Z1(n,e){const{snapshot:t}=n,{edgeCount:r}=t,o=t.flags.arcToEdgeIsIdentity,s=Xt(e,"edgeList","src",Uint32Array,r,!0),i=Xt(e,"edgeList","dst",Uint32Array,r,!o),a=Xt(e,"edgeList","weights",Float32Array,r,t.weights!==null&&!o);Xd(t,"edgeList",a),n.verify&&f1(t,n.facts(),s,i,a),Yr(t,"edgeList",za(t,s,i??t.colIdx,a??t.weights))}function Kr(n,e,t,r,o){const s=Yd(t,e,Uint32Array,r);n.verify&&o(s),Yr(n.snapshot,e,s)}function e2(n,e,t){const{snapshot:r}=n,o=Yd(t,e,Float64Array,r.nodeCount);if(n.verify){m1(e,o,r[e]());return}Yr(r,e,o)}function t2(n,e,t){const{snapshot:r}=n,{nodeCount:o}=r,s=Xt(t,e,"perm",Uint32Array,o,!0),i=Xt(t,e,"segmentOffsets",Uint32Array,5,!0);if(n.verify){const a=e==="degreeOrder"?Ar(r.rowPtr,o):n.facts().inDegree;g1(e,a,s,i)}Yr(r,e,Object.freeze({perm:s,segmentOffsets:i}))}function n2(n){const e=vt(n,"core"),t=r=>{const o=e[r];return o==null?null:Xs(o,`core.${r}`)};return{rowPtr:Xs(e.rowPtr,"core.rowPtr"),colIdx:t("colIdx"),weights:t("weights"),arcToEdge:t("arcToEdge"),edgeToArc:t("edgeToArc")}}function r2(n,e,t,r){const o=n.u32(e.rowPtr,"core.rowPtr","core");let s;if(e.colIdx===null){if(t.arcs!==0)throw re("core.colIdx",`null although counts.arcs is ${t.arcs}`);s=new Uint32Array(0)}else s=n.u32(e.colIdx,"core.colIdx","core");let i=null;if(e.weights!==null){if(!r.weighted)throw re("core.weights","present although flags.weighted is false");i=n.array(e.weights,"core.weights","f32","core")}else if(r.weighted){if(t.arcs!==0)throw re("core.weights",`null although flags.weighted is true and counts.arcs is ${t.arcs}`);i=new Float32Array(0)}const a=r.arcToEdgeIsIdentity,c=(l,u,d)=>{if(l!==null){if(a)throw re(`core.${u}`,"present although flags.arcToEdgeIsIdentity is true");return n.u32(l,`core.${u}`,"core")}if(a)return null;if(d!==0)throw re(`core.${u}`,`null although the permutation is not the identity and the count is ${d}`);return new Uint32Array(0)};return{rowPtr:o,colIdx:s,weights:i,arcToEdge:c(e.arcToEdge,"arcToEdge",t.arcs),edgeToArc:c(e.edgeToArc,"edgeToArc",t.edges)}}function o2(n,e,t,r,o){if(e===null||t===null||t.length===0||!(e.buffer===r.buffer&&e.byteOffset>=r.byteOffset&&e.byteOffset+e.byteLength<=r.byteOffset+r.byteLength))return null;const i=e.byteOffset-r.byteOffset;if(i%ft!==0)throw re(`core.${n}`,`inside the arena at offset ${i}, not a multiple of ${ft}`,{byteOffset:i});if(t.buffer!==o.buffer||t.byteOffset!==o.byteOffset+i)throw re(`core.${n}`,"the arena describes a segment the array is not a view of");return Object.freeze({byteOffset:o.byteOffset+i,byteLength:e.byteLength})}function s2(n,e,t,r,o){if(n==null)return null;const s=vt(n,"arena"),i=Nn(s.buffer,"arena.buffer"),a=Nn(s.byteOffset,"arena.byteOffset"),c=Nn(s.byteLength,"arena.byteLength"),l=e[i];if(l===void 0)throw re("arena.buffer",`buffer index ${i} is out of range`,{found:i});if(a+c>l.byteLength)throw re("arena",`range [${a}, ${a+c}) exceeds the buffer`,{byteOffset:a,byteLength:c,bufferByteLength:l.byteLength});const u=l.locate(a,c);if(u===null)return null;const d={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let f=0;const h={buffer:i,byteOffset:a,byteLength:c},g=Ho;for(const w of g){const p=o2(w,t[w],r[w],h,u);p!==null&&(d[w]=p,(w==="rowPtr"||w==="colIdx"||w==="weights")&&(f=p.byteOffset-u.byteOffset+p.byteLength))}if(o&&s.hotByteLength!==f)throw re("arena.hotByteLength",`manifest says ${String(s.hotByteLength)}, the segments say ${f}`,{expected:f,found:s.hotByteLength});return Object.freeze({buffer:u.buffer,byteOffset:u.byteOffset,byteLength:c,alignment:ft,segments:Object.freeze(d),hotByteLength:f})}function i2(n){const e=vt(n,"flags"),t=r=>_r(e[r],`flags.${r}`);return{multigraph:t("multigraph"),hasSelfLoops:t("hasSelfLoops"),arcToEdgeIsIdentity:t("arcToEdgeIsIdentity"),weighted:t("weighted"),allWeightsOne:t("allWeightsOne"),nonNegativeWeights:t("nonNegativeWeights"),finiteWeights:t("finiteWeights")}}function a2(n,e){if(n==null)return null;const t=vt(n,e),r=o=>Cn(t[o],`${e}.${o}`);return{format:r("format"),id:r("id"),title:r("title"),type:r("type"),namespace:r("namespace")}}function c2(n){const e=vt(n,"meta"),t=e.keywords??[],r=Ks(t,"meta.keywords").map((s,i)=>Xo(s,`meta.keywords[${i}]`)),o=Hn(e.extra??{},"meta.extra");if(!kn(o))throw re("meta.extra","expected an object");return Object.freeze({name:Cn(e.name,"meta.name"),description:Cn(e.description,"meta.description"),creator:Cn(e.creator,"meta.creator"),created:Cn(e.created,"meta.created"),modified:Cn(e.modified,"meta.modified"),keywords:Object.freeze(r),sourceFormat:Cn(e.sourceFormat,"meta.sourceFormat"),sourceVersion:Cn(e.sourceVersion,"meta.sourceVersion"),idType:Ys(e.idType,"meta.idType",L1),timeFormat:Ys(e.timeFormat,"meta.timeFormat",M1),timeRepresentation:Ys(e.timeRepresentation,"meta.timeRepresentation",U1),mode:Ys(e.mode,"meta.mode",F1),declaredMultigraph:z1(e.declaredMultigraph,"meta.declaredMultigraph"),weightOrigin:a2(e.weightOrigin,"meta.weightOrigin"),extra:Object.freeze(o)})}function Qd(n){if(n.format!==la)throw re("format",`expected "${la}", found ${Hr(n.format)}`,{found:n.format});const e=Ks(n.wire,"wire"),t=e[0],r=e[1];if(typeof t!="number"||typeof r!="number"||!Number.isInteger(t)||!Number.isInteger(r))throw re("wire","expected [major, minor] integers",{found:n.wire});if(t!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${t} is not supported (reader: ${zn})`,{kind:"wire",found:t,supported:zn});if(n.formatVersion!==Mr)throw new P("E_UNSUPPORTED_VERSION",`formatVersion ${Hr(n.formatVersion)} is not supported (reader: ${Mr})`,{kind:"format",found:n.formatVersion,supported:Mr});return[t,r]}function l2(n,e,t,r){const o=vt(n,"manifest");Qd(o);const s=new q1(e,t),i=_r(o.directed,"directed"),a=vt(o.counts,"counts"),c={nodes:Nn(a.nodes,"counts.nodes"),edges:Nn(a.edges,"counts.edges"),arcs:Nn(a.arcs,"counts.arcs"),selfLoops:Nn(a.selfLoops,"counts.selfLoops")},l=i2(o.flags);if(l.arcToEdgeIsIdentity&&(!i||c.arcs!==c.edges))throw re("flags.arcToEdgeIsIdentity","set on an undirected graph or with arcs !== edges");const u=n2(o.core),d=r2(s,u,c,l),f=s2(o.arena,e,u,d,s.structure),h=s.ids(o.ids),g=s.table(o.nodeColumns??[],"node",null,c.nodes,"nodeColumns"),w=s.table(o.edgeColumns??[],"edge",null,c.edges,"edgeColumns"),p=s.table(o.graphColumns??[],"graph",null,1,"graphColumns"),m=new Map,y=Ks(o.extensions??[],"extensions");for(let I=0;I<y.length;I++){const k=`extensions[${I}]`,N=vt(y[I],k),C=Xo(N.name,`${k}.name`);if(m.has(C))throw re(`${k}.name`,`extension table "${C}" appears twice`,{table:C});const O=Nn(N.rowCount,`${k}.rowCount`);m.set(C,s.table(N.columns,"extension",C,O,`${k}.columns`))}let b=c2(o.meta??{});if(s.skipped.length>0){const I=Object.freeze(s.skipped.map(k=>Object.freeze({...k})));b=Object.freeze({...b,extra:Object.freeze({...b.extra,[B1]:I})})}const v=s.views(o.views);s.structure&&s.checkOverlaps();const A={label:Cn(o.label,"label"),serial:null,directed:i,nodeCount:c.nodes,edgeCount:c.edges,arcCount:c.arcs,selfLoopCount:c.selfLoops,rowPtr:d.rowPtr,colIdx:d.colIdx,weights:d.weights,arcToEdge:d.arcToEdge,edgeToArc:d.edgeToArc,flags:l,ids:h,nodes:g,edges:w,graph:p,extensions:m,meta:b,arena:f,checksum:!1},E=pf(A);return t.level==="full"?E.validate({level:"full"}):t.level==="structure"&&E.validate({level:"structure"}),t.level!=="full"&&H1(E,v,t.level==="structure"),E}const Tn=16,u2=new TextDecoder("utf-8",{fatal:!0});function Jd(n,e){const t=new ja("container"),{manifest:r}=Ha(n,t,e.includeViews,!0),o=O1(r);return{manifestBytes:o,regionStart:hr(Tn+o.byteLength,ft),segments:t.segments,regionLength:t.regionLength}}function Zd(n,e){n.set(ua,0);const t=new DataView(n.buffer,n.byteOffset,n.byteLength);t.setUint16(4,zn,!0),t.setUint16(6,_u,!0),new Uint32Array(n.buffer,n.byteOffset+8,1)[0]=da,t.setUint32(12,e,!0)}function ef(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function d2(n,e={}){const t=Jd(n,e),r=new Uint8Array(t.regionStart+t.regionLength);Zd(r,t.manifestBytes.byteLength),r.set(t.manifestBytes,Tn);for(const o of t.segments)r.set(ef(o.view),t.regionStart+o.ref.byteOffset);return r}function*f2(n){const e=new Uint8Array(n.regionStart);Zd(e,n.manifestBytes.byteLength),e.set(n.manifestBytes,Tn),yield e;for(const t of n.segments){if(t.ref.byteLength===0)continue;const r=new Uint8Array(hr(t.ref.byteLength,ft));r.set(ef(t.view)),yield r}}function h2(n,e={}){return f2(Jd(n,e))}function g2(n,e){if(e<Tn)throw re("header",`truncated: ${e} bytes, expected at least ${Tn}`,{byteLength:e});for(let a=0;a<ua.length;a++)if(n[a]!==ua[a])throw re("magic","not a GSNP container",{found:Array.from(n.subarray(0,4))});const t=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t.getUint16(4,!0),o=t.getUint16(6,!0);if(r!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${r} is not supported (reader: ${zn})`,{kind:"wire",found:r,supported:zn});const s=t.getUint32(8,Eu);if(s!==da)throw re("endianness",`probe reads 0x${s.toString(16)}; the container was written on another endianness`,{found:s,expected:da});const i=t.getUint32(12,!0);if(Tn+i>e)throw re("manifest",`truncated: ${i} manifest bytes declared, ${e} bytes in total`,{manifestLength:i,byteLength:e});return{major:r,minor:o,manifestLength:i}}function w2(n,e){let t;try{t=u2.decode(n)}catch{throw re("manifest","not valid UTF-8")}const r=qd(t,"manifest");if(typeof r!="object"||r===null||Array.isArray(r))throw re("manifest","expected an object");const o=r,[s,i]=Qd(o);if(s!==e.major||i!==e.minor)throw re("wire",`manifest says [${s}, ${i}], the header says [${e.major}, ${e.minor}]`,{found:[s,i],header:[e.major,e.minor]});return o}function p2(n,e){const t=W1(e,"full"),r=n instanceof Uint8Array?n:new Uint8Array(n),o=g2(r,r.byteLength),s=w2(r.subarray(Tn,Tn+o.manifestLength),o),i=hr(Tn+o.manifestLength,ft),a=Math.max(0,r.byteLength-i),{buffer:c}=r;let l;if(!t.copy&&!V1(c)&&r.byteOffset%8===0)l=Hd(c,r.byteOffset+i,a);else{const u=new Uint8Array(hr(a,ft));a>0&&u.set(r.subarray(i)),l=Hd(u.buffer,0,a)}return l2(s,[l],t)}function m2(n,e,t){for(let r=1;r<t;r++){const o=n[r],s=n[r-1];if(o<s||o===s&&e[r]<e[r-1])return!1}return!0}function y2(n,e){return new P("E_INVALID_WEIGHT",`edge ${n} has a NaN weight`,{edge:n,weight:e})}function b2(n,e,t){let r=1/0,o=-1/0;for(let s=0;s<e;s++){const i=Math.fround(n[s]);if(Number.isNaN(i))throw y2(s,n[s]);i<r&&(r=i,t[0]=i),i>o&&(o=i,t[1]=i)}}function v2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c&&s++}return s}function A2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c?s++:(r[a+1]++,o[c+1]++)}return s}function tf(n,e){for(let t=0;t<e;t++)n[t+1]+=n[t]}function E2(n,e,t,r){let o=!1;for(let s=0;s<t;s++){const i=e[s];r[s]=i,s>0&&n[s]===n[s-1]&&e[s-1]===i&&(o=!0)}return o}function _2(n,e,t,r,o){for(let s=0;s<t;s++){const i=2*r[e[s]]++;o[i]=n[s],o[i+1]=s}}function I2(n,e,t,r,o,s){for(let i=0;i<t;i++){const a=n[i],c=e[i],l=r[c]++;if(o[2*l]=a,o[2*l+1]=i,s[l>>>5]|=1<<(l&31),a!==c){const u=2*r[a]++;o[u]=c,o[u+1]=i}}}function k2(n,e,t,r,o,s){for(let i=0;i<n;i++){const a=2*e[i+1];for(let c=2*e[i];c<a;c+=2){const l=r[t[c]]++;o[l]=i,s[l]=t[c+1]}}}function S2(n,e,t,r,o,s){const{targetStart:i,byTarget:a,declared:c}=e;for(let l=0;l<n;l++){const u=i[l+1];for(let d=i[l];d<u;d++){const f=a[2*d+1],h=t[a[2*d]]++;r[h]=l,o[h]=f,(c[d>>>5]>>>(d&31)&1)===1&&(s[f]=h)}}}function P2(n,e){const t=n.length;for(let r=0;r<t;r++)e[n[r]]=r}function x2(n,e,t){const r=n.length;for(let o=0;o<r;o++)t[o]=e[n[o]]}function C2(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Ya(n,e){const{directed:t,nodeCount:r,edgeCount:o,src:s,dst:i}=n,a=n.weights;let c=!0,l=!0,u=!0;if(a!==null&&o>0){const k=new Float64Array([1/0,-1/0]);b2(a,o,k);const N=k[0],C=k[1];c=N===1&&C===1,l=N>=0,u=N>-1/0&&C<1/0}const d=new Uint32Array(r+1),f=new Uint32Array(r+1),h=t?v2(s,i,o,d,f):A2(s,i,o,d,f),g=t?o:2*o-h,w=t&&m2(s,i,o),p=wb({nodeCount:r,arcCount:g,edgeCount:o,weighted:a!==null,identity:w},e),{rowPtr:m,colIdx:y,weights:b,arcToEdge:v,edgeToArc:A}=p;tf(f,r),m.set(f);let E;if(w)E=E2(s,i,o,y),b!==null&&a!==null&&b.set(a.subarray(0,o));else if(v!==null&&A!==null){tf(d,r);const k=f;k.set(d);const N=new Uint32Array(2*g);let C=null;t?_2(s,i,o,k,N):(C=new Uint32Array(g+31>>>5),I2(s,i,o,k,N,C)),k.set(m),C===null?(k2(r,d,N,k,y,v),P2(v,A)):S2(r,{targetStart:d,byTarget:N,declared:C},k,y,v,A),b!==null&&a!==null&&x2(v,a,b),E=C2(m,y,r)}else throw new P("E_UNSUPPORTED","unreachable: a non-identity core without permutation arrays",{directed:t,arcCount:g});const I=Object.freeze({multigraph:E,hasSelfLoops:h>0,arcToEdgeIsIdentity:w,weighted:b!==null,allWeightsOne:c,nonNegativeWeights:l,finiteWeights:u});return{core:p,arcCount:g,selfLoopCount:h,flags:I}}function N2(n,e){return n instanceof Uint8Array?mr(e):n instanceof Uint32Array?new Uint32Array(e):n instanceof Int32Array?new Int32Array(e):n instanceof Float32Array?new Float32Array(e):new Float64Array(e)}function T2(n,e){const t=n.validity;let r=null,o=0;for(let s=0;s<e.length;s++){const i=e[s];i!==x&&(t===null||Le(t,i))||(r??=In(e.length,!0),Kt(r,s),o++)}return{validity:r,nullCount:o}}function Xa(n,e){return n.nullable||e===0?n:Object.freeze({...n,nullable:!0})}function O2(n,e){for(let t=0;t<e.length;t++){const r=e[t];if(r!==x&&r>=n.length)throw new P("E_INDEX_RANGE",`indexMap[${t}] = ${r} is outside the column of ${n.length} rows`,{index:t,found:r,length:n.length,column:n.meta.name})}}function $2(n,e,t){const{length:r}=e,{components:o,fill:s}=t,i=N2(n.data,r*o);typeof s=="number"&&s!==0&&i.fill(s);for(let a=0;a<r;a++){const c=e[a];if(c!==x)for(let l=0;l<o;l++)i[a*o+l]=n.data[c*o+l]}return i}function R2(n,e,t){const{length:r}=e,o=new Uint32Array(Fe(r)).fill(t.fill===!0?4294967295:0);for(let s=0;s<r;s++){const i=e[s];i!==x&&(Le(n.data,i)?Ht(o,s):Kt(o,s))}return o}function D2(n,e,t){const r=typeof t.fill=="string"?n.codeOf(t.fill):x,o=r===x?0:r,s=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const a=e[i];s[i]=a===x?o:n.codes[a]}return s}function L2(n,e,t){const r=typeof t.fill=="string"?t.fill:"",o=new Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];o[s]=i===x?r:n.valueAt(i)}return o}function M2(n,e){const t=new Uint32Array(e.length+1);let r=0;for(let o=0;o<e.length;o++){const s=e[o];s!==x&&(r+=n[s+1]-n[s]),t[o+1]=r}return t}function U2(n,e,t){const r=new Uint32Array(t);let o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i!==x)for(let a=n[i];a<n[i+1];a++)r[o++]=a}return r}function F2(n,e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const o=e[r];t[r]=o===x?void 0:n.values[o]}return t}function B2(n,e,t){const{meta:r}=n,{dtype:o}=e;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":n.data=$2(e,t,r);return;case"bool":n.data=R2(e,t,r);return;case"dict":n.data=D2(e,t,r);return;case"string":n.offsets=null,n.utf8=null,n.strings=L2(e,t,r);return;case"list":{const s=M2(e.offsets,t);n.offsets=s,n.child=Qo(e.child,U2(e.offsets,t,s[t.length]));return}case"json":n.values=F2(e,t);return;default:{const s=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Qo(n,e){O2(n,e);const{validity:t,nullCount:r}=T2(n,e),o={...Us(n),meta:Xa(n.meta,r),length:e.length,validity:t};return B2(o,n,e),Tt(o)}function nf(n,e){if(n.meta.refersTo===null)return n;const t=r=>r===x||r>=e.length?x:e[r];if(n.dtype==="u32"){const{length:r}=n,o=new Uint32Array(r);let s=n.validity===null?null:n.validity.slice(),{nullCount:i}=n;for(let c=0;c<r;c++){const l=t(n.data[c]);o[c]=l,l===x&&(s===null||Le(s,c))&&(s??=In(r,!0),Kt(s,c),i++)}const a={...Us(n),meta:Xa(n.meta,i),data:o,validity:s};return Tt(a)}if(n.dtype==="list"&&n.child.dtype==="u32"){const{length:r,offsets:o,child:s}=n,i=new Array(r);let a=n.validity===null?null:n.validity.slice(),{nullCount:c}=n;for(let f=0;f<r;f++){const h=[],g=o[f],w=o[f+1];for(let p=g;p<w;p++){const m=t(s.data[p]);m!==x&&h.push(m)}i[f]=h,w>g&&h.length===0&&(a===null||Le(a,f))&&(a??=In(r,!0),Kt(a,f),c++)}const l=Xa(n.meta,c),u=Vo(Object.freeze({...l,nullable:!0}),i),d={...Us(u),meta:l,validity:a};return Tt(d)}throw new P("E_COLUMN_TYPE",`column "${n.meta.name}" has refersTo but is not u32 or a list of u32`,{column:n.meta.name,field:"refersTo"})}function rf(n,e){return n.refersTo==="node"?e.node:n.refersTo==="edge"?e.edge:null}function Qa(n,e,t,r){const o=n.rowCount,s=[];for(const i of n){const a=rf(i.meta,r);let c=i;a!==null&&(c=nf(i,a)),s.push(c)}return new wn({domain:n.domain,rowCount:o,columns:s})}function of(n,e,t){const r=[];for(const o of n){const s=Qo(o,e),i=rf(o.meta,t);r.push(i===null?s:nf(s,i))}return new wn({domain:n.domain,rowCount:e.length,columns:r})}function At(n,e){return In(n,e===!0)}function _e(n,e){return Le(n,e)}function pn(n,e,t){ba(n,e,t)}function z2(n,e){return gr(n,e)}function sf(n,e){return X0(n,e)}function Qs(n,e,t){const r=Fe(e);if(n.length<r)throw new P("E_MASK_LENGTH",`mask over ${t} has ${n.length} words; ${r} needed for ${e} ${t}`,{found:n.length,required:r,length:e})}const af=Object.freeze({droppedEdges:0,mergedEdges:0});function cf(){return{parts:null,nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function Jo(n,e={}){const t=Ya(n,e.arena!==!1),{core:r}=t;return{arcCount:t.arcCount,selfLoopCount:t.selfLoopCount,rowPtr:r.rowPtr,colIdx:r.colIdx,weights:r.weights,arcToEdge:r.arcToEdge,edgeToArc:r.edgeToArc,flags:t.flags,arena:r.arena}}function Zo(n,e,t){return{label:n.label,serial:null,directed:t.directed,nodeCount:t.nodeCount,edgeCount:t.edgeCount,arcCount:e.arcCount,selfLoopCount:e.selfLoopCount,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,flags:e.flags,ids:t.ids,nodes:t.nodes,edges:t.edges,graph:n.graph,extensions:t.extensions,meta:n.meta,arena:e.arena,checksum:!1}}function es(n,e,t){if(e===null&&t===null||n.extensions.size===0)return n.extensions;const r=new Map;for(const[o,s]of n.extensions)r.set(o,Qa(s,null,s.rowCount,{node:e,edge:t}));return r}function G2(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++){const o=n[r];o!==x&&t[o]===x&&(t[o]=r)}return t}function Js(n){const e=n.length,t=new Uint32Array(e).fill(x);let r=0,o=0,s=0;for(let a=0;a<e;a++)n[a]===a?t[a]=r++:n[a]===x?o++:s++;if(o===0&&s===0)return{count:r,remap:null,origin:null,dropped:o,merged:s};const i=new Uint32Array(e);for(let a=0;a<e;a++){const c=n[a];i[a]=c===x?x:t[c]}return{count:r,remap:i,origin:G2(i,r),dropped:o,merged:s}}function W2(n,e){return n.length===e&&qr(n)}function ts(n,e,t){const{count:r,origin:o}=e,s=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){const c=o===null?a:o[a];s[a]=t===null?n.src[c]:t[n.src[c]],i[a]=t===null?n.dst[c]:t[n.dst[c]]}return{src:s,dst:i}}function Ja(n,e){if(e!==void 0)for(const t of Object.keys(e))zt(`${n}.${t}`,e[t],Sy)}function ns(n,e,t){const{count:r,remap:o,origin:s}=e;if(n===null){if(t!=="sum")return null;const a=new Float32Array(r);if(o===null)return a.fill(1),a;for(let c=0;c<o.length;c++)o[c]!==x&&a[o[c]]++;return a}if(o===null||s===null)return n;const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=n[s[a]];if(t==="first")return i;for(let a=0;a<o.length;a++){const c=o[a];if(c===x||s[c]===a)continue;const l=n[a];switch(t){case"last":i[c]=l;break;case"sum":i[c]+=l;break;case"min":l<i[c]&&(i[c]=l);break;case"max":l>i[c]&&(i[c]=l);break;default:{const u=t;throw new P("E_UNSUPPORTED",`unknown weight reducer ${String(u)}`,{reducer:u})}}}return i}function Zs(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=e(r)?r:x;return Js(t)}function V2(n,e,t){const{count:r,remap:o}=e,{components:s}=n.meta,i=s,a=new Float64Array(r*i),c=new Uint32Array(r),l=new Uint8Array(r),u=n.data,d=o===null?n.length:o.length;for(let y=0;y<d;y++){const b=o===null?y:o[y];if(!(b===x||!n.isSet(y))){c[b]++;for(let v=0;v<i;v++){const A=u[y*i+v],E=b*i+v;if(l[b]===0)a[E]=A;else switch(t){case"sum":case"mean":a[E]+=A;break;case"min":A<a[E]&&(a[E]=A);break;case"max":A>a[E]&&(a[E]=A);break;default:{const I=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(I)}`,{reducer:I})}}}l[b]=1}}if(t==="mean"){for(let y=0;y<r;y++)if(c[y]>1)for(let b=0;b<i;b++)a[y*i+b]/=c[y]}const h=t==="mean"||t==="sum"&&n.dtype!=="f32"&&n.dtype!=="f64"?"f64":n.dtype;let g;switch(h){case"f64":g=a;break;case"f32":g=new Float32Array(a);break;case"i32":g=new Int32Array(a);break;case"u32":g=new Uint32Array(a);break;case"u8":g=new Uint8Array(new ArrayBuffer(Math.ceil(r*i/4)*4),0,r*i),g.set(a);break;default:{const y=h;throw new P("E_COLUMN_TYPE",`cannot reduce a ${String(y)} column`,{dtype:y})}}let w=null,p=0;for(let y=0;y<r;y++)l[y]===0&&(w??=In(r,!0),Kt(w,y),p++);const m=ht(n.meta.name,n.meta.domain,{dtype:h,components:s,nullable:n.meta.nullable||p>0,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(m,r,w),data:g})}function j2(n,e){const{count:t,remap:r}=e,o=new Uint32Array(t);if(r===null)o.fill(1);else for(let i=0;i<r.length;i++)r[i]!==x&&o[r[i]]++;const s=ht(n.meta.name,n.meta.domain,{dtype:"u32",nullable:!1,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(s,t,null),data:o})}function Za(n,e,t){if(t==="drop"||n.meta.refersTo!==null)return null;const{count:r,remap:o,origin:s}=e;switch(t){case"first":return s===null?n:Qo(n,s);case"last":{if(o===null)return n;const i=new Uint32Array(r);for(let a=0;a<o.length;a++)o[a]!==x&&(i[o[a]]=a);return Qo(n,i)}case"count":return j2(n,e);case"sum":case"min":case"max":case"mean":{const{dtype:i}=n;switch(i){case"f32":case"f64":case"i32":case"u32":case"u8":return V2(n,e,t);case"bool":case"dict":case"string":case"list":case"json":throw new P("E_COLUMN_TYPE",`reducer "${t}" needs a numeric column; "${n.meta.name}" is ${i}`,{column:n.meta.name,dtype:i,reducer:t});default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${String(a)}`,{dtype:a})}}}default:{const i=t;throw new P("E_UNSUPPORTED",`unknown column reducer ${String(i)}`,{reducer:i})}}}function ei(n,e,t,r){const o={node:r,edge:e.remap};if(t===void 0||Object.keys(t).length===0)return e.origin===null?r===null?n.edges:Qa(n.edges,null,n.edgeCount,o):of(n.edges,e.origin,o);const s=[];for(const a of n.edges){const c=t[a.meta.name];if(c===void 0){const u=e.origin===null?a:Qo(a,e.origin);s.push(u);continue}const l=Za(a,e,c);l!==null&&s.push(l)}const i=new wn({domain:"edge",rowCount:e.count,columns:s});return Qa(i,null,e.count,o)}function lf(n,e,t){const r=Zs(n.edgeCount,t),{src:o,dst:s}=ts(e,r,null),i=ns(e.weights,r,"first"),a=Jo({directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,src:o,dst:s,weights:i}),c=ei(n,r,void 0,null);return{parts:Zo(n,a,{directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,ids:n.ids,nodes:n.nodes,edges:c,extensions:es(n,null,r.remap)}),nodeOrigin:null,edgeOrigin:r.origin,nodeRemap:null,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:0}}}function q2(n,e,t){return Qs(t,n.edgeCount,"edges"),lf(n,e,r=>_e(t,r))}function H2(n,e){return lf(n,e,t=>e.src[t]!==e.dst[t])}function uf(n,e,t,r){return new P("E_INDEX_RANGE",`inducedSubgraph selection[${n}] = ${e} is ${r} (nodeCount ${t})`,{index:n,found:e,nodeCount:t,reason:r})}function K2(n,e){const{nodeCount:t}=n;if(e instanceof Uint32Array){const r=new Uint8Array(t),o=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];if(i>=t)throw uf(s,i,t,"out of range");if(r[i]===1)throw uf(s,i,t,"repeated");r[i]=1,o[s]=i}return o}return Qs(e.mask,t,"nodes"),sf(e.mask,t)}function df(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++)t[n[r]]=r;return t}function ff(n,e,t,r){const o=t===null?n.nodeCount:t.length,s=t===null?null:df(t,n.nodeCount),{src:i,dst:a}=ts(e,r,s),c=ns(e.weights,r,"first"),l=Jo({directed:n.directed,nodeCount:o,edgeCount:r.count,src:i,dst:a,weights:c}),u={node:s,edge:r.remap},d=t===null?n.nodes:of(n.nodes,t,u),f=t===null?n.ids:Gy(n.ids,t),h=ei(n,r,void 0,s);return{parts:Zo(n,l,{directed:n.directed,nodeCount:o,edgeCount:r.count,ids:f,nodes:d,edges:h,extensions:es(n,s,r.remap)}),nodeOrigin:t,edgeOrigin:r.origin,nodeRemap:s,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:r.merged}}}function Y2(n,e,t){const r=K2(n,t),o=W2(r,n.nodeCount),s=o?null:r,i=o?null:df(r,n.nodeCount),a=i===null?Zs(n.edgeCount,()=>!0):Zs(n.edgeCount,c=>i[e.src[c]]!==x&&i[e.dst[c]]!==x);return ff(n,e,s,a)}function X2(n,e,t){const{nodeCount:r}=n;if(t.length!==r)throw new P("E_INVALID_PERMUTATION",`perm has ${t.length} entries, expected ${r}`,{expected:r,found:t.length});const o=new Uint8Array(r);for(let a=0;a<r;a++){const c=t[a];if(c>=r||o[c]===1)throw new P("E_INVALID_PERMUTATION",`perm[${a}] = ${c} is out of range or repeated (nodeCount ${r})`,{index:a,found:c,nodeCount:r});o[c]=1}const s=qr(t)?null:t.slice(),i=Zs(n.edgeCount,()=>!0);return ff(n,e,s,i)}function hf(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Q2(n,e,t,r,o){for(let s=0;s<o;s++){const i=e[t+s],a=e[r+s],c=Math.min(i,a),l=Math.max(i,a);n[c]=c,n[l]=c}}function J2(n,e,t={}){const r=t.reciprocal===!0,o=zt("weights",t.weights,Fs)??"first",{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i);for(let y=0;y<i;y++)u[y]=r&&e.src[y]!==e.dst[y]?x:y;for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if(A>y){const[I,k]=qs(a,c,A,y);Q2(u,l,v,I,Math.min(E-v,k-I))}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,o),w=Jo({directed:!1,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,void 0,null);return{parts:Zo(n,w,{directed:!1,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Z2(n,e){const{nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s}=n,i=e.arcToEdge,a=qr(i);let c=null,l=null;if(!a){c=i,l=new Uint32Array(r);for(let f=0;f<o;f++)l[i[f]]=f}const u=_d({directed:!0,nodeCount:t,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,selfLoopCount:s});return Gn(e.rowPtr.buffer),Gn(e.colIdx.buffer),e.weights!==null&&Gn(e.weights.buffer),c!==null&&Gn(c.buffer),{parts:{label:n.label,serial:null,directed:!0,nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,edgeToArc:l,flags:u,ids:n.ids,nodes:n.nodes,edges:n.edges,graph:n.graph,extensions:n.extensions,meta:n.meta,arena:null,checksum:!1},nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function ev(n,e,t={}){const r=zt("weights",t.weights,Fs)??"first",o=zt("selfLoops",t.selfLoops,["keep","drop"])==="drop";Ja("edgeReducers",t.edgeReducers);const{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i).fill(x);for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if((n.directed||A>=y)&&!(A===y&&o)){const I=l[v];for(let k=v;k<E;k++)u[l[k]]=I}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,r),w=Jo({directed:n.directed,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,t.edgeReducers,null);return{parts:Zo(n,w,{directed:n.directed,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Je(n,e){const t=n.length,r=e??new Uint32Array(t);if(r.length!==t)throw new P("E_COLUMN_LENGTH",`out has ${r.length} entries, expected ${t}`,{expected:t,found:r.length});let o=0;for(let i=0;i<t;i++){const a=n[i];if(a===x)throw new P("E_PARTITION",`labels[${i}] is INVALID_INDEX`,{index:i});a>o&&(o=a)}const s=o<4*t+1024?tv(n,r,o):nv(n,r);return{labels:r,count:s}}function tv(n,e,t){const r=new Uint32Array(t+1).fill(x);let o=0;for(let s=0;s<n.length;s++){const i=n[s];let a=r[i];a===x&&(a=o++,r[i]=a),e[s]=a}return o}function nv(n,e){const t=new Map;let r=0;for(let o=0;o<n.length;o++){const s=n[o];let i=t.get(s);i===void 0&&(i=r++,t.set(s,i)),e[o]=i}return r}function rv(n,e){if(n.length!==e)throw new P("E_PARTITION",`partition has ${n.length} entries, expected nodeCount ${e}`,{expected:e,found:n.length});let t=-1;for(let r=0;r<e;r++){const o=n[r];if(o===x)throw new P("E_PARTITION",`partition[${r}] is INVALID_INDEX`,{index:r});o>t&&(t=o)}if(t<e){const r=new Uint8Array(t+1);let o=0;for(let s=0;s<e;s++)r[n[s]]===0&&(r[n[s]]=1,o++);if(o===t+1)return{labels:n.slice(),count:t+1}}return Je(n)}function ov(n,e,t,r,o){const s=[];if(o!==void 0){const i={count:t,remap:e,origin:r};for(const a of n.nodes){const c=o[a.meta.name];if(c===void 0)continue;const l=Za(a,i,c);l!==null&&s.push(l)}}return new wn({domain:"node",rowCount:t,columns:s})}function sv(n,e,t){const r=n.length,o=[];for(let u=0;u<r;u++)n[u]!==x&&o.push(u);const s=new Uint32Array(t+1);for(const u of o)s[e[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const i=new Uint32Array(o.length);for(const u of o)i[s[e[u]]++]=u;s.fill(0);for(const u of o)s[n[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const a=new Uint32Array(o.length);for(let u=0;u<i.length;u++){const d=i[u];a[s[n[d]]++]=d}const c=new Uint32Array(r).fill(x);let l=0;for(;l<a.length;){const u=a[l];let d=l+1;for(;d<a.length&&n[a[d]]===n[u]&&e[a[d]]===e[u];)d++;for(let f=l;f<d;f++)c[a[f]]=u;l=d}return c}function iv(n,e,t,r={}){const o=zt("weights",r.weights,Fs)??"sum",s=zt("selfLoops",r.selfLoops,["keep","drop"])==="drop",i=(zt("parallel",r.parallel,["merge","keep"])??"merge")==="merge";Ja("nodeReducers",r.nodeReducers),Ja("edgeReducers",r.edgeReducers);const{nodeCount:a,edgeCount:c}=n,{labels:l,count:u}=rv(t,a),d=new Uint32Array(u),f=new Uint32Array(u).fill(x);for(let N=0;N<a;N++){const C=l[N];d[C]++,f[C]===x&&(f[C]=N)}const h=new Uint32Array(c),g=new Uint32Array(c);for(let N=0;N<c;N++){const C=l[e.src[N]],O=l[e.dst[N]];C===O&&s?(h[N]=x,g[N]=x):n.directed||C<=O?(h[N]=C,g[N]=O):(h[N]=O,g[N]=C)}let w;if(i)w=sv(h,g,u);else{w=new Uint32Array(c);for(let N=0;N<c;N++)w[N]=h[N]===x?x:N}const p=Js(w),{src:m,dst:y}=ts(e,p,l),b=ns(e.weights,p,o),v=Jo({directed:n.directed,nodeCount:u,edgeCount:p.count,src:m,dst:y,weights:b}),A=ov(n,l,u,f,r.nodeReducers),E=[];if(r.edgeReducers!==void 0)for(const N of n.edges){const C=r.edgeReducers[N.meta.name];if(C===void 0)continue;const O=Za(N,p,C);O!==null&&E.push(O)}const I=new wn({domain:"edge",rowCount:p.count,columns:E});return{parts:Zo(n,v,{directed:n.directed,nodeCount:u,edgeCount:p.count,ids:nd(u),nodes:A,edges:I,extensions:es(n,l,p.remap)}),nodeOrigin:f,edgeOrigin:p.origin,nodeRemap:l,edgeRemap:p.remap,blockSizes:d,report:{droppedEdges:p.dropped,mergedEdges:p.merged}}}function av(n,e,t,r,o){return{label:n.label,serial:n.serial,directed:n.directed,nodeCount:n.nodeCount,edgeCount:n.edgeCount,arcCount:n.arcCount,selfLoopCount:n.selfLoopCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:r,edgeToArc:o,flags:n.flags,ids:n.ids,nodes:ld(n.nodes,e??{}),edges:ld(n.edges,t??{}),graph:n.graph.clone(),extensions:n.extensions,meta:n.meta,arena:n.arena,checksum:!1}}const cv=2166136261,lv=16777619,uv=3421674724,dv=1540483477;class ec{constructor(){this.laneA=cv,this.laneB=uv}word(e){const t=e>>>0;this.laneA=Math.imul(this.laneA^t,lv)>>>0;const r=(t<<16|t>>>16)>>>0;return this.laneB=Math.imul(this.laneB^r,dv)>>>0,this}words(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e[t]);return this}identity(e){this.word(e);for(let t=0;t<e;t++)this.word(t);return this}bytes(e){const{byteLength:t,byteOffset:r}=e;if(this.word(t),r%4===0&&t%4===0){const i=new Uint32Array(e.buffer,r,t/4);for(let a=0;a<i.length;a++)this.word(i[a]);return this}const o=new Uint8Array(e.buffer,r,t);let s=0;for(;s+4<=t;s+=4)this.word(o[s]|o[s+1]<<8|o[s+2]<<16|o[s+3]<<24);if(s<t){let i=0;for(let a=0;s+a<t;a++)i|=o[s+a]<<8*a;this.word(i)}return this}text(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e.charCodeAt(t));return this}digest(){return this.laneA.toString(16).padStart(8,"0")+this.laneB.toString(16).padStart(8,"0")}}function mn(n){return new ec().bytes(n).digest()}function gf(n,e){n.text(e.dtype).word(e.length).word(e.nullCount),e.validity!==null?n.words(e.validity):n.word(0);const{dtype:t}=e;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":n.bytes(e.data);break;case"dict":n.words(e.codes).word(e.dictionary.length);for(const r of e.dictionary)n.text(r);break;case"string":n.words(e.offsets).bytes(e.utf8);break;case"list":n.words(e.offsets),gf(n,e.child);break;case"json":n.text(JSON.stringify(e.values));break;default:K0(t)}}function wf(n){if(ka(n))throw new P("E_DETACHED",`column "${n.meta.name}" was transferred away`,{column:n.meta.name});const e=new ec;return gf(e,n),e.digest()}function fv(n){const e=new ec;return e.word(n.directed?1:0).word(n.nodeCount).word(n.edgeCount).word(n.arcCount).word(n.selfLoopCount),e.words(n.rowPtr).words(n.colIdx),n.weights===null?e.word(0):e.bytes(n.weights),n.flags.arcToEdgeIsIdentity?e.identity(n.arcCount).identity(n.edgeCount):e.words(n.arcToEdge).words(n.edgeToArc),e.digest()}let hv=1;const ti=["reverse","coo","edgeList","outDegree","inDegree","degree","weightedOutDegree","weightedInDegree","weightedDegree","selfLoopWeight","totalWeight","selfLoopArcs","selfLoopsPerNode","mate","degreeOrder","reverseDegreeOrder","symmetric"],gv="__graphtyNoStructuredClone";function wv(){}const tc=new WeakMap;function pv(){return{reverse:null,coo:null,edgeList:null,outDegree:null,inDegree:null,degree:null,weightedOutDegree:null,weightedInDegree:null,weightedDegree:null,selfLoopWeight:null,totalWeight:null,selfLoopArcs:null,selfLoopsPerNode:null,mate:null,degreeOrder:null,reverseDegreeOrder:null,symmetric:null}}function On(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function mv(n){const{nodeCount:e,edgeCount:t,arcCount:r,flags:o}=n;if(n.rowPtr.length!==e+1)throw On("I1",`rowPtr has ${n.rowPtr.length} entries, expected ${e+1}`,{expected:e+1,found:n.rowPtr.length});if(n.colIdx.length!==r)throw On("I1",`colIdx has ${n.colIdx.length} entries, expected ${r}`,{expected:r,found:n.colIdx.length});if(n.weights!==null&&n.weights.length!==r)throw On("I8",`weights has ${n.weights.length} entries, expected ${r}`,{expected:r,found:n.weights.length});const s=o.arcToEdgeIsIdentity;if(n.arcToEdge===null!==s||n.edgeToArc===null!==s)throw On("I9","arcToEdge / edgeToArc must be null exactly when flags.arcToEdgeIsIdentity",{flag:"arcToEdgeIsIdentity",found:s});if(s&&(!n.directed||r!==t))throw On("I9","flags.arcToEdgeIsIdentity requires a directed snapshot with arcCount === edgeCount",{flag:"arcToEdgeIsIdentity",directed:n.directed,arcCount:r,edgeCount:t});if(n.arcToEdge!==null&&n.arcToEdge.length!==r)throw On("I5",`arcToEdge has ${n.arcToEdge.length} entries, expected ${r}`,{expected:r,found:n.arcToEdge.length});if(n.edgeToArc!==null&&n.edgeToArc.length!==t)throw On("I5",`edgeToArc has ${n.edgeToArc.length} entries, expected ${t}`,{expected:t,found:n.edgeToArc.length});if(n.ids.size!==e)throw On("I11",`ids.size is ${n.ids.size}, expected ${e}`,{expected:e,found:n.ids.size});if(n.nodes.rowCount!==e||n.edges.rowCount!==t||n.graph.rowCount!==1)throw On("I12","table row counts do not match nodeCount / edgeCount / 1",{nodes:n.nodes.rowCount,edges:n.edges.rowCount,graph:n.graph.rowCount})}function ni(n,e){for(const t of e)t.meta.mutable||n.columns.set(t,wf(t))}let yv=class yu{constructor(e){mv(e),this[Au]=!0,this.serial=e.serial??hv++,this.label=e.label,this.formatVersion=Mr,this.directed=e.directed,this.nodeCount=e.nodeCount,this.edgeCount=e.edgeCount,this.arcCount=e.arcCount,this.selfLoopCount=e.selfLoopCount,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.weights=e.weights,this.flags=Object.freeze({...e.flags}),this.ids=e.ids,this.nodes=e.nodes,this.edges=e.edges,this.graph=e.graph,this.extensions=e.extensions,this.meta=e.meta,this.arena=e.arena;let t=null;if(e.checksum){t={core:new Map,columns:new WeakMap,views:new Map},t.core.set("rowPtr",mn(e.rowPtr)),t.core.set("colIdx",mn(e.colIdx)),e.weights!==null&&t.core.set("weights",mn(e.weights)),e.arcToEdge!==null&&t.core.set("arcToEdge",mn(e.arcToEdge)),e.edgeToArc!==null&&t.core.set("edgeToArc",mn(e.edgeToArc)),ni(t,e.nodes),ni(t,e.edges),ni(t,e.graph);for(const o of e.extensions.values())ni(t,o)}const r={arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,views:pv(),checksums:t,contentHash:null,edgeIds:null};Object.defineProperty(this,"state",{value:r,enumerable:!1,writable:!1,configurable:!1}),tc.set(this,r),bv(e),Object.defineProperty(this,gv,{value:wv,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get detached(){return this.rowPtr.length===0}get arcToEdge(){this.assertAttached();const{state:e}=this;return e.arcToEdge===null&&(e.arcToEdge=Ba(this.arcCount),e.checksums?.core.set("arcToEdge",mn(e.arcToEdge))),e.arcToEdge}get edgeToArc(){this.assertAttached();const{state:e}=this;return e.edgeToArc===null&&(e.edgeToArc=Ba(this.edgeCount),e.checksums?.core.set("edgeToArc",mn(e.edgeToArc))),e.edgeToArc}outArcs(e){return this.assertAttached(),[this.rowPtr[e],this.rowPtr[e+1]]}outDegreeOf(e){return this.assertAttached(),this.rowPtr[e+1]-this.rowPtr[e]}findArc(e,t){return this.assertAttached(),yb(this.rowPtr,this.colIdx,e,t)}hasArc(e,t){return this.findArc(e,t)!==x}arcsBetween(e,t){return this.assertAttached(),qs(this.rowPtr,this.colIdx,e,t)}multiplicity(e,t){return this.assertAttached(),gd(this.rowPtr,this.colIdx,e,t)}arcSource(e){this.assertAttached();const{coo:t}=this.state.views;return t!==null?t.src[e]:bb(this.rowPtr,e)}edgeSource(e){this.assertAttached();const t=this.state.views.edgeList;return t!==null?t.src[e]:this.arcSource(this.edgeToArc[e])}edgeTarget(e){return this.colIdx[this.edgeToArc[e]]}edgeIndexOf(e){const{state:t}=this,r=ib(this.edges);if(t.edgeIds?.version!==r){const o=this.edges.byRole("id");t.edgeIds={version:r,column:o,index:o===null?null:new fb(o)}}return t.edgeIds.index===null?x:t.edgeIds.index.indexOf(e)}reverse(){return this.cached("reverse",()=>Eb(this))}coo(){return this.cached("coo",()=>_b(this))}edgeList(){return this.cached("edgeList",()=>bd(this))}outDegree(){return this.cached("outDegree",()=>Ar(this.rowPtr,this.nodeCount))}inDegree(){return this.cached("inDegree",()=>this.directed?Ar(this.reverse().rowPtr,this.nodeCount):this.outDegree())}degree(){return this.cached("degree",()=>Ib(this.outDegree(),this.directed?this.inDegree():this.selfLoopsPerNode()))}weightedOutDegree(){return this.cached("weightedOutDegree",()=>this.weights===null?Ga(this.outDegree()):vd(this.rowPtr,this.weights,this.nodeCount))}weightedInDegree(){return this.cached("weightedInDegree",()=>{if(!this.directed)return this.weightedOutDegree();const e=this.reverse();return e.weights===null?Ga(this.inDegree()):vd(e.rowPtr,e.weights,this.nodeCount)})}weightedDegree(){return this.cached("weightedDegree",()=>kb(this.weightedOutDegree(),this.directed?this.weightedInDegree():this.selfLoopWeight()))}selfLoopWeight(){return this.cached("selfLoopWeight",()=>xb(this,{selfLoopArcs:this.selfLoopArcs(),selfLoopsPerNode:this.selfLoopsPerNode()}))}totalWeight(){return this.cached("totalWeight",()=>Sb(this))}selfLoopArcs(){return this.cached("selfLoopArcs",()=>this.materialiseSelfLoops().selfLoopArcs)}selfLoopsPerNode(){return this.cached("selfLoopsPerNode",()=>this.materialiseSelfLoops().selfLoopsPerNode)}selfLoopsAt(e){return this.assertAttached(),vb(this.rowPtr,this.colIdx,e)}mate(){return this.cached("mate",()=>Nb(this))}degreeOrder(e){if((zt("of",e?.of,["forward","reverse"])??"forward")==="reverse"&&this.directed)return this.cached("reverseDegreeOrder",()=>Ad(this.reverse().rowPtr,this.nodeCount));const r=this.cached("degreeOrder",()=>Ad(this.rowPtr,this.nodeCount));return this.directed||(this.state.views.reverseDegreeOrder=r),r}isSymmetric(){return this.cached("symmetric",()=>this.directed?Tb(this,this.reverse()):!0)}prepare(e){for(const t of e)this.materialiseView(t);return this}dropCaches(){const{state:e}=this;for(const t of ti)e.views[t]=null;e.checksums?.views.clear(),this.flags.arcToEdgeIsIdentity&&(e.arcToEdge=null,e.edgeToArc=null,e.checksums?.core.delete("arcToEdge"),e.checksums?.core.delete("edgeToArc"));for(const t of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const r of t)wy(r)}cachedViews(){if(this.detached)return this.dropCaches(),[];const{views:e}=this.state;return ti.filter(t=>e[t]!==null)}toUndirected(e){return this.assertAttached(),this.directed?this.wrapDerived(J2(this,this.edgeEndpoints(),e)):this.wrapDerived(cf())}transpose(){return this.assertAttached(),this.directed?this.wrapDerived(Z2(this,this.reverse())):this.wrapDerived(cf())}simplified(e){return this.assertAttached(),this.wrapDerived(ev(this,this.edgeEndpoints(),e))}withoutSelfLoops(){return this.assertAttached(),this.wrapDerived(H2(this,this.edgeEndpoints()))}filterEdges(e){return this.assertAttached(),this.wrapDerived(q2(this,this.edgeEndpoints(),e))}inducedSubgraph(e){return this.assertAttached(),this.wrapDerived(Y2(this,this.edgeEndpoints(),e))}contract(e,t){return this.assertAttached(),this.wrapDerived(iv(this,this.edgeEndpoints(),e,t))}relabel(e){return this.assertAttached(),this.wrapDerived(X2(this,this.edgeEndpoints(),e))}seal(){Vs(this.nodes),Vs(this.edges),Vs(this.graph);for(const e of this.extensions.values())Vs(e)}withColumns(e,t){this.assertAttached();const r=this.flags.arcToEdgeIsIdentity,o=av(this,e,t,r?null:this.arcToEdge,r?null:this.edgeToArc);return new yu({...o,checksum:this.state.checksums!==null})}byteLength(e={}){let t=this.rowPtr.byteLength+this.colIdx.byteLength;return this.weights!==null&&(t+=this.weights.byteLength),this.flags.arcToEdgeIsIdentity||(t+=this.arcToEdge.byteLength+this.edgeToArc.byteLength),e.views===!0&&(t+=Av(this,this.state.views)),e.columns===!0&&(t+=Ev(this)),e.ids===!0&&(t+=this.ids.byteLength()),t}contentHash(){this.assertAttached();const{state:e}=this;return e.contentHash??=fv(this),e.contentHash}transferables(){return this.assertAttached(),T1(this)}toWire(e){return this.assertAttached(),N1(this,e)}toBytes(e){return this.assertAttached(),d2(this,e)}toByteChunks(e){return this.assertAttached(),h2(this,e)}validate(e={}){this.assertAttached();const t=zt("level",e.level,["structure","full"])??"full";if(typeof e.checksum!="boolean"&&e.checksum!==void 0)throw new P("E_UNSUPPORTED","validate option checksum must be a boolean",{field:"checksum",found:e.checksum,reason:"unsupported option"});if(xy(this.ids))throw new P("E_DETACHED","the id map's storage was transferred away",{serial:this.serial});for(const r of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const o of r)if(ka(o))throw new P("E_DETACHED",`column "${o.meta.name}" was transferred away`,{column:o.meta.name,serial:this.serial});e.checksum===!0&&this.verifyChecksums(),t==="structure"?Nd(this):r1(this)}assertAttached(){if(this.rowPtr.length===0)throw new P("E_DETACHED","the snapshot's core buffer was transferred away",{serial:this.serial})}cached(e,t){this.assertAttached();const{views:r}=this.state,o=r[e];if(o!==null)return o;const s=t();return r[e]=s,this.recordView(e,s),s}materialiseSelfLoops(){const e=Pb(this),{views:t}=this.state;return t.selfLoopArcs===null&&(t.selfLoopArcs=e.selfLoopArcs,this.recordView("selfLoopArcs",e.selfLoopArcs)),t.selfLoopsPerNode===null&&(t.selfLoopsPerNode=e.selfLoopsPerNode,this.recordView("selfLoopsPerNode",e.selfLoopsPerNode)),{selfLoopArcs:t.selfLoopArcs,selfLoopsPerNode:t.selfLoopsPerNode}}recordView(e,t){mf(this,this.state,e,t)}verifyChecksums(){const e=this.state.checksums;if(e===null)throw new P("E_INVALID_SNAPSHOT","no checksums were recorded for this snapshot",{reason:"no-checksum"});const t=(i,a)=>new P("E_INVALID_SNAPSHOT",`checksum mismatch: ${i} was modified after freeze`,{reason:"checksum",...a}),{state:r}=this,o=[["rowPtr",this.rowPtr],["colIdx",this.colIdx],["weights",this.weights],["arcToEdge",r.arcToEdge],["edgeToArc",r.edgeToArc]];for(const[i,a]of o){const c=e.core.get(i);if(c!==void 0&&a!==null&&mn(a)!==c)throw t(`core array ${i}`,{array:i})}const s=[["nodes",this.nodes],["edges",this.edges],["graph",this.graph],...[...this.extensions].map(([i,a])=>[`extensions[${i}]`,a])];for(const[i,a]of s)for(const c of a){const l=e.columns.get(c);if(l!==void 0&&wf(c)!==l)throw t(`column "${c.meta.name}" of ${i}`,{table:i,column:c.meta.name})}for(const i of ti){const a=r.views[i];if(a!==null)for(const[c,l]of Object.entries(Wa(this,i,a))){const u=e.views.get(`${i}.${c}`);if(u!==void 0&&mn(l)!==u)throw t(`view ${i}.${c}`,{view:i,member:c})}}}edgeEndpoints(){return this.state.views.edgeList??bd(this)}wrapDerived(e){return{snapshot:e.parts===null?this:new yu({...e.parts,checksum:this.state.checksums!==null}),nodeOrigin:e.nodeOrigin,edgeOrigin:e.edgeOrigin,nodeRemap:e.nodeRemap,edgeRemap:e.edgeRemap,blockSizes:e.blockSizes,report:e.report}}materialiseView(e){switch(e){case"reverse":this.reverse();break;case"coo":this.coo();break;case"edgeList":this.edgeList();break;case"outDegree":this.outDegree();break;case"inDegree":this.inDegree();break;case"degree":this.degree();break;case"weightedOutDegree":this.weightedOutDegree();break;case"weightedInDegree":this.weightedInDegree();break;case"weightedDegree":this.weightedDegree();break;case"selfLoopWeight":this.selfLoopWeight();break;case"totalWeight":this.totalWeight();break;case"selfLoopArcs":this.selfLoopArcs();break;case"selfLoopsPerNode":this.selfLoopsPerNode();break;case"mate":this.mate();break;case"degreeOrder":this.degreeOrder();break;case"reverseDegreeOrder":this.degreeOrder({of:"reverse"});break;case"symmetric":this.isSymmetric();break;default:{const t=e;throw new P("E_UNSUPPORTED",`unknown view ${String(t)}`,{view:t})}}}};function bv(n){const e=new Set([n.rowPtr.buffer,n.colIdx.buffer]);n.weights!==null&&e.add(n.weights.buffer),n.arcToEdge!==null&&e.add(n.arcToEdge.buffer),n.edgeToArc!==null&&e.add(n.edgeToArc.buffer);for(const t of Oy(n.ids))e.add(t);for(const t of e)it(t);it(n.ids),it(n.nodes),it(n.edges),it(n.graph);for(const t of n.extensions.values())it(t)}function pf(n){return new yv(n)}function vv(n){if(typeof n!="object"||n===null)return!1;const e=n;return e[Au]===!0&&e.formatVersion===Mr}function Av(n,e){let t=0;for(const r of ti){const o=e[r];o!==null&&!(r==="reverseDegreeOrder"&&o===e.degreeOrder)&&(t+=Rb(n,r,o))}return t}function Ev(n){let e=0;for(const t of[n.nodes,n.edges,n.graph,...n.extensions.values()])for(const r of t)e+=r.byteLength;return e}function mf(n,e,t,r){const o=e.checksums;if(o!==null)for(const[s,i]of Object.entries(Wa(n,t,r)))o.views.set(`${t}.${s}`,mn(i))}function Yr(n,e,t){const r=tc.get(n);return r?.views[e]!==null?!1:(r.views[e]=t,mf(n,r,e,t),!0)}function _v(n,e){const t=tc.get(n);return t===void 0?null:t.views[e]}const Iv=new Set(["keep","error","first","last","sum","min","max"]);function yf(n,e,t){if(typeof e!="string"||!Iv.has(e))throw t(n,e);return e}const kv="graphty.weight";function nc(){return performance.now()}function Sv(n){if(n.selfLoopCount===0)return;const e=n.edgeBound;for(let t=0;t<e;t++)if(n.edgeAlive.get(t)&&n.src.get(t)===n.dst.get(t)){const r=n.src.get(t);throw new P("E_SELF_LOOP",`edge ${t} is a self-loop at node ${r}`,{edge:t,node:r})}}function Pv(n){const e=n.edgeAlive.view().slice(),t=n.src.view(),r=n.dst.view(),o=n.edgeBound;for(let s=0;s<o;s++)t[s]===r[s]&&Le(e,s)&&Kt(e,s);return e}function bf(n,e){const t=n.edgeBound;return{directed:e,nodeCount:n.nodeBound,edgeCount:t,src:n.src.view(),dst:n.dst.view(),weights:n.weight===null?null:n.weight.view()}}function xv(n,e,t,r,o,s){const{rowPtr:i,colIdx:a,arcToEdge:c}=n.core,l=e.nodeBound,u=e.edgeBound,d={staging:e,weights:e.weight===null?null:e.weight.view(),policy:r,countMultiplicity:o,builderIndex:s},f=new Uint32Array(u);for(let w=0;w<u;w++)f[w]=w;const h={survivorOf:f,reduced:null,stored:null,explicit:null,merged:0},g=[];for(let w=0;w<l;w++){const p=i[w+1];let m=i[w];for(;m<p;){const y=a[m],b=Cv(a,m,p);b-m>1&&(t||y>=w)&&(Nv(g,c,m,b),Tv(d,h,w,y,g)),m=b}}return h.merged===0?null:{...h}}function Cv(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Nv(n,e,t,r){n.length=0;for(let o=t;o<r;o++)n.push(e===null?o:e[o])}function Tv(n,e,t,r,o){const{policy:s,staging:i,builderIndex:a}=n;if(s==="error"){const f=[a(o[0]),a(o[1])];throw new P("E_DUPLICATE_EDGE",`edges ${f[0]} and ${f[1]} both connect ${t} -> ${r}`,{source:t,target:r,edges:f})}const c=s==="last"?o[o.length-1]:o[0],l=Ov(n,t,r,o),u=e.survivorOf.length;l!==null&&(e.reduced??=new Float64Array(u),e.stored??=new Uint32Array(Fe(u)),e.reduced[c]=l,Ht(e.stored,c)),(l!==null||o.some(f=>i.weightExplicit(f)))&&!i.weightExplicit(c)&&(e.explicit??=new Uint32Array(Fe(u)),Ht(e.explicit,c));for(const f of o)f!==c&&(e.survivorOf[f]=c,e.merged++)}function Ov(n,e,t,r){const{policy:o}=n;if(o!=="sum"&&o!=="min"&&o!=="max")return null;const s=$v(n.weights,r,o,n.countMultiplicity);if(s!==null&&Number.isNaN(s)){const i=r.map(n.builderIndex);throw new P("E_INVALID_WEIGHT",`duplicateEdges "${o}" over edges ${i.join(", ")} (${e} -> ${t}) yields NaN`,{source:e,target:t,edges:i,policy:o,reason:"reducer"})}return s}function $v(n,e,t,r){if(n===null)return t==="sum"&&r?e.length:null;let o=n[e[0]];for(let s=1;s<e.length;s++){const i=n[e[s]];switch(t){case"sum":o+=i;break;case"min":o=Math.min(o,i);break;case"max":o=Math.max(o,i);break;default:{const a=t;throw new P("E_UNSUPPORTED",`unknown reducer ${a}`,{policy:a})}}}return o}function Rv(n,e,t){const{weight:r}=n;if(r===null||e===0)return null;const o=r.view(),s=t==="f64"&&Dv(o,e),i=n.weightSet!==null||n.weightMode==="omitted";if(!s&&!i)return null;const a=s?"f64":"f32",c=ht(kv,"edge",{dtype:a,role:"weight",nullable:i}),l=a==="f64"?new Float64Array(e):new Float32Array(e);l.set(o.subarray(0,e));const u=i?Lv(n,e):null;return Tt({...Gr(c,e,u),data:l})}function Dv(n,e){for(let t=0;t<e;t++){const r=n[t];if(Math.fround(r)!==r)return!0}return!1}function Lv(n,e){const t=new Uint32Array(Fe(e));for(let r=0;r<e;r++)n.weightExplicit(r)&&Ht(t,r);return t}function Mv(n,e){return n.ids===null||n.idToIndex===null?nd(e):rd(n.ids,e,{map:n.idToIndex})}function rc(n,e,t,r=[]){const o=t.map(i=>i.toColumn(e)),s=new wn({domain:n,rowCount:e,columns:[...o,...r]});return lb(s),s}function Uv(n){const e=[];for(const[t,r]of n)e.push(xa("graph",1,t,[r.value],r.decl??{}));return new wn({domain:"graph",rowCount:1,columns:e})}function Fv(n,e,t,r){if(e===null&&t===null)return null;const o=new Uint32Array(n);for(let s=0;s<n;s++){let i=e===null?s:e.remap[s];i!==x&&t!==null&&r!==null&&(i=r.remap[t.survivorOf[i]]),o[s]=i}return qr(o)?null:o}function Bv(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return{remap:e,origin:e,count:n}}function ri(n,e){return new P("E_UNSUPPORTED",`freeze option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function zv(n){n.duplicateEdges!==void 0&&yf("duplicateEdges",n.duplicateEdges,ri);for(const e of["arena","release","profile","checksum"]){const t=n[e];if(t!==void 0&&typeof t!="boolean")throw ri(e,t)}if(n.label!==void 0&&typeof n.label!="string")throw ri("label",n.label);if(n.prepare!==void 0&&!Array.isArray(n.prepare))throw ri("prepare",n.prepare)}function Gv(n,e){const t=e.profile===!0,r={},o=t?nc():0;let s=o;const i=H=>{if(t){const Y=nc();r[H]=(r[H]??0)+(Y-s),s=Y}},{directed:a}=n,c=n.staging;zv(e);const l=e.arena!==!1,u=e.duplicateEdges??n.options.duplicateEdges,d=n.options.selfLoops,f=c.nodeBound,h=c.edgeBound,g=h-c.liveEdgeCount;d==="error"&&Sv(c);const w=a?c.liveEdgeCount:2*c.liveEdgeCount-c.selfLoopCount;if(w>Te)throw new P("E_TOO_LARGE",`arc count ${w} exceeds MAX_COUNT`,{count:w,max:Te});let p=c,m=null,y=null,b=0;const v=d==="drop"&&c.selfLoopCount>0;if(c.hasTombstones||v){const H=ad(f,c.nodeAlive.view()),Y=ad(h,v?Pv(c):c.edgeAlive.view());b=v?c.selfLoopCount:0,p=cd(c,{nodes:H,edges:Y,edgeValues:null,mergedWeights:null,mergedWeightStored:null,mergedWeightSet:null}),m=H,y=Y}i("compact");const A=p.nodeBound;let E=Ya(bf(p,a),l&&u==="keep");i("sort");let I=null,k=null;if(u!=="keep"){const H=y;if(I=xv(E,p,a,u,n.options.weighted!==!1,Y=>H===null?Y:H.origin[Y]),I!==null){const{survivorOf:Y}=I,ee=eb(Y);let Z=null,J=null;if(I.reduced!==null&&I.stored!==null){Z=new Float64Array(ee.count),J=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.stored,ne)&&(Z[ee.remap[ne]]=I.reduced[ne],Ht(J,ee.remap[ne]))}let ce=null;if(I.explicit!==null){ce=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.explicit,ne)&&Ht(ce,ee.remap[ne])}const de=new Uint32Array(Y.length);for(let ne=0;ne<Y.length;ne++)de[ne]=ee.remap[Y[ne]];p=cd(p,{nodes:Bv(A),edges:ee,edgeValues:de,mergedWeights:Z,mergedWeightStored:J,mergedWeightSet:ce}),k=ee,E=Ya(bf(p,a),l)}else l&&(E={...E,core:mb(E.core)});i("duplicates")}const N=p.edgeBound,{core:C,arcCount:O,selfLoopCount:T,flags:$}=E,L=Rv(p,N,n.options.weightDtype);i("weights");const F=Mv(p,A);i("ids");const M=rc("node",A,p.nodeColumns),R=rc("edge",N,p.edgeColumns,L===null?[]:[L]),D=Uv(n.graphValues),U=new Map;for(const H of p.extensions)U.set(H.name,rc("extension",H.rowCount,H.columns));i("columns");const B={label:e.label??null,serial:null,directed:a,nodeCount:A,edgeCount:N,arcCount:O,selfLoopCount:T,rowPtr:C.rowPtr,colIdx:C.colIdx,weights:C.weights,arcToEdge:C.arcToEdge,edgeToArc:C.edgeToArc,flags:$,ids:F,nodes:M,edges:R,graph:D,extensions:U,meta:n.meta,arena:C.arena,checksum:e.checksum===!0},V=pf(B);e.prepare!==void 0&&e.prepare.length>0&&V.prepare(e.prepare),i("snapshot"),t&&(r.total=nc()-o);const W=m!==null&&!qr(m.remap)?m.remap:null,q=Fv(h,y,I,k),K=I===null?0:I.merged,X=Object.freeze({nodeRemap:W,edgeRemap:q,compacted:W!==null||q!==null,droppedSelfLoops:b,mergedEdges:K,droppedEdges:g+b+K,widened:Object.freeze(n.widened.map(H=>Object.freeze({...H}))),timings:Object.freeze({...r})});return{snapshot:V,report:X,staging:p}}const Wv=new Set(["keep","drop","error"]),Vv=new Set(["f32","f64"]),jv="graphty.directed",qv="graphty.pair";function Kn(n,e){return new P("E_UNSUPPORTED",`builder option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function Hv(n){if(typeof n!="object"||n===null)throw Kn("options",n);if(typeof n.directed!="boolean")throw Kn("directed",n.directed);const e=n.weighted??"auto";if(e!=="auto"&&typeof e!="boolean")throw Kn("weighted",e);const t=n.weightDtype??"f32";if(!Vv.has(t))throw Kn("weightDtype",t);const r=yf("duplicateEdges",n.duplicateEdges??"keep",Kn),o=n.selfLoops??"keep";if(!Wv.has(o))throw Kn("selfLoops",o);const s=n.addMissingNodes??!0;if(typeof s!="boolean")throw Kn("addMissingNodes",s);const i=a=>{const c=n[a];if(c===void 0)return null;if(!Number.isInteger(c)||c<0)throw Kn(a,c);return c};return{fixed:{weighted:e,weightDtype:t,duplicateEdges:r,selfLoops:o,addMissingNodes:s,expectedNodes:i("expectedNodes"),expectedEdges:i("expectedEdges")},directed:n.directed}}function Kv(n){const e={};for(const t of Object.keys(n)){const r=n[t];r!==void 0&&(e[t]=r)}return e}function vf(n,e){return n.dtype===e.dtype&&n.components===e.components&&n.itemDtype===e.itemDtype&&n.itemComponents===e.itemComponents}class oi{constructor(e){this.locked=!1,this.optionsCache=null,this.nodeNames=null,this.edgeNames=null,this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutations=0,this.dirtyFlag=!0,this.disposed=!1;const t=Hv(e);this.fixed=t.fixed,this.directedValue=t.directed,this.staging=this.freshStaging()}static from(e,t){const r=Kv(t??{}),o=e.edges.byRole("weight"),s=r.weightDtype??(o!==null&&o.dtype==="f64"?"f64":void 0),i=r.weighted??(e.flags.weighted?!0:void 0),a=new oi({directed:e.directed,expectedNodes:e.nodeCount,expectedEdges:e.edgeCount,...r,...s===void 0?{}:{weightDtype:s},...i===void 0?{}:{weighted:i}});return a.addGraph(e,{onDuplicateNode:"error"}),a.setMeta(e.meta),a}get options(){return this.check(),this.optionsCache??=Object.freeze({directed:this.directedValue,...this.fixed}),this.optionsCache}get directed(){return this.check(),this.directedValue}get directedLocked(){return this.check(),this.locked}get nodeCount(){return this.check(),this.staging.liveNodeCount}get edgeCount(){return this.check(),this.staging.liveEdgeCount}get nodeBound(){return this.check(),this.staging.nodeBound}get edgeBound(){return this.check(),this.staging.edgeBound}get mutationCount(){return this.check(),this.mutations}get dirty(){return this.check(),this.dirtyFlag}setDirected(e,t){if(this.check(),e!==this.directedValue){if(this.locked)throw new P("E_DIRECTED","the builder's direction is locked",{reason:"locked",directed:this.directedValue});if(this.staging.liveEdgeCount===0){this.directedValue=e,this.optionsCache=null,this.mutated();return}if(!e)throw new P("E_DIRECTED","a builder with edges cannot become undirected",{reason:"edges present",edgeCount:this.staging.liveEdgeCount});if(t?.expand!==!0)throw new P("E_DIRECTED","an undirected builder with edges becomes directed only with { expand: true }",{reason:"expand required",edgeCount:this.staging.liveEdgeCount});this.expandToDirected()}}lockDirected(){this.check(),this.locked=!0}addNode(e){return this.check(),this.addValidatedNode(jn(e))}addNodes(e,t){this.check();const o=(Array.isArray(e)?e:[...e]).map(i=>jn(i));if(t!==void 0&&t.length<o.length)throw new P("E_COLUMN_LENGTH",`out has ${t.length} entries for ${o.length} ids`,{expected:o.length,found:t.length});const s=t??new Uint32Array(o.length);for(let i=0;i<o.length;i++)s[i]=this.addValidatedNode(o[i]);return s}addAnonymousNodes(e){if(this.check(),!Number.isInteger(e)||e<0)throw new P("E_INDEX_RANGE",`node count ${e} is not a non-negative integer`,{count:e});const{staging:t}=this,r=t.nodeBound;if(this.checkNodeLimit(e),t.idToIndex!==null){for(let o=r;o<r+e;o++)if(t.idToIndex.has(o))throw new P("E_DUPLICATE_ID",`node id ${o} exists; anonymous node ${o} cannot use it`,{id:o,index:t.idToIndex.get(o)})}return t.pushAnonymousNodes(e),e>0&&this.mutated(),r}hasNode(e){return this.check(),this.lookup(e)!==x}indexOf(e){return this.check(),this.lookup(e)}idOf(e){this.check();const{staging:t}=this;if(!this.isLiveNode(e))throw new P("E_INDEX_RANGE",`node index ${e} is out of range or removed`,{index:e,bound:t.nodeBound});return t.ids===null?e:t.ids[e]}removeNode(e){this.check();const t=this.lookup(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return this.removeLiveNode(t)}removeNodeByIndex(e){if(this.check(),!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e});return this.removeLiveNode(e)}reserve(e,t){this.check();const r=(i,a)=>{if(a===void 0)return 0;if(!Number.isInteger(a)||a<0||a>Te)throw new P("E_TOO_LARGE",`reserve(${i}) ${a} is not an integer in [0, MAX_COUNT]`,{field:i,count:a,max:Te});return a},o=r("nodes",e),s=r("edges",t);$a(o),this.staging.reserve(o,s)}addEdge(e,t,r){this.check();const o=this.checkWeight(r,void 0),s=this.resolveEndpoint(jn(e)),i=this.resolveEndpoint(jn(t));return this.pushEdge(s,i,o)}addEdgeByIndex(e,t,r){this.check();const o=this.checkWeight(r,void 0);return this.checkLiveNode(e),this.checkLiveNode(t),this.pushEdge(e,t,o)}addEdges(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdges: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});for(let c=0;c<o;c++)this.checkLiveNode(e[c]),this.checkLiveNode(t[c]);let s=null;if(r!==void 0){for(let c=0;c<o;c++)this.checkWeight(r[c],c);s=this.fixed.weighted===!1?null:r}this.checkEdgeLimit(o,this.arcsOf(e,t,o));const{staging:i}=this;i.reserve(0,i.edgeBound+o);const a=i.pushEdges(e,t,s);return o>0&&this.mutated(),a}addEdgesByIds(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdgesByIds: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});const s=new Array(o),i=new Array(o),a=new Array(o);for(let l=0;l<o;l++)s[l]=jn(e[l]),i[l]=jn(t[l]),a[l]=this.checkWeight(r===void 0?void 0:r[l],l);if(!this.fixed.addMissingNodes)for(let l=0;l<o;l++)this.requireLive(s[l]),this.requireLive(i[l]);this.checkEdgeLimit(o,this.directedValue?o:2*o);const c=this.staging.edgeBound;for(let l=0;l<o;l++){const u=this.resolveEndpoint(s[l]),d=this.resolveEndpoint(i[l]);this.staging.pushEdge(u,d,a[l])}return o>0&&this.mutated(),c}removeEdge(e){return this.check(),this.isLiveEdge(e)?(this.staging.killEdge(e),this.mutated(),!0):!1}hasEdge(e){return this.check(),this.isLiveEdge(e)}edgeEndpoints(e){return this.check(),this.checkEdge(e),[this.staging.src.get(e),this.staging.dst.get(e)]}edgeWeight(e){this.check(),this.checkEdge(e);const{weight:t}=this.staging;return t===null?1:t.get(e)}setEdgeWeight(e,t){this.check(),this.checkEdge(e);const r=this.checkWeight(t,void 0),{staging:o}=this;r!==void 0&&(o.ensureWeights().set(e,r),o.trackWeight(e,!0)),this.mutated()}outEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.outEdges(e):this.staging.incidentEdges(e)}inEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.inEdges(e):this.staging.incidentEdges(e)}findEdges(e,t){return this.check(),this.checkNodeIndex(e),this.checkNodeIndex(t),this.staging.edgesBetween(e,t,this.directedValue)}declareNodeColumn(e){return this.check(),this.declare("node",e)}declareEdgeColumn(e){return this.check(),this.declare("edge",e)}nodeColumn(e){return this.check(),this.handleOf(this.staging.nodeColumns,e)}edgeColumn(e){return this.check(),this.handleOf(this.staging.edgeColumns,e)}setNodeValue(e,t,r){this.check(),this.checkNodeIndex(t),this.writeCell("node",e,t,r)}setEdgeValue(e,t,r){this.check(),this.checkEdgeIndex(t),this.writeCell("edge",e,t,r)}widenNodeColumn(e,t){this.check(),this.widenColumn("node",e,t)}widenEdgeColumn(e,t){this.check(),this.widenColumn("edge",e,t)}setNodeColumn(e,t,r){this.check(),this.setBulkColumn("node",this.staging.nodeBound,e,t,r??{})}setEdgeColumn(e,t,r){this.check(),this.setBulkColumn("edge",this.staging.edgeBound,e,t,r??{})}setGraphValue(e,t,r){this.check();const o=r??{};ht(e,"graph",{dtype:"json",...o}),t!==void 0&&Qv(e,t,o),this.graphValues.set(e,{decl:o,value:t}),this.mutated()}setMeta(e){this.check(),this.metaValue=Ky(this.metaValue,e),this.mutated()}addExtensionTable(e,t){this.check();const{staging:r}=this;if(r.extensions.some(s=>s.name===e))throw new P("E_COLUMN_EXISTS",`extension table "${e}" already exists`,{table:e});const o=[];for(const s of t){const i=jr(s.name,"extension",s,!1);if(o.some(a=>a.meta.name===i.meta.name))throw new P("E_COLUMN_EXISTS",`column "${s.name}" is declared twice in "${e}"`,{table:e,column:s.name});Xr(o,i.meta,e),o.push(i)}return r.extensions.push({name:e,columns:o,rowCount:0}),this.mutated(),r.extensions.length-1}addExtensionRow(e,t){this.check();const r=this.extensionOf(e);if(t.length!==r.columns.length)throw new P("E_COLUMN_LENGTH",`extension table "${r.name}" has ${r.columns.length} columns; ${t.length} values given`,{table:r.name,expected:r.columns.length,found:t.length});const o=r.rowCount,s=r.columns.map((i,a)=>{const c=this.checkReference(i.meta,t[a]);return i.checkValue(o,c),c});for(let i=0;i<s.length;i++)r.columns[i].write(o,s[i]);return r.rowCount=o+1,this.mutated(),o}addNodeRecord(e,t){this.check();const r=jn(e),o=Object.keys(t);this.checkCells("node",this.prospectiveNodeIndex(r),o,t);const s=this.addValidatedNode(r);for(const i of o)this.writeCell("node",i,s,t[i]);return s}addEdgeRecord(e,t,r,o){this.check();const s=o===void 0?"weight":o;let i;if(s!==null&&Object.prototype.hasOwnProperty.call(r,s)){const l=r[s];if(l!=null){if(typeof l!="number")throw new P("E_INVALID_WEIGHT",`edge weight "${s}" is not a number`,{key:s,found:typeof l});i=l}}const a=Object.keys(r).filter(l=>l!==s);this.checkWeight(i,void 0),this.checkCells("edge",this.staging.edgeBound,a,r);const c=this.addEdge(e,t,i);for(const l of a)this.writeCell("edge",l,c,r[l]);return c}addGraph(e,t){this.check();const r=t?.onDuplicateNode??"merge";if(r!=="merge"&&r!=="error")throw new P("E_UNSUPPORTED",`addGraph option onDuplicateNode has an unsupported value ${String(r)}`,{field:"onDuplicateNode",found:r,reason:"unsupported option"});if(e.directed!==this.directedValue)throw new P("E_DIRECTED",`a ${e.directed?"directed":"undirected"} snapshot cannot be appended to a ${this.directedValue?"directed":"undirected"} builder`,{reason:"direction mismatch",directed:this.directedValue,found:e.directed});const{staging:o}=this,{nodeCount:s,edgeCount:i}=e,a=o.ids===null&&o.nodeBound===0&&e.ids.kind==="identity"&&e.ids.offset===0,c=new Uint32Array(s);let l=s;if(!a){l=0;for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);if(m===x)l++;else if(r==="error")throw new P("E_DUPLICATE_ID",`node id ${Pn(p)} already exists`,{id:p,index:m})}}this.checkNodeLimit(l);const u=e.edgeList();this.checkEdgeLimit(i,this.arcsOf(u.src,u.dst,i));const d=e.edges.byRole("weight"),f=new Array(i);for(let w=0;w<i;w++){let p;d!==null?p=d.isSet(w)?d.value(w):void 0:u.weights!==null&&(p=u.weights[w]),f[w]=this.checkWeight(p,w)}for(const w of e.nodes)this.checkIncomingColumn("node",w);for(const w of e.edges)w!==d&&this.checkIncomingColumn("edge",w);for(const[w,p]of e.extensions)this.checkIncomingExtension(w,p);if(a){const w=this.addAnonymousNodes(s);for(let p=0;p<s;p++)c[p]=w+p}else for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);c[w]=m===x?this.addValidatedNode(p):m}e.flags.weighted&&this.fixed.weighted!==!1&&o.ensureWeights();const h=new Uint32Array(i);for(let w=0;w<i;w++)h[w]=this.pushEdge(c[u.src[w]],c[u.dst[w]],f[w]);const g={node:c,edge:h};for(const w of e.nodes)this.copyColumn("node",w,c,g);for(const w of e.edges)w!==d&&this.copyColumn("edge",w,h,g);for(const w of e.graph)w.isSet(0)&&this.setGraphValue(w.meta.name,w.value(0),Sn(w.meta));for(const[w,p]of e.extensions)this.appendExtension(w,p,g);this.mutated()}freeze(e){return this.freezeWithReport(e).snapshot}freezeWithReport(e){this.check();const t=e??{},r={staging:this.staging,directed:this.directedValue,options:this.options,graphValues:this.graphValues,meta:this.metaValue,widened:this.widenings},o=Gv(r,t);return this.staging=o.staging,this.widenings=[],this.dirtyFlag=!1,t.release===!0&&(this.staging=this.freshStaging()),{snapshot:o.snapshot,report:o.report}}clear(){this.check(),this.staging=this.freshStaging(),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutated()}dispose(){this.disposed||(this.staging=new La({weightDtype:this.fixed.weightDtype,weighted:!1,expectedNodes:null,expectedEdges:null,resizable:void 0}),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.disposed=!0)}byteLength(){return this.check(),this.staging.byteLength()}check(){if(this.disposed)throw new P("E_BUILDER_DISPOSED","the builder was disposed",{})}mutated(){this.mutations++,this.dirtyFlag=!0}freshStaging(){return new La({weightDtype:this.fixed.weightDtype,weighted:this.fixed.weighted===!0,expectedNodes:this.fixed.expectedNodes,expectedEdges:this.fixed.expectedEdges,resizable:void 0})}prospectiveNodeIndex(e){const{staging:t}=this;return t.idToIndex===null?typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<t.nodeBound?e:t.nodeBound:t.idToIndex.get(typeof e=="number"&&e===0?0:e)??t.nodeBound}lookup(e){const{staging:t}=this;if(t.idToIndex===null)return typeof e!="number"||!Number.isInteger(e)||e<0||e>=t.nodeBound?x:t.nodeAlive.get(e)?e:x;const r=t.idToIndex.get(typeof e=="number"&&e===0?0:e);return r===void 0||!t.nodeAlive.get(r)?x:r}isLiveNode(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.nodeBound&&t.nodeAlive.get(e)}isLiveEdge(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.edgeBound&&t.edgeAlive.get(e)}checkNodeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.nodeBound)throw new P("E_INDEX_RANGE",`node index ${e} is out of range`,{index:e,bound:this.staging.nodeBound})}checkEdgeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.edgeBound)throw new P("E_INDEX_RANGE",`edge index ${e} is out of range`,{edge:e,bound:this.staging.edgeBound})}checkLiveNode(e){if(!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e})}checkEdge(e){if(!this.isLiveEdge(e))throw new P("E_INDEX_RANGE",`edge index ${e} is out of range or removed`,{edge:e,bound:this.staging.edgeBound})}checkNodeLimit(e){if(this.staging.nodeBound+e>Te)throw new P("E_TOO_LARGE",`node count ${this.staging.nodeBound+e} exceeds MAX_COUNT`,{count:this.staging.nodeBound+e,max:Te})}checkEdgeLimit(e,t){const{staging:r}=this,o=r.edgeBound+e,i=(this.directedValue?r.liveEdgeCount:2*r.liveEdgeCount-r.selfLoopCount)+t;if(o>Te||i>Te)throw new P("E_TOO_LARGE",`edge count ${o} (${i} arcs) exceeds MAX_COUNT`,{count:o,arcs:i,max:Te})}arcsOf(e,t,r){if(this.directedValue)return r;let o=0;for(let s=0;s<r;s++)o+=e[s]===t[s]?1:2;return o}addValidatedNode(e){const{staging:t}=this;t.materialiseIds();const o=t.idToIndex.get(e);if(o!==void 0)return t.nodeAlive.get(o)||(t.nodeAlive.set(o,!0),t.liveNodeCount++,this.mutated()),o;this.checkNodeLimit(1);const s=t.pushNode(typeof e=="string"?Ro(e):e);return this.mutated(),s}resolveEndpoint(e){const t=this.lookup(e);if(t!==x)return t;if(this.fixed.addMissingNodes)return this.addValidatedNode(e);throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}requireLive(e){if(this.lookup(e)===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}removeLiveNode(e){const{staging:t}=this,r=[];for(let o=t.firstOut.get(e);o!==x;o=t.nextOut.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));for(let o=t.firstIn.get(e);o!==x;o=t.nextIn.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));return t.nodeAlive.set(e,!1),t.liveNodeCount--,this.mutated(),Uint32Array.from(r).sort()}checkWeight(e,t){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new P("E_INVALID_WEIGHT",`weight ${String(e)} is not a number`,{weight:e,...t===void 0?{}:{edge:t}});if(this.fixed.weighted===!1){if(e!==1)throw new P("E_INVALID_WEIGHT",`weight ${e} on a builder declared unweighted`,{weight:e,reason:"unweighted builder",...t===void 0?{}:{edge:t}});return}return e}}pushEdge(e,t,r){this.checkEdgeLimit(1,this.directedValue||e===t?1:2);const o=this.staging.pushEdge(e,t,r);return this.mutated(),o}expandToDirected(){const{staging:e}=this,t=e.liveEdgeCount;this.checkEdgeLimit(t,t);const r={name:jv,dtype:"bool",role:"directed"},o={name:qv,dtype:"u32",role:"pair",refersTo:"edge"};this.checkDeclaration("edge",r),this.checkDeclaration("edge",o);const s=this.declare("edge",r),i=this.declare("edge",o),a=e.edgeColumns[s],c=e.edgeColumns[i],l=e.edgeBound;for(let u=0;u<l;u++){if(!e.edgeAlive.get(u))continue;a.write(u,!1);const d=e.src.get(u),f=e.dst.get(u);if(d===f)continue;const g=e.weightExplicit(u)&&e.weight!==null?e.weight.get(u):void 0,w=e.pushEdge(f,d,g);a.write(w,!1),c.write(u,w),c.write(w,u)}this.directedValue=!0,this.optionsCache=null,this.mutated()}columnsOf(e){return e==="node"?this.staging.nodeColumns:this.staging.edgeColumns}handleOf(e,t){const r=this.columnIndex(e,t);return r<0?x:r}columnIndex(e,t){let o=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;if(o?.columns!==e||o.map.size!==e.length){const s=new Map;for(let i=0;i<e.length;i++)s.set(e[i].meta.name,i);o={columns:e,map:s},e===this.staging.nodeColumns?this.nodeNames=o:e===this.staging.edgeColumns&&(this.edgeNames=o)}return o.map.get(t)??-1}pushColumn(e,t){e.push(t);const r=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;return r!==null&&r.columns===e&&r.map.size===e.length-1&&r.map.set(t.meta.name,e.length-1),e.length-1}declare(e,t){const{meta:r,existing:o}=this.checkDeclaration(e,t);if(o!==x)return o;const s=this.columnsOf(e);return this.mutated(),this.pushColumn(s,new Ws(r,!1))}checkDeclaration(e,t){if(typeof t.name!="string"||t.name.length===0)throw new P("E_COLUMN_TYPE","a column declaration needs a non-empty name",{field:"name",found:t.name});const r=ht(t.name,e,t),o=this.columnsOf(e),s=this.columnIndex(o,r.name);if(s>=0){if(vf(o[s].meta,r))return{meta:r,existing:s};throw new P("E_COLUMN_EXISTS",`${e} column "${r.name}" is already declared as ${o[s].meta.dtype}`,{column:r.name,domain:e,found:o[s].meta.dtype,expected:r.dtype})}return Xr(o,r,e),{meta:r,existing:x}}resolveColumn(e,t,r){const o=this.columnsOf(e);if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>=o.length)throw new P("E_UNKNOWN_COLUMN",`no ${e} column with handle ${t}`,{domain:e,handle:t});return o[t]}const s=this.columnIndex(o,t);if(s>=0)return o[s];if(r==null)return null;const i=Ra(r),a=jr(t,e,{dtype:i,nullable:!0},!0);return this.pushColumn(o,a),a}checkCells(e,t,r,o){const s=this.columnsOf(e);for(const i of r){const a=o[i],c=this.columnIndex(s,i),l=c<0?void 0:s[c];l!==void 0?l.checkValue(t,this.checkReference(l.meta,a)):a!=null&&(Ra(a),typeof a=="string"?wr(a,{column:i,row:t}):typeof a=="object"&&cn(a,`${i}[${t}]`))}}checkReference(e,t){if(e.refersTo===null||t===void 0||t===null)return t;const r=e.refersTo==="node"?this.staging.nodeBound:this.staging.edgeBound,o=s=>{if(typeof s=="number"&&s!==x&&!(s>=0&&s<r))throw new P("E_INDEX_RANGE",`column "${e.name}" refers to ${String(e.refersTo)} ${s}, which is not below ${r}`,{column:e.name,refersTo:e.refersTo,found:s,bound:r})};if(Array.isArray(t)){for(const s of t)o(s);return t}return o(t),t===x?void 0:t}checkIncomingColumn(e,t){const r=this.columnsOf(e);this.columnIndex(r,t.meta.name)<0&&Xr(r,t.meta,e)}checkIncomingExtension(e,t){const r=this.staging.extensions.find(s=>s.name===e),o=[...t];if(r===void 0){const s=[];for(const i of o){const a={...Sn(i.meta),name:i.meta.name},c=jr(a.name,"extension",a,!1);if(s.some(l=>l.meta.name===c.meta.name))throw new P("E_COLUMN_EXISTS",`column "${a.name}" is declared twice in "${e}"`,{table:e,column:a.name});Xr(s,c.meta,e),s.push(c)}return}for(const s of o)if(!r.columns.some(i=>i.meta.name===s.meta.name))throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${s.meta.name}"`,{table:e,column:s.meta.name})}widenColumn(e,t,r){const o=this.columnsOf(e);let s;if(typeof t=="number")s=Number.isInteger(t)&&t>=0&&t<o.length?o[t]:void 0;else{const c=this.columnIndex(o,t);s=c<0?void 0:o[c]}if(s===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${e} column ${String(t)}`,{domain:e,column:t});const i=s.inferredDtype;if(i===null)throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is declared, not inferred`,{column:s.meta.name,domain:e});if(pr(r)<0)throw new P("E_COLUMN_TYPE",`${r} is not a dtype inference widens to`,{column:s.meta.name,dtype:r});const a=r;if(pr(a)<pr(i))throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is ${i}; it cannot narrow to ${a}`,{column:s.meta.name,found:i,expected:a});a!==i&&(s.widenTo(a),this.widenings.push({column:s.meta.name,domain:e,from:i,to:a}),this.mutated())}writeCell(e,t,r,o){const s=this.resolveColumn(e,t,o);if(s===null)return;const i=s.write(r,this.checkReference(s.meta,o));i!==null&&this.widenings.push({column:s.meta.name,domain:e,from:i.from,to:i.to}),this.mutated()}setBulkColumn(e,t,r,o,s){const i=Jv(e,t,r,o,s,{node:this.staging.nodeBound,edge:this.staging.edgeBound}),a=this.columnsOf(e),c=this.columnIndex(a,r);Xr(a.filter(l=>l.meta.name!==r),i.meta,e),c>=0?a[c]=i:this.pushColumn(a,i),this.mutated()}extensionOf(e){const{extensions:t}=this.staging;if(!Number.isInteger(e)||e<0||e>=t.length)throw new P("E_INDEX_RANGE",`no extension table with handle ${e}`,{handle:e});return t[e]}copyColumn(e,t,r,o){const s=this.columnsOf(e),{name:i}=t.meta;let a=this.columnIndex(s,i);if(a<0){const u={...Sn(t.meta)};Xr(s,t.meta,e),a=this.pushColumn(s,jr(i,e,u,!1))}else{const u=s[a];if(!vf(u.meta,t.meta)){const d=Xv(Da(u.meta.dtype),Da(t.meta.dtype));if(u.meta.dtype!==d){const f=u.meta.dtype;u.widenTo(d),this.widenings.push({column:i,domain:e,from:f,to:d})}}}const c=s[a],l=Af(t.meta,o);for(let u=0;u<t.length;u++){if(!t.isSet(u))continue;let d=t.value(u);l!==null&&(d=Ef(d,l),d===void 0)||c.write(r[u],d)}}appendExtension(e,t,r){const{staging:o}=this,s=[...t];let i=o.extensions.find(l=>l.name===e);if(i===void 0){const l=s.map(d=>({...Sn(d.meta),name:d.meta.name})),u=this.addExtensionTable(e,l);i=o.extensions[u]}const a=i.columns,c=i.rowCount;for(const l of s){const u=a.find(d=>d.meta.name===l.meta.name);if(u===void 0)throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${l.meta.name}"`,{table:e,column:l.meta.name});Yv(u,l,c,Af(l.meta,r))}for(const l of a)l.ensureLength(c+t.rowCount);i.rowCount=c+t.rowCount}}function Yv(n,e,t,r){for(let o=0;o<e.length;o++){if(!e.isSet(o)){n.ensureLength(t+o+1);continue}let s=e.value(o);if(r!==null&&(s=Ef(s,r),s===void 0)){n.ensureLength(t+o+1);continue}n.write(t+o,s)}}function Xr(n,e,t){if(e.role===null)return;const r=n.find(o=>o.meta.name!==e.name&&o.meta.role===e.role);if(r!==void 0)throw new P("E_DUPLICATE_ROLE",`role "${e.role}" is already held by column "${r.meta.name}" in ${t}`,{role:e.role,column:e.name,holder:r.meta.name})}function Xv(n,e){return pr(n)>=pr(e)?n:e}function Af(n,e){switch(n.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ef(n,e){if(typeof n=="number")return n<e.length?e[n]:void 0;if(typeof n=="object"&&n!==null){const t=Array.from(n),r=t.filter(o=>o<e.length).map(o=>e[o]);return r.length===0&&t.length>0?void 0:r}throw new P("E_COLUMN_TYPE",`a refersTo cell holds a ${typeof n}, not an index or a list`,{found:typeof n,reason:"refersTo"})}function Qv(n,e,t){jr(n,"graph",t.dtype===void 0?{...t,dtype:Ra(e)}:t,t.dtype===void 0).write(0,e)}function Jv(n,e,t,r,o,s){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=jr(t,n,{nullable:!1,...o,dtype:a},!1),{components:u}=l.meta;let d;switch(a){case"bool":d=Math.ceil(e/32);break;case"dict":d=e;break;case"f32":case"f64":case"i32":case"u32":case"u8":d=e*u;break;default:throw new P("E_COLUMN_TYPE",`column "${t}": a ${String(a)} column cannot adopt a typed array`,{column:t,field:"dtype"})}if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});switch(l.ensureLength(e),a){case"bool":{const f=r;for(let h=0;h<e;h++)l.write(h,(f[h>>>5]>>>(h&31)&1)===1);break}case"dict":{const{dictionary:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no dictionary`,{column:t});for(let h=0;h<e;h++){const g=r[h];if(g>=f.size)throw new P("E_COLUMN_TYPE",`column "${t}": code ${g} at row ${h} is outside the ${f.size} declared options`,{column:t,row:h,code:g});l.write(h,f.values[g])}break}default:{const{typed:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no typed storage`,{column:t});const{refersTo:h}=l.meta,g=h==="node"?s.node:s.edge;for(let w=0;w<r.length;w++){const p=r[w];if(h!==null&&p!==x&&p>=g)throw new P("E_INDEX_RANGE",`column "${t}" refers to ${h} ${p} at row ${w}, which is not below ${g}`,{column:t,row:w,refersTo:h,found:p,bound:g});if(h!==null&&p===x&&l.validity===null)throw new P("E_COLUMN_TYPE",`column "${t}": row ${w} of a non-nullable refersTo column holds INVALID_INDEX`,{column:t,row:w,field:"nullable"});f.set(w,p)}if(l.validity!==null)for(let w=0;w<e;w++)l.validity.set(w,h===null||r[w]!==x);break}}return l}const Zv="id";function eA(n,e){if(e.directed!==void 0&&e.directed!==n)throw new P("E_DIRECTED",`options.directed (${String(e.directed)}) disagrees with the input's directed (${String(n)})`,{reason:"direction mismatch",directed:n,found:e.directed});return{builder:{directed:n,weighted:e.weighted,weightDtype:e.weightDtype,duplicateEdges:e.duplicateEdges,selfLoops:e.selfLoops,addMissingNodes:e.addMissingNodes,expectedNodes:e.expectedNodes,expectedEdges:e.expectedEdges},freeze:{label:e.label,prepare:e.prepare,arena:e.arena,release:e.release,profile:e.profile,checksum:e.checksum}}}function _f(n){return ArrayBuffer.isView(n)}function oc(n,e,t,r,o){const s=_f(o)?o:o.data,i=_f(o)?{}:o.decl;if(ArrayBuffer.isView(s)){e==="node"?n.setNodeColumn(r,s,i):n.setEdgeColumn(r,s,i);return}const a=xa(e,t,r,s,i),c={...Sn(a.meta),name:r,dtype:a.dtype},l=e==="node"?n.declareNodeColumn(c):n.declareEdgeColumn(c);for(let u=0;u<t;u++){if(!a.isSet(u))continue;const d=a.value(u);e==="node"?n.setNodeValue(l,u,d):n.setEdgeValue(l,u,d)}}function si(n,e,t){return new P("E_COLUMN_LENGTH",`${n} has ${t} entries, expected ${e}`,{field:n,expected:e,found:t})}function tA(n){const{nodeCount:e,ids:t}=n;if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new P("E_INDEX_RANGE",`nodeCount ${e} is not a non-negative integer`,{field:"nodeCount",found:e});if(t!==void 0){if(e!==void 0&&e!==t.length)throw si("ids",e,t.length);return t.length}if(e===void 0)throw new P("E_INDEX_RANGE","nodeCount is required when no ids are given",{field:"nodeCount"});return e}function nA(n,e){const t=n.addNodes(e);for(let r=0;r<t.length;r++)if(t[r]!==r){const o=e[r];throw new P("E_DUPLICATE_ID",`ids[${r}] repeats the id of index ${t[r]}`,{id:o,index:t[r],position:r})}}function rA(n){const{src:e,dst:t,weights:r,edgeIds:o}=n;if(t.length!==e.length)throw si("dst",e.length,t.length);if(r!==void 0&&r.length!==e.length)throw si("weights",e.length,r.length);if(o!==void 0&&o.length!==e.length)throw si("edgeIds",e.length,o.length)}function sc(n,e={}){const{src:t,dst:r,weights:o}=n;rA(n);const s=tA(n),i=t.length,a=eA(n.directed,e),c={...a.builder,weightDtype:e.weightDtype??(o instanceof Float64Array?"f64":void 0),expectedNodes:e.expectedNodes??s,expectedEdges:e.expectedEdges??i},l=new oi(c);if(n.ids===void 0?l.addAnonymousNodes(s):nA(l,n.ids),l.addEdges(t,r,o),n.nodeColumns!==void 0)for(const u of Object.keys(n.nodeColumns))oc(l,"node",s,u,n.nodeColumns[u]);if(n.edgeColumns!==void 0)for(const u of Object.keys(n.edgeColumns))oc(l,"edge",i,u,n.edgeColumns[u]);return n.edgeIds!==void 0&&oc(l,"edge",i,Zv,{data:n.edgeIds,decl:{role:"id",unique:!0}}),n.meta!==void 0&&l.setMeta(n.meta),l.freeze(a.freeze)}const at=new DataView(new ArrayBuffer(8));function Qt(n){return at.setFloat64(0,n,!0),at.getInt32(4,!0)}function If(n){return at.setFloat64(0,n,!0),at.getUint32(0,!0)}const Ir=.6931471803691238,kr=19082149292705877e-26,oA=0x40000000000000,sA=.6666666666666735,iA=.3999999999940942,aA=.2857142874366239,cA=.22222198432149784,lA=.1818357216161805,uA=.15313837699209373,dA=.14798198605116586;function Ge(n){let e=n,t=Qt(e);const r=If(e);let o=0;if(t<1048576){if((t&2147483647|r)===0)return-1/0;if(t<0)return Number.NaN;o-=54,e*=oA,t=Qt(e)}if(t>=2146435072)return e+e;o+=(t>>20)-1023,t&=1048575;const s=t+614244&1048576;return at.setFloat64(0,e,!0),at.setInt32(4,t|s^1072693248,!0),e=at.getFloat64(0,!0),o+=s>>20,fA(e-1,o,t)}function fA(n,e,t){if((1048575&2+t)<3){if(n===0)return e===0?0:e*Ir+e*kr;const l=n*n*(.5-.3333333333333333*n);return e===0?n-l:e*Ir-(l-e*kr-n)}const r=n/(2+n),o=r*r,s=o*o,i=s*(iA+s*(cA+s*uA)),c=o*(sA+s*(aA+s*(lA+s*dA)))+i;if((t-398458|440401-t)>0){const l=.5*n*n;return e===0?n-(l-r*(l+c)):e*Ir-(l-(r*(l+c)+e*kr)-n)}return e===0?n-r*(n-c):e*Ir-(r*(n-c)-e*kr-n)}const kf=-.16666666666666632,hA=.00833333333332249,gA=-.0001984126982985795,wA=27557313707070068e-22,pA=-25050760253406863e-24,mA=158969099521155e-24,yA=.0416666666666666,bA=-.001388888888887411,vA=2480158728947673e-20,AA=-27557314351390663e-23,EA=2087572321298175e-24,_A=-11359647557788195e-27;function rs(n,e,t){if((Qt(n)&2147483647)<1044381696&&Math.trunc(n)===0)return n;const r=n*n,o=r*n,s=hA+r*(gA+r*(wA+r*(pA+r*mA)));return t===0?n+o*(kf+r*s):n-(r*(.5*e-o*s)-e-o*kf)}function os(n,e){const t=Qt(n)&2147483647;if(t<1044381696&&Math.trunc(n)===0)return 1;const r=n*n,o=r*(yA+r*(bA+r*(vA+r*(AA+r*(EA+r*_A)))));if(t<1070805811)return 1-(.5*r-(r*o-n*e));let s;t>1072234496?s=.28125:(at.setInt32(4,t-2097152,!0),at.setUint32(0,0,!0),s=at.getFloat64(0,!0));const i=.5*r-s;return 1-s-(i-(r*o-n*e))}const IA=.6366197723675814,Sf=1.5707963267341256,ic=6077100506506192e-26,Pf=6077100506303966e-26,ac=20222662487959506e-37,kA=20222662487111665e-37,SA=84784276603689e-45,Oe=new Float64Array(2);function xf(n){const e=Qt(n),t=e&2147483647;if(t<1073928572){const d=e>0?1:-1;let f=n-d*Sf;return t===1073291771?(f-=d*Pf,Oe[0]=f-d*ac,Oe[1]=f-Oe[0]-d*ac):(Oe[0]=f-d*ic,Oe[1]=f-Oe[0]-d*ic),d}const r=Math.abs(n),o=Math.floor(r*IA+.5);let s=r-o*Sf,i=o*ic;const a=t>>20;let c=s-i,l=a-(Qt(c)>>20&2047);if(l>16){let d=s;i=o*Pf,s=d-i,i=o*ac-(d-s-i),c=s-i,l=a-(Qt(c)>>20&2047),l>49&&(d=s,i=o*kA,s=d-i,i=o*SA-(d-s-i),c=s-i)}const u=s-c-i;return e<0?(Oe[0]=-c,Oe[1]=-u,-o):(Oe[0]=c,Oe[1]=u,o)}const PA=6.283185307179586;function Cf(n,e){return e>1094263291?n%PA:n}function Jt(n){const e=Qt(n)&2147483647;if(e<=1072243195)return rs(n,0,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return rs(Oe[0],Oe[1],1);case 1:return os(Oe[0],Oe[1]);case 2:return-rs(Oe[0],Oe[1],1);default:return-os(Oe[0],Oe[1])}}function yn(n){const e=Qt(n)&2147483647;if(e<=1072243195)return os(n,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return os(Oe[0],Oe[1]);case 1:return-rs(Oe[0],Oe[1],1);case 2:return-os(Oe[0],Oe[1]);default:return rs(Oe[0],Oe[1],1)}}const Nf=3.141592653589793,Tf=1.5707963267948966,ii=6123233995736766e-32,xA=.16666666666666666,CA=-.3255658186224009,NA=.20121253213486293,TA=-.04005553450067941,OA=.0007915349942898145,$A=3479331075960212e-20,RA=-2.403394911734414,DA=2.0209457602335057,LA=-.6882839716054533,MA=.07703815055590194;function cc(n){const e=n*(xA+n*(CA+n*(NA+n*(TA+n*(OA+n*$A))))),t=1+n*(RA+n*(DA+n*(LA+n*MA)));return e/t}function Of(n){const e=Qt(n),t=e&2147483647;if(t>=1072693248)return(t-1072693248|If(n))===0?e>0?0:Nf+2*ii:Number.NaN;if(t<1071644672)return t<=1012924416?Tf+ii:Tf-(n-(ii-n*cc(n*n)));if(e<0){const c=(1+n)*.5,l=Math.sqrt(c),u=cc(c)*l-ii;return Nf-2*(l+u)}const r=(1-n)*.5,o=Math.sqrt(r);at.setFloat64(0,o,!0),at.setUint32(0,0,!0);const s=at.getFloat64(0,!0),i=(r-s*s)/(o+s),a=cc(r)*o+i;return 2*(s+a)}const UA=709.782712893384,FA=-745.1332191019411,BA=1.4426950408889634,zA=9332636185032189e-317,GA=.16666666666666602,WA=-.0027777777777015593,VA=6613756321437934e-20,jA=-16533902205465252e-22,qA=41381367970572385e-24;function $f(n,e){return at.setFloat64(0,n,!0),at.setInt32(4,at.getInt32(4,!0)+(e<<20),!0),at.getFloat64(0,!0)}function HA(n,e,t){return e>=2146435072?!t||Number.isNaN(n)?n+n:0:n>UA?1/0:n<FA?0:null}const Sr=new Float64Array(3);function KA(n,e,t){if(e<1072734898){Sr[0]=t?-1:1,Sr[1]=t?n+Ir:n-Ir,Sr[2]=t?-kr:kr;return}const r=Math.trunc(BA*n+(t?-.5:.5));Sr[0]=r,Sr[1]=n-r*Ir,Sr[2]=r*kr}function Qr(n){const e=Qt(n),t=e<0,r=e&2147483647,o=r>=1082535490?HA(n,r,t):null;if(o!==null)return o;if(r<1043333120)return 1+n;let s=0,i=0,a=0,c=n;r>1071001154&&(KA(n,r,t),[a,s,i]=Sr,c=s-i);const l=c*c,u=c-l*(GA+l*(WA+l*(VA+l*(jA+l*qA))));if(a===0)return 1-(c*u/(u-2)-c);const d=1-(i-c*u/(2-u)-s);return a>=-1021?$f(d,a):$f(d,a+1e3)*zA}function YA(...n){let e=0,t=!1;for(const s of n){const i=Math.abs(s);Number.isNaN(i)?t=!0:i>e&&(e=i)}if(e===1/0)return 1/0;if(t)return Number.NaN;if(e===0)return 0;let r=0,o=0;for(const s of n){const i=Math.abs(s)/e,a=i*i-o,c=r+a;o=c-r-a,r=c}return Math.sqrt(r)*e}function XA(n,e){let t=n,r=Math.abs(e),o=1;for(;r>0;)r%2===1&&(o*=t),t*=t,r=Math.floor(r/2);return e<0?1/o:o}function QA(n,e){return n===0?e>0?0:1/0:n===1/0?e>0?1/0:0:e===.5?Math.sqrt(n):Qr(e*Ge(n))}function JA(n,e){if(e===0)return 1;if(Number.isNaN(n)||Number.isNaN(e))return Number.NaN;const t=Number.isInteger(e);if(t&&Math.abs(e)<=1024)return XA(n,e);const r=Math.abs(n);if(!Number.isFinite(e))return r===1?Number.NaN:r>1==e>0?1/0:0;if(n<0&&!t&&r!==1/0)return Number.NaN;const o=QA(r,e);return(n<0||Object.is(n,-0))&&t&&e%2!==0?-o:o}function Rf(n){if(n.ids===void 0)throw new P("E_UNKNOWN_NODE","node ids cannot be resolved: this graph has no id map (pass a GraphSnapshot)",{reason:"no id map"});return n.ids}function xe(n,e){return typeof e=="number"?e:Rf(n).requireIndex(e.id)}function ss(n,e){return"mask"in e?(Qs(e.mask,n.nodeCount,"nodes"),sf(e.mask,n.nodeCount)):"ids"in e?Rf(n).indicesOf(e.ids,"throw"):e}function Df(n,e){if("mask"in e)return Qs(e.mask,n.nodeCount,"nodes"),e.mask;const t=ss(n,e),r=At(n.nodeCount);for(let o=0;o<t.length;o++){const s=t[o];if(!Number.isInteger(s)||s<0||s>=n.nodeCount)throw new P("E_INDEX_RANGE",`node index ${String(s)} is out of range for ${n.nodeCount} nodes`,{index:s,nodeCount:n.nodeCount});pn(r,s,!0)}return r}function Q(n,e){return Object.assign(n,{code:e})}function lc(n,e,t,r){const o=t===void 0?`${n}: ${String(e)} nodes need ${String(r)} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`${n}: ${String(e)} nodes exceeds maxNodes ${String(t)}; the result would allocate ${String(r)} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(Q(new RangeError(o),"E_TOO_LARGE"),{params:{nodeCount:e,maxNodes:t??null,bytes:r}})}function Lf(n,e,t,r,o){if(t!==void 0&&(e>t||Number.isNaN(t)))throw lc(n,e,t,r);try{return o()}catch(s){throw s instanceof RangeError?lc(n,e,void 0,r):s}}class Mf extends Error{constructor(e,t,r){super(`${e} did not converge in ${String(t)} iterations (tolerance ${String(r)}); raise maxIterations or tolerance`),this.algorithm=e,this.iterations=t,this.tolerance=r,this.name="ConvergenceError",this.code="E_NOT_CONVERGED"}}class uc extends Error{constructor(e,t,r){super(`cannot walk the shortest path from node ${String(e)} to node ${String(t)}: the predecessor array has a ${r}`),this.source=e,this.target=t,this.reason=r,this.name="PathWalkError",this.code="E_BAD_PATH"}}class ZA extends Error{constructor(e){super(`${e}: the accelerator's shortest-path counts overflowed, so its scores are wrong; run the CPU ${e} instead`),this.algorithm=e,this.name="PathCountOverflowError",this.code="E_PATH_COUNT_OVERFLOW"}}function Uf(n,e){let t=0,r=n.length-1;for(;t<r;){const o=t+r>>1;n[o+1]<=e?t=o+1:r=o}return t}class Yn{constructor(e,t=!1){this.size=0,this.tieBreakByIndex=t,this.heap=new Uint32Array(e),this.slot=new Uint32Array(e).fill(x),this.key=new Float64Array(e)}isEmpty(){return this.size===0}has(e){return this.slot[e]!==x}keyOf(e){return this.key[e]}peekKey(){return this.size===0?1/0:this.key[this.heap[0]]}push(e,t){if(!(e>=0&&e<this.slot.length))throw new RangeError(`Node index ${String(e)} is outside the heap's ${String(this.slot.length)} nodes`);this.key[e]=t,this.heap[this.size]=e,this.slot[e]=this.size,this.size++,this.siftUp(this.size-1)}pushOrDecrease(e,t){const r=this.slot[e];if(r===x){this.push(e,t);return}t<this.key[e]&&(this.key[e]=t,this.siftUp(r))}pop(){const e=this.heap[0];if(this.slot[e]=x,this.size--,this.size>0){const t=this.heap[this.size];this.heap[0]=t,this.slot[t]=0,this.siftDown(0)}return e}before(e,t){const r=this.key[e],o=this.key[t];return r<o||this.tieBreakByIndex&&r===o&&e<t}siftUp(e){let t=e;const r=this.heap[t];for(;t>0;){const o=t-1>>1,s=this.heap[o];if(!this.before(r,s))break;this.heap[t]=s,this.slot[s]=t,t=o}this.heap[t]=r,this.slot[r]=t}siftDown(e){let t=e;const r=this.heap[t];for(;;){const o=2*t+1;if(o>=this.size)break;const s=o+1,i=s<this.size&&this.before(this.heap[s],this.heap[o])?s:o,a=this.heap[i];if(!this.before(a,r))break;this.heap[t]=a,this.slot[a]=t,t=i}this.heap[t]=r,this.slot[r]=t}}function Ff(n,e,t,r){const o=[];let s=r;for(;s!==t;){if(o.length>=n.nodeCount-1)throw new uc(t,r,"cycle");const i=e[s];if(!(i<n.arcCount))throw new uc(t,r,"gap");o.push(i),s=Uf(n.rowPtr,i)}return o}function Jr(n,e,t,r){const o=xe(n,r);if(o===t)return Uint32Array.of(t);if(e[o]===x)return new Uint32Array(0);const s=[o,...Ff(n,e,t,o).map(a=>Uf(n.rowPtr,a))],i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Zr(n,e,t,r){const o=xe(n,r);if(o===t||e[o]===x)return new Uint32Array(0);const s=Ff(n,e,t,o).map(a=>n.arcToEdge[a]),i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Bf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=new Float64Array(o).fill(1/0),l=new Uint32Array(o).fill(x),u=new Yn(o),d=t.cutoff??1/0;for(c[r]=0,u.push(r,0);!u.isEmpty();){const f=u.pop(),h=c[f],g=s[f+1];for(let w=s[f];w<g;w++){const p=a===null?1:a[w],m=i[w],y=h+p;y<c[m]&&y<=d&&(c[m]=y,l[m]=w,u.pushOrDecrease(m,y))}}return{dist:c,predArc:l,pathTo:f=>Jr(n,l,r,f),pathEdges:f=>Zr(n,l,r,f)}}const zf=5792;function e3(n,e){if(e.weighted===!1)return{w:null,negative:!1};if(e.weights!==void 0&&e.weights.length!==n.arcCount)throw Q(new RangeError(`allPairsShortestPath: the weights override has ${String(e.weights.length)} entries; the snapshot has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");const t=e.weights??n.weights;if(t===null)return{w:null,negative:!1};let r=!0,o=!1;for(let s=0;s<n.arcCount;s++){const i=t[s];if(!Number.isFinite(i)){const a=e.weights===void 0&&!Number.isNaN(i)?"; a finite weight above the f32 range (3.4e38) becomes Infinity in the snapshot's f32 arc weights -- pass the exact f64 weights through the weights override":"";throw Q(new RangeError(`allPairsShortestPath: arc ${String(s)} has weight ${String(i)}; weights must be finite${a}`),"E_BAD_WEIGHT")}r&&(r=i===1),o||(o=i<0)}return{w:r?null:t,negative:o}}function t3(n,e,t,r,o){const{nodeCount:s,rowPtr:i,colIdx:a}=n;r.fill(1/0);for(let c=0;c<s;c++){const l=c*s;for(let u=i[c];u<i[c+1];u++){const d=a[u],f=e===null?1:e[u];d!==c&&f<r[l+d]&&(r[l+d]=f,o!==null&&(o[l+d]=u))}r[l+c]=0}for(let c=0;c<s;c++){const l=c*s,u=r.subarray(l,l+s);for(let d=0;d<s;d++){const f=d*s,h=r[f+c];if(h===1/0)continue;const g=r.subarray(f,f+s);if(o===null)for(let w=0;w<g.length;w++){const p=h+u[w];p<g[w]&&(g[w]=p)}else{const w=o.subarray(l,l+s),p=o.subarray(f,f+s);for(let m=0;m<g.length;m++){const y=h+u[m];y<g[m]&&(g[m]=y,p[m]=w[m])}}}if(t){for(let d=0;d<s;d++)if(r[d*s+d]<0)return!0}}return!1}function n3(n,e){for(let t=0;t<n.nodeCount;t++)for(let r=n.rowPtr[t];r<n.rowPtr[t+1];r++)if(e[r]<0&&(!n.directed||n.colIdx[r]===t))return!0;return!1}function r3(n,e,t){const{nodeCount:r,rowPtr:o,colIdx:s}=n,i=new Uint32Array(r);e.fill(1/0);for(let a=0;a<r;a++){const c=e.subarray(a*r,a*r+r),l=t?.subarray(a*r,a*r+r);c[a]=0,i[0]=a;let u=1;for(let d=0;d<u;d++){const f=i[d],h=c[f]+1;for(let g=o[f];g<o[f+1];g++){const w=s[g];c[w]===1/0&&(c[w]=h,l!==void 0&&(l[w]=g),i[u++]=w)}}}}function o3(n,e,t,r){const{nodeCount:o,rowPtr:s,colIdx:i}=n,a=new Yn(o);t.fill(1/0);for(let c=0;c<o;c++){const l=t.subarray(c*o,c*o+o),u=r?.subarray(c*o,c*o+o);for(l[c]=0,a.push(c,0);!a.isEmpty();){const d=a.pop(),f=l[d];for(let h=s[d];h<s[d+1];h++){const g=i[h],w=f+e[h];w<l[g]&&(l[g]=w,u!==void 0&&(u[g]=h),a.pushOrDecrease(g,w))}}}}function s3(n,e,t,r){if(r==="floyd-warshall")return"floyd-warshall";if(e===null)return"bfs";if(t){if(r==="per-source")throw Q(new Error('allPairsShortestPath: method "per-source" runs Dijkstra, which is incorrect with a negative weight; use "auto" or "floyd-warshall"'),"E_BAD_OPTION");return"floyd-warshall"}const o=n.nodeCount;return r==="per-source"||3*n.arcCount<o*o?"dijkstra":"floyd-warshall"}function Gf(n,e={}){const t=n.nodeCount,r=e.maxNodes??zf;if(!(t<=r))throw lc("allPairsShortestPath",t,r,(e.paths===!0?12:8)*t*t);const{w:o,negative:s}=e3(n,e),i=s3(n,o,s,e.method),a=new Float64Array(t*t),c=e.paths===!0?new Uint32Array(t*t).fill(x):null;let l=!1;i==="bfs"?r3(n,a,c):i==="dijkstra"&&o!==null?o3(n,o,a,c):l=s&&o!==null&&n3(n,o)||t3(n,o,s,a,c),l&&a.fill(Number.NaN);const u=(d,f)=>{const h=xe(n,d),g=xe(n,f);if(c===null)throw Q(new Error("allPairsShortestPath: pass paths: true to walk shortest paths"),"E_BAD_OPTION");if(l)throw new uc(h,g,"cycle");return c.subarray(h*t,h*t+t)};return{dist:a,n:t,hasNegativeCycle:l,method:i,predArc:c,pathTo:(d,f)=>Jr(n,u(d,f),xe(n,d),f),pathEdges:(d,f)=>Zr(n,u(d,f),xe(n,d),f)}}function Wf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=t.cutoff??1/0,l=new Float64Array(o).fill(1/0),u=new Uint32Array(o).fill(x);l[r]=0;const d=()=>{let g=!1;for(let w=0;w<o;w++){const p=l[w];if(p===1/0)continue;const m=s[w+1];for(let y=s[w];y<m;y++){const b=i[y],v=p+(a===null?1:a[y]);v<l[b]&&v<=c&&(l[b]=v,u[b]=y,g=!0)}}return g};let f=!1;for(let g=0;g<o-1&&!f;g++)f=!d();const h=!f&&d();return{dist:l,predArc:u,hasNegativeCycle:h,pathTo:g=>Jr(n,u,r,g),pathEdges:g=>Zr(n,u,r,g)}}const i3=2654435769;function a3(n,e){const t=Array.from({length:n},(o,s)=>s);let r=i3;for(let o=0;o<e;o++){r=r+1831565813>>>0;let s=Math.imul(r^r>>>15,r|1);s=s+Math.imul(s^s>>>7,s|61)^s;const i=((s^s>>>14)>>>0)/2**32,a=o+Math.floor(i*(n-o));[t[o],t[a]]=[t[a],t[o]]}return t.slice(0,e)}function is(n,e,t,r="betweenness"){const o=n.nodeCount,s=e===void 0?void 0:Array.from(ss(n,e));if(t!==void 0&&(!Number.isInteger(t)||t<0||t>o))throw Q(new RangeError(`${r}: k must be an integer in [0, ${o}], got ${t}`),"E_BAD_OPTION");if(s!==void 0){for(const i of s)if(!Number.isInteger(i)||i<0||i>=o)throw Q(new RangeError(`${r}: sources must be node indices in [0, ${o}), got ${i}`),"E_BAD_NODE");if(t!==void 0&&t!==s.length)throw Q(new RangeError(`${r}: k (${t}) must be absent or equal sources.length (${s.length})`),"E_BAD_OPTION");return s}return t===void 0?Array.from({length:o},(i,a)=>a):a3(o,t)}function Vf(n,e,t,r,o,s){const{nodeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Int32Array(i).fill(-1),d=new Float64Array(i),f=new Float64Array(i),h=new Uint32Array(i);for(const g of e){let w=0,p=0;for(u[g]=0,d[g]=1,h[p++]=g;w<p;){const m=h[w++],y=u[m]+1;let b=-1;for(let v=a[m],A=a[m+1];v<A;v++){const E=c[v];E===b||o!==null&&!_e(o,l[v])||(b=E,u[E]<0&&(u[E]=y,h[p++]=E),u[E]===y&&(d[E]+=d[m]))}}for(let m=p-1;m>=0;m--){const y=h[m],b=u[y]+1;let v=-1;for(let A=a[y],E=a[y+1];A<E;A++){const I=c[A];if(!(I===v||o!==null&&!_e(o,l[A]))&&(v=I,u[I]===b)){const k=d[y]/d[I]*(1+f[I]);f[y]+=k,r!==null&&(r[l[A]]+=k)}}t!==null&&y!==g&&(t[y]+=s?f[y]+1:f[y])}t!==null&&s&&(t[g]+=p-1);for(let m=0;m<p;m++){const y=h[m];u[y]=-1,d[y]=0,f[y]=0}}}function jf(n,e,t,r){const o=n.directed?1:2,s=t===!0&&r>0?r:o;for(let i=0;i<e.length;i++)e[i]/=s;return s}function qf(n,e={}){const t=n.nodeCount,r=is(n,e.sources,e.k),o=new Float64Array(t),s=e.endpoints===!0;Vf(n,r,o,null,null,s);const i=jf(n,o,e.normalized,s?t*(t-1):(t-1)*(t-2));return{scores:o,iterations:r.length,converged:!0,divisor:i}}function dc(n,e={}){const t=n.nodeCount,r=e.alive??null;if(r!==null&&r.length<Math.ceil(n.edgeCount/32))throw Q(new RangeError(`edgeBetweennessCentrality: alive covers fewer than ${n.edgeCount} edges`),"E_BAD_OPTION");const o=new Float64Array(n.edgeCount);Vf(n,is(n,e.sources,e.k),null,o,r,!1);const s=jf(n,o,e.normalized,(t-1)*(t-2));return{scores:o,divisor:s}}function fc(n,e,t){return{pathTo:r=>Jr(n,t,e,r),pathEdges:r=>Zr(n,t,e,r)}}function ai(n,e,t="start"){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`${t} node index ${String(r)} is out of range for ${String(n.nodeCount)} nodes`),"E_BAD_NODE");return r}function Hf(n,e){return e===void 0?x:ai(n,e,"target")}function ci(n,e){if(e===void 0)return null;const{rowPtr:t,nodeCount:r}=n;if(e.length!==n.arcCount)throw Q(new RangeError(`arcOrder has ${String(e.length)} entries, expected ${String(n.arcCount)}`),"E_BAD_OPTION");const o=new Uint8Array(e.length);for(let s=0;s<r;s++){const i=t[s],a=t[s+1];for(let c=i;c<a;c++){if(e[c]<i||e[c]>=a)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} is not an arc of node ${String(s)}`),"E_BAD_OPTION");if(o[e[c]]===1)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} repeats an arc of node ${String(s)}`),"E_BAD_OPTION");o[e[c]]=1}}return e}function Kf(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=ci(n,t.arcOrder),c=new Uint32Array(o).fill(x),l=new Uint32Array(o).fill(x),u=new Uint32Array(o).fill(x),d=new Uint32Array(o),f=t.maxDepth??x,h=Hf(n,t.target);let g=0,w=0;for(d[w++]=r,u[r]=0;g<w;){const p=d[g++];if(p===h)break;const m=u[p];if(m>=f)continue;const y=s[p+1];for(let b=s[p];b<y;b++){const v=a===null?b:a[b],A=i[v];u[A]===x&&(u[A]=m+1,c[A]=p,l[A]=v,d[w++]=A)}}return{order:d.subarray(0,w),parent:c,depth:u,visitedCount:w,predArc:l,...fc(n,r,l)}}function c3(n,e,t,r){const{rowPtr:o,colIdx:s,arcToEdge:i}=n;let a=o[t],c=o[t+1];for(;a<c;){const u=a+c>>>1;s[u]<r?a=u+1:c=u}const l=o[t+1];for(;a<l&&s[a]===r&&i[a]!==i[e];)a++;return a}function l3(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.alpha??1,c=t.beta??18;let l=null;const u=new Uint32Array(o).fill(x),d=new Uint32Array(o).fill(x),f=new Uint32Array(o).fill(x),h=new Uint32Array(o);h[0]=r,f[r]=0;let g=0,w=1;const p=n.inDegree();let m=n.arcCount-p[r],y=!1;for(let b=0;g<w;b++){const v=w-g;if(y)y=v>=o/c;else{let E=0;for(let I=g;I<w;I++)E+=s[h[I]+1]-s[h[I]];y=E>m/a}const A=w;if(y){l??(l=n.reverse());for(let E=0;E<o;E++){if(f[E]!==x)continue;const I=l.rowPtr[E+1];for(let k=l.rowPtr[E];k<I;k++){const N=l.colIdx[k];if(f[N]===b){u[E]=N,d[E]=n.directed?l.fwdArc[k]:c3(n,k,N,E),f[E]=b+1,h[w++]=E;break}}}}else{for(let E=g;E<A;E++){const I=h[E],k=s[I+1];for(let N=s[I];N<k;N++){const C=i[N];f[C]===x&&(u[C]=I,d[C]=N,f[C]=b+1,h[w++]=C)}}h.subarray(A,w).sort()}for(let E=A;E<w;E++)m-=p[h[E]];g=A}return{order:h.subarray(0,w),parent:u,depth:f,visitedCount:w,predArc:d,...fc(n,r,d)}}const hc=2;function Yf(n,e={}){const{nodeCount:t}=n,r=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n],o=new Uint8Array(t).fill(hc),s=new Uint32Array(t);for(let a=0;a<t;a++){if(o[a]!==hc)continue;o[a]=0;let c=0,l=0;for(s[l++]=a;c<l;){const u=s[c++];for(const{rowPtr:d,colIdx:f}of r){const h=d[u+1];for(let g=d[u];g<h;g++){const w=f[g];if(o[w]===hc)o[w]=o[u]^1,s[l++]=w;else if(o[w]===o[u])return{bipartite:!1,sides:null}}}}}const i=At(t);for(let a=0;a<t;a++)o[a]===1&&pn(i,a,!0);return{bipartite:!0,sides:i}}function gc(n,e,t){const{rowPtr:r,colIdx:o,weights:s}=e,i=new Float64Array(n).fill(1/0),a=new Uint32Array(n),c=s===null?null:new Yn(n),l=new Uint8Array(n);return{dist:i,reached:a,run(u){let d=0;if(i[u]=0,a[d++]=u,c===null||s===null){for(let f=0;f<d;f++){const h=a[f];if(!(i[h]>=t))for(let g=r[h],w=r[h+1];g<w;g++){const p=o[g];i[p]===1/0&&(i[p]=i[h]+1,a[d++]=p)}}return d}for(c.push(u,0);!c.isEmpty();){const f=c.pop();if(l[f]=1,!(i[f]>=t))for(let h=r[f],g=r[f+1];h<g;h++){const w=o[h];if(l[w]===1)continue;const p=i[f]+s[h];p<i[w]&&(i[w]===1/0&&(a[d++]=w),i[w]=p,c.pushOrDecrease(w,p))}}return d},clear(u){for(let d=0;d<u;d++)i[a[d]]=1/0,l[a[d]]=0}}}function Xf(n,e,t,r,o){return n.harmonic===!0?n.normalized===!0&&e>1?o/(e-1):o:r<=0?0:n.normalized===!0&&e>1?t/r/(e-1):1/r}function Qf(n,e,t,r){const o=n.run(r);let s=0,i=0;for(let a=1;a<o;a++){const c=n.dist[n.reached[a]];s+=c,i+=c>0?1/c:0}return n.clear(o),Xf(e,t,o-1,s,i)}function wc(n,e,t){const r=e.weighted===!0;if(!t||!n.directed)return{rowPtr:n.rowPtr,colIdx:n.colIdx,weights:r?e.weights??n.weights:null};const o=n.reverse(),s=e.weights;let i=null;return r&&(i=s===void 0?o.weights:Float64Array.from(o.fwdArc,a=>s[a])),{rowPtr:o.rowPtr,colIdx:o.colIdx,weights:i}}function Jf(n,e={}){const t=n.nodeCount,r=e.cutoff??1/0,o=new Float64Array(t);if(e.sources===void 0&&e.k===void 0){const u=gc(t,wc(n,e,!1),r);for(let d=0;d<t;d++)o[d]=Qf(u,e,t,d);return{scores:o,iterations:t,converged:!0,sourcesUsed:t}}const s=is(n,e.sources,e.k,"closenessCentrality"),i=gc(t,wc(n,e,!0),r),a=new Float64Array(t),c=new Float64Array(t),l=new Uint32Array(t);for(const u of s){const d=i.run(u);for(let f=1;f<d;f++){const h=i.reached[f],g=i.dist[h];a[h]+=g,c[h]+=g>0?1/g:0,l[h]+=1}i.clear(d)}for(let u=0;u<t;u++)o[u]=Xf(e,t,l[u],a[u],c[u]);return{scores:o,iterations:s.length,converged:!0,sourcesUsed:s.length}}function u3(n,e,t={}){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`nodeClosenessCentrality: node must be an index in [0, ${n.nodeCount}), got ${r}`),"E_BAD_NODE");const o=gc(n.nodeCount,wc(n,t,!1),t.cutoff??1/0);return Qf(o,t,n.nodeCount,r)}function Zf(n,e,t,r,o){let s=n.rowPtr[t];const i=n.rowPtr[t+1];let a=e.rowPtr[r];const c=e.rowPtr[r+1];let l=0;for(;s<i&&a<c;){const u=n.colIdx[s],d=e.colIdx[a];if(u===d)for(l+=o===void 0?1:o(u),s++,a++;a<c&&e.colIdx[a]===d;)a++;else u<d?s++:a++}return l}function d3(n,e,t,r={}){return Zf(n,r.directed===!0?n.reverse():n,e,t)}class eo{constructor(e){this.parent=new Uint32Array(e),this.rank=new Uint32Array(e);for(let t=0;t<e;t++)this.parent[t]=t}find(e){let t=e;for(;this.parent[t]!==t;)this.parent[t]=this.parent[this.parent[t]],t=this.parent[t];return t}union(e,t){const r=this.find(e),o=this.find(t);return r===o?!1:(this.rank[r]<this.rank[o]?this.parent[r]=o:this.rank[r]>this.rank[o]?this.parent[o]=r:(this.parent[o]=r,this.rank[r]++),!0)}toLabels(){const e=new Uint32Array(this.parent.length);for(let t=0;t<e.length;t++)e[t]=this.find(t);return Je(e)}}function We(n,e){let t=null;return{labels:n,count:e,groups(){if(t===null){const r=new Uint32Array(e);for(let i=0;i<n.length;i++)r[n[i]]++;const o=[];for(let i=0;i<e;i++)o.push(new Uint32Array(r[i]));const s=new Uint32Array(e);for(let i=0;i<n.length;i++){const a=n[i];o[a][s[a]++]=i}t=o}return t}}}function eh(n){const e=new eo(n.nodeCount),t=n.edgeList();for(let s=0;s<n.edgeCount;s++)e.union(t.src[s],t.dst[s]);const{labels:r,count:o}=e.toLabels();return We(r,o)}function th(n){if(n.directed)throw Q(new Error("Connected components requires an undirected graph. Use weaklyConnectedComponents, or pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");return eh(n)}function nh(n){return eh(n)}function rh(n,e){const{rowPtr:t,colIdx:r}=n;for(let o=0;o<n.nodeCount;o++){let s=-1;for(let i=t[o],a=t[o+1];i<a;i++)r[i]!==s&&(s=r[i],e[o]++)}}function f3(n,e={}){const t=new Float64Array(n.nodeCount),r=n.directed?e.mode??"total":"out";r!=="in"&&rh(n,t),r!=="out"&&rh(n.reverse(),t);const o=n.nodeCount-1;if(e.normalized===!0&&o>0)for(let s=0;s<t.length;s++)t[s]/=o;return t}function oh(n){const{src:e,dst:t}=n.edgeList(),r=new Uint32Array(n.nodeCount),o=new Uint32Array(n.nodeCount);for(let s=0;s<e.length;s++)o[e[s]]++,r[t[s]]++;return{inDegree:r,outDegree:o}}class sh{constructor(e){this.min=new Yn(e,!0)}isEmpty(){return this.min.isEmpty()}has(e){return this.min.has(e)}keyOf(e){return-this.min.keyOf(e)}push(e,t){this.min.push(e,-t)}pushOrIncrease(e,t){this.min.pushOrDecrease(e,-t)}pop(){return this.min.pop()}}function ih(n){const e=new Uint32Array(n.arcCount),t=n.rowPtr.slice(0,n.nodeCount),{src:r}=n.edgeList();for(let o=0;o<n.edgeCount;o++)e[t[r[o]]++]=n.edgeToArc[o];return e}function ah(n,e,t){const r=new Float64Array(n.nodeCount);for(let o=0;o<n.nodeCount;o++){let s=0;for(let i=n.rowPtr[o];i<n.rowPtr[o+1];i++)s+=t===null?1:t[e[i]];r[o]=s}return r}function pc(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t];if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function h3(n,e,t){if(n===void 0)return null;if(n.length!==e)throw Q(new RangeError(`${t} has ${String(n.length)} entries; the graph has ${String(e)} nodes`),"E_BAD_OPTION");const r=Float64Array.from(n);return pc(r),r}function ch(n,e){if(e===void 0)return n.weights;if(e.length!==n.arcCount)throw Q(new RangeError(`weights has ${String(e.length)} entries; the graph has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");return e}function g3(n){if(n<0||n>1)throw Q(new Error("Damping factor must be between 0 and 1"),"E_BAD_OPTION")}class w3{constructor(e,t={}){if(!e.directed)throw Q(new Error("DeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.active=new Uint8Array(e.nodeCount).fill(1)}compute(e={}){return this.run(e,!1)}update(e,t={}){const{s:r}=this,o=r.reverse(),s=new Uint8Array(r.nodeCount);for(let i=0;i<e.length;i++){const a=e[i];if(!(!Number.isInteger(a)||a<0||a>=r.nodeCount)){s[a]=1;for(let c=o.rowPtr[a];c<o.rowPtr[a+1];c++)s[o.colIdx[c]]=1;for(let c=r.rowPtr[a];c<r.rowPtr[a+1];c++)s[r.colIdx[c]]=1}}return this.active=s,this.run(t,e.length>0)}run(e,t){const r=e.dampingFactor??.85,o=e.tolerance??1e-6,s=e.maxIterations??100,i=e.deltaThreshold??o/10;g3(r);const{s:a,order:c,scores:l}=this,u=a.nodeCount;if(u===0)return new Float64Array(0);const d=h3(e.personalization,u,"personalization"),f=e.weighted===!0?this.weights:null,h=(1-r)/u;let g=this.active.reduce((w,p)=>w+p,0);for(let w=0;(g>0||w===0&&t)&&w<s;w++){const p=new Float64Array(u);let m=0;for(let b=0;b<u;b++)a.rowPtr[b]===a.rowPtr[b+1]&&(m+=l[b]+this.deltas[b]);if(m>0){const b=r*m/u;for(let v=0;v<u;v++)p[v]+=d===null?b:b*d[v]}for(let b=0;b<u;b++){const v=this.deltas[b];if(this.active[b]===0||Math.abs(v)<i)continue;l[b]+=v;const A=this.outW[b];if(A>0)for(let E=a.rowPtr[b];E<a.rowPtr[b+1];E++){const I=c[E];p[a.colIdx[I]]+=r*v*((f===null?1:f[I])/A)}}let y=0;g=0;for(let b=0;b<u;b++){p[b]+=d===null?h:(1-r)*d[b];const v=Math.abs(p[b]);y=Math.max(y,v),this.active[b]=v>=i?1:0,g+=this.active[b]}if(this.deltas=p,y<o)break}return pc(l),l.slice()}}class p3{constructor(e,t={}){if(!e.directed)throw Q(new Error("PriorityDeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.heap=new sh(e.nodeCount);for(let r=0;r<e.nodeCount;r++)this.heap.push(r,1/e.nodeCount)}computeWithPriority(e={}){const t=e.dampingFactor??.85,r=e.tolerance??1e-6,o=e.maxIterations??100,s=e.deltaThreshold??r/10,{s:i,order:a,scores:c,deltas:l,heap:u}=this,d=i.nodeCount,f=e.weighted===!0?this.weights:null;let h=0,g=0;for(;!u.isEmpty()&&h<o;){const w=u.pop(),p=l[w];if(Math.abs(p)<s)continue;c[w]+=p,l[w]=0;const m=f===null?i.rowPtr[w+1]-i.rowPtr[w]:this.outW[w];if(m>0)for(let y=i.rowPtr[w];y<i.rowPtr[w+1];y++){const b=a[y],v=i.colIdx[b],A=l[v]+t*p*((f===null?1:f[b])/m);l[v]=A,Math.abs(A)>=s&&u.pushOrIncrease(v,Math.abs(A))}if(g++,g%1e3===0){let y=0;for(let b=0;b<d;b++)y=Math.max(y,Math.abs(l[b]));if(y<r)break}h++}for(let w=0;w<d;w++)Math.abs(l[w])>=s&&(c[w]+=l[w]);return pc(c),c.slice()}}const mc=0,yc=1,m3=2;function bc(n){return{state:new Uint8Array(n),parent:new Uint32Array(n).fill(x),predArc:new Uint32Array(n).fill(x),depth:new Uint32Array(n).fill(x),cursor:new Uint32Array(n),stack:new Uint32Array(n),pre:new Uint32Array(n),post:new Uint32Array(n),preCount:0,postCount:0,backArc:!1}}function y3(n,e,t,r){const{rowPtr:o,colIdx:s}=n,{state:i,parent:a,predArc:c,depth:l,cursor:u,pre:d}=t,f=u[e]++,h=r===null?f:r[f],g=s[h];return i[g]===mc?(i[g]=yc,a[g]=e,c[g]=h,l[g]=l[e]+1,u[g]=o[g],d[t.preCount++]=g,g):(i[g]===yc&&(t.backArc=!0),x)}function vc(n,e,t,r,o){const{rowPtr:s}=n,{state:i,depth:a,cursor:c,stack:l,pre:u,post:d}=t;let f=0;if(i[e]=yc,a[e]=0,c[e]=s[e],u[t.preCount++]=e,l[f++]=e,e!==r)for(;f>0;){const h=l[f-1];if(c[h]<s[h+1]){const g=y3(n,h,t,o);if(g!==x&&(l[f++]=g,g===r))return}else i[h]=m3,d[t.postCount++]=h,f--}}function lh(n,e,t={}){const r=ai(n,e),o=ci(n,t.arcOrder),s=Hf(n,t.target),i=bc(n.nodeCount),a=t.order==="post";return vc(n,r,i,a?x:s,o),{order:a?i.post.subarray(0,i.postCount):i.pre.subarray(0,i.preCount),parent:i.parent,depth:i.depth,visitedCount:i.preCount,predArc:i.predArc,...fc(n,r,i.predArc)}}function b3(n){return n.directed?v3(n):A3(n)}function v3(n){const{nodeCount:e}=n,t=bc(e);for(let r=0;r<e&&!t.backArc;r++)t.state[r]===mc&&vc(n,r,t,x,null);return t.backArc}function A3(n){const{nodeCount:e,rowPtr:t,colIdx:r}=n,o=new eo(e);for(let s=0;s<e;s++){const i=t[s+1];for(let a=t[s];a<i;a++){const c=r[a];if(c===s||c>s&&(a===t[s]||r[a-1]!==c)&&!o.union(s,c))return!0}}return!1}function E3(n,e={}){if(!n.directed)throw Q(new Error("Topological sort requires a directed graph"),"E_NEEDS_DIRECTED");const t=ci(n,e.arcOrder),r=bc(n.nodeCount);for(let o=0;o<n.nodeCount&&!r.backArc;o++)r.state[o]===mc&&vc(n,o,r,x,t);return r.backArc?null:r.post.reverse()}function uh(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=e.startVector;if(s!==void 0&&s.length!==t)throw Q(new Error(`eigenvectorCentrality: startVector has ${String(s.length)} entries for ${String(t)} nodes`),"E_BAD_OPTION");let i=new Float64Array(t);if(t===0)return{scores:i,iterations:0,converged:!0};const a=_3(n,e.mode??"in");if(I3(a,t))return{scores:i,iterations:0,converged:!0};for(let d=0;d<t;d++)a.rowPtr[d+1]>a.rowPtr[d]&&(i[d]=s===void 0?1:s[d]);fh(i);let c=new Float64Array(t),l=0,u=!1;for(;l<r&&!u;l++){for(let f=0;f<t;f++){let h=i[f];const g=a.rowPtr[f+1];for(let w=a.rowPtr[f];w<g;w++)h+=i[a.colIdx[w]];c[f]=h}fh(c);let d=0;for(let f=0;f<t;f++)d+=Math.abs(c[f]-i[f]);[i,c]=[c,i],u=d<t*o}if(!u)throw new Mf("eigenvectorCentrality",r,o);return e.normalized!==!1&&dh(i),{scores:i,iterations:l,converged:u}}function dh(n){let e=1/0,t=0;for(const s of n)e=Math.min(e,s),t=Math.max(t,s);const r=t-e,o=t>0?1:0;for(let s=0;s<n.length;s++)n[s]=r>0?(n[s]-e)/r:o}function _3(n,e){const t=n.nodeCount,r=!n.directed||e==="out"?n:n.reverse(),o=n.directed&&e==="total",s=o?n.rowPtr:new Uint32Array(t+1),i=o?n.colIdx:new Uint32Array(0),a=new Uint32Array(t+1),c=new Uint32Array(r.colIdx.length+i.length);let l=0;for(let u=0;u<t;u++){let d=r.rowPtr[u];const f=r.rowPtr[u+1];let h=s[u];const g=s[u+1],w=l;for(;d<f||h<g;){const p=h>=g||d<f&&r.colIdx[d]<=i[h]?r.colIdx[d++]:i[h++];(l===w||c[l-1]!==p)&&(c[l++]=p)}a[u+1]=l}return{rowPtr:a,colIdx:c.subarray(0,l)}}function I3(n,e){const t=new Uint32Array(e);for(const s of n.colIdx)t[s]++;const r=new Uint32Array(e);let o=0;for(let s=0;s<e;s++)t[s]===0&&(r[o++]=s);for(let s=0;s<o;s++){const i=r[s];for(let a=n.rowPtr[i];a<n.rowPtr[i+1];a++)--t[n.colIdx[a]]===0&&(r[o++]=n.colIdx[a])}return o===e}function fh(n){let e=0;for(const t of n)e+=t*t;if(e=Math.sqrt(e),e>0)for(let t=0;t<n.length;t++)n[t]/=e}function to(n,e){const t=new Uint32Array(e),r=e>0&&_e(n,0);let o=!1;for(let s=0;s<e;s++)_e(n,s)!==r&&(t[s]=1,o=!0);return e===0?We(t,0):We(t,o?2:1)}function Ac(n,e){const t=n.edgeList(),r=new Float64Array(n.edgeCount);for(let o=0;o<n.edgeCount;o++)r[o]=e!==void 0?e[t.arc[o]]:t.weights?.[o]??1;return r}function Ec(n,e,t,r,o){const{src:s,dst:i}=n.edgeList(),a=[];for(let c=0;c<n.edgeCount;c++){const l=_e(e,s[c]);(t?l&&!_e(e,i[c]):l!==_e(e,i[c]))&&(!o||r[c]>0)&&a.push(c)}return Uint32Array.from(a)}function k3(n,e){const t=n.nodeCount,r=n.edgeCount,{src:o,dst:s}=n.edgeList(),i=new Uint32Array(2*r),a=new Uint32Array(2*r);i.set(o),i.set(s,r),a.set(s),a.set(o,r);const c=sc({directed:!0,nodeCount:t,src:i,dst:a}),{rowPtr:l,colIdx:u,arcToEdge:d,edgeToArc:f}=c,h=c.arcCount,g=new Float64Array(h),w=new Uint32Array(h),p=new Uint8Array(h);for(let E=0;E<t;E++)for(let I=l[E];I<l[E+1];I++){const k=I>l[E]&&u[I]===u[I-1]?w[I-1]:I;w[I]=k;const N=d[I];(N<r||!n.directed)&&(p[k]=1,g[k]+=Math.max(e[N<r?N:N-r],0))}const m=new Uint32Array(h);for(let E=0;E<h;E++)if(w[E]===E){const I=d[E];m[E]=w[f[I<r?I+r:I-r]]}const y=new Uint32Array(h),b=new Uint32Array(t),v=new Uint8Array(h),A=(E,I)=>{v[I]===0&&(v[I]=1,y[l[E]+b[E]++]=I)};for(let E=0;E<r;E++)A(o[E],w[f[E]]),n.directed||A(s[E],w[f[E+r]]);return{rowPtr:l,colIdx:u,arcToEdge:d,capacity:g,groupOf:w,twin:m,order:y,placed:b,inOrder:v,real:p}}function _c(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=n.nodeCount;if(!(Number.isInteger(o)&&o>=0&&o<i&&Number.isInteger(s)&&s>=0&&s<i))throw Q(new RangeError(`source ${String(o)} and sink ${String(s)} must be node indices below ${i}`),"E_BAD_NODE");if(o===s)throw Q(new RangeError(`source and sink are the same node (${o})`),"E_BAD_OPTION");const a=Ac(n,r.weights),c=k3(n,a),l=new Float64Array(c.colIdx.length),u=new Uint32Array(i),d=r.algorithm==="ford-fulkerson"?C3:x3;let f=0;for(;d(c,o,s,u);)f+=S3(c,o,s,u,l);const h=N3(c,o);return{...to(h,n.nodeCount),maxFlow:f,flow:P3(n,c,a,l),sourceSide:h,cutEdges:Ec(n,h,n.directed,a,!0)}}function S3(n,e,t,r,o){const{colIdx:s,twin:i}=n;let a=1/0;for(let c=t;c!==e;c=s[i[r[c]]])a=Math.min(a,n.capacity[r[c]]);for(let c=t;c!==e;){const l=r[c],u=i[l];n.capacity[l]-=a,n.capacity[u]+=a,n.inOrder[u]===0&&(n.inOrder[u]=1,n.order[n.rowPtr[c]+n.placed[c]++]=u),n.real[l]===1?o[l]+=a:o[u]-=a,c=s[u]}return a}function P3(n,e,t,r){const o=n.edgeCount,s=new Float64Array(o),{rowPtr:i,colIdx:a,arcToEdge:c,groupOf:l}=e;for(let u=0;u<n.nodeCount;u++)for(let d=i[u];d<i[u+1];d++){const f=a[d];if(l[d]!==d||f<=u)continue;const h=r[d]-r[e.twin[d]];if(h===0)continue;const g=h>0?d:e.twin[d],w=i[a[e.twin[g]]+1];let p=Math.abs(h),m=-1,y=1;for(let b=g;b<w&&l[b]===g;b++){const v=c[b];if(!(v>=o&&n.directed)){if(m>=0){const A=Math.min(p,Math.max(t[m],0));s[m]+=y*A,p-=A}m=v<o?v:v-o,y=v<o?1:-1}}m>=0&&(s[m]+=y*p)}return s}function hh(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=_c(n,o,s,{...r,algorithm:r.algorithm??"ford-fulkerson"});return{...to(i.sourceSide,n.nodeCount),cutValue:i.maxFlow,side:i.sourceSide,cutEdges:i.cutEdges}}function x3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n;r.fill(x);const l=new Uint32Array(r.length);let u=0,d=0;for(l[d++]=e;u<d;){const f=l[u++],h=o[f]+a[f];for(let g=o[f];g<h;g++){const w=i[g],p=s[w];if(c[w]>0&&p!==e&&r[p]===x){if(r[p]=w,p===t)return!0;l[d++]=p}}}return!1}function C3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n,l=r.length;r.fill(x);const u=new Uint8Array(l),d=new Uint32Array(l),f=new Uint32Array(l);let h=0;for(d[h++]=e,u[e]=1,f[e]=o[e];h>0;){const g=d[h-1],w=f[g]++;if(w>=o[g]+a[g]){h--;continue}const p=i[w],m=s[p];if(c[p]>0&&u[m]===0){if(r[m]=p,m===t)return!0;u[m]=1,f[m]=o[m],d[h++]=m}}return!1}function N3(n,e){const{rowPtr:t,colIdx:r,order:o,placed:s,capacity:i}=n,a=t.length-1,c=At(a),l=new Uint32Array(a);let u=0,d=0;for(l[d++]=e,pn(c,e,!0);u<d;){const f=l[u++],h=t[f]+s[f];for(let g=t[f];g<h;g++){const w=r[o[g]];i[o[g]]>0&&!_e(c,w)&&(pn(c,w,!0),l[d++]=w)}}return c}function no(n){let e=n>>>0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}const T3=2147483647;function O3(n,e){for(let t=0;t<n.nodeCount;t++){const r=n.rowPtr[t+1];for(let o=n.rowPtr[t];o<r;o++)if(n.colIdx[o]!==t&&(e===null||e[o]>0))return!0}return!1}function gh(n,e,t){for(let r=0;r<e.length;r++){if(t!==null&&t[r]===1)continue;const o=n.collect(r,e);if(o!==0&&n.voteOf(e[r])!==o)return!1}return!0}function Ic(n,e){if(e===null)return n.weights;const t=new Float64Array(n.arcCount);for(let r=0;r<t.length;r++)t[r]=e[n.arcToEdge[r]];return t}function li(n){const e=n.edges.byRole("weight");return e!==null&&e.dtype==="f64"?e.data:null}function kc(n,e){const t=e?Ic(n,li(n)):null;if(t!==null)for(let o=0;o<t.length;o++){const s=t[o];if(!(s>=0)||s===1/0)throw Q(new RangeError(`arc ${o} has weight ${s}; label propagation needs finite, non-negative weights`),"E_BAD_WEIGHT")}const r=n.directed?n.reverse():null;return{sides:r===null?1:2,rowPtrs:[n.rowPtr,r===null?n.rowPtr:r.rowPtr],colIdxs:[n.colIdx,r===null?n.colIdx:r.colIdx],arcWeights:[t,t===null||r===null?t:Ic(r,li(n))],weights:t}}function Sc(n,e,t){if(!Number.isInteger(e)||e<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${e}`),"E_BAD_OPTION");if(t!==null&&!Number.isInteger(t))throw Q(new RangeError(`randomSeed must be a finite integer, got ${t}`),"E_BAD_OPTION");if(e*n>Number.MAX_SAFE_INTEGER)throw Q(new RangeError(`maxIterations * nodeCount (${e} * ${n}) exceeds Number.MAX_SAFE_INTEGER`),"E_BAD_OPTION")}class Pc{constructor(e,t,r){this.rows=t,this.epoch=-1,this.count=0,this.acc=new Float64Array(e),this.stamp=new Int32Array(e).fill(-1),this.touched=new Uint32Array(e),this.seen=r?null:new Int32Array(e).fill(-1)}collect(e,t){++this.epoch===T3&&(this.stamp.fill(-1),this.seen?.fill(-1),this.epoch=0);const{acc:r,stamp:o,touched:s,seen:i,rows:a}=this,c=this.epoch;let l=0;for(let d=0;d<a.sides;d++){const f=a.rowPtrs[d],h=a.colIdxs[d],g=a.arcWeights[d],w=f[e+1];for(let p=f[e];p<w;p++){const m=h[p];if(m===e)continue;if(i!==null){if(i[m]===c)continue;i[m]=c}const y=t[m];if(y===x)continue;const b=g===null?1:g[p];o[y]!==c?(o[y]=c,r[y]=b,s[l++]=y):r[y]+=b}}this.count=l;let u=0;for(let d=0;d<l;d++)r[s[d]]>u&&(u=r[s[d]]);return u}voteOf(e){return this.stamp[e]===this.epoch?this.acc[e]:0}}function wh(n,e,t,r,o,s,i){const a=n.nodeCount,c=no(i),l=new Pc(a,e,t),u=a+1,d=new Uint32Array(u),f=new Uint8Array(a);let h=0;for(let v=0;v<a;v++)(o===null||o[v]===0)&&(d[h++]=v,f[v]=1);for(let v=h-1;v>=1;v--){const A=Math.floor(c()*(v+1)),E=d[v];d[v]=d[A],d[A]=E}let g=0,w=h;const p=s*a;let m=0;const{touched:y,acc:b}=l;for(;h>0&&m<p;){const v=d[g];g=g+1===u?0:g+1,h--,f[v]=0,m++;const A=l.collect(v,r);if(A===0)continue;let E=0,I=0;for(let k=0;k<l.count;k++){const N=y[k];b[N]===A&&(I++,(I===1||c()*I<1)&&(E=N))}if(E!==r[v]){r[v]=E;for(let k=0;k<e.sides;k++){const N=e.rowPtrs[k],C=e.colIdxs[k],O=N[v+1];for(let T=N[v];T<O;T++){const $=C[T];f[$]===0&&r[$]!==E&&(o===null||o[$]===0)&&(f[$]=1,d[w]=$,w=w+1===u?0:w+1,h++)}}}}return{visits:m,size:h}}function ph(n,e={}){const t=e.maxIterations??100,r=e.randomSeed??42,o=e.weighted??!0,s=n.nodeCount;Sc(s,t,r);const i=kc(n,o),a=new Uint32Array(s);for(let f=0;f<s;f++)a[f]=f;if(s===0||t===0){const{labels:f,count:h}=Je(a);return{...We(f,h),iterations:0,converged:!O3(n,i.weights)}}const{visits:c,size:l}=wh(n,i,o,a,null,t,r),{labels:u,count:d}=Je(a);return{...We(u,d),iterations:Math.ceil(c/s),converged:l===0}}function $3(n,e,t={}){const r=t.maxIterations??100,o=t.randomSeed??42,s=t.weighted??!0,i=n.nodeCount;if(e.length!==i)throw Q(new RangeError(`seeds has ${e.length} entries; the snapshot has ${i} nodes`),"E_BAD_OPTION");Sc(i,r,o);const a=kc(n,s),c=new Uint32Array(i),l=new Uint8Array(i),u=new Map;for(let p=0;p<i;p++){const m=e[p];if(m===x){c[p]=x;continue}let y=u.get(m);y===void 0&&(y=p,u.set(m,p)),c[p]=y,l[p]=1}const{visits:d,size:f}=wh(n,a,s,c,l,r,o),h=f===0||r===0&&gh(new Pc(i,a,s),c,l);R3(a,c);const{labels:g,count:w}=Je(c);return{...We(g,w),iterations:i===0?0:Math.ceil(d/i),converged:h}}function R3(n,e){const t=[];for(let r=0;r<e.length;r++)if(e[r]===x)for(e[r]=r,t.push(r);t.length>0;)D3(n,e,t.pop(),r,t)}function D3(n,e,t,r,o){for(let s=0;s<n.sides;s++){const i=n.rowPtrs[s],a=n.colIdxs[s],c=n.arcWeights[s],l=i[t+1];for(let u=i[t];u<l;u++){const d=a[u];e[d]===x&&(c===null||c[u]>0)&&(e[d]=r,o.push(d))}}}function mh(n,e={}){const t=e.maxIterations??100,r=e.weighted??!0,o=n.nodeCount;Sc(o,t,null);const s=kc(n,r),i=new Pc(o,s,r),{touched:a,acc:c}=i;let l=new Uint32Array(o),u=new Uint32Array(o),d=new Uint32Array(o).fill(x);const f=new Uint32Array(o);for(let b=0;b<o;b++)l[b]=b,f[b]=L3(b);let h=0,g=0,w=!1;for(;g<2&&h<t&&!w;){const b=h%2===0;h++;let v=!1;for(let A=0;A<o;A++){const E=l[A];u[A]=E;const I=i.collect(A,l);if(I===0||i.voteOf(E)===I)continue;let k=x;for(let N=0;N<i.count;N++){const C=a[N];c[C]===I&&(k===x||f[C]<f[k])&&(k=C)}(b?f[k]>f[E]:f[k]<f[E])&&(u[A]=k,v=!0)}w=v&&M3(u,d),[d,l,u]=[l,u,d],g=v?0:g+1}const p=g>=2||gh(i,l,null),{labels:m,count:y}=Je(l);return{...We(m,y),iterations:h,converged:p}}function L3(n){return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function M3(n,e){for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function xc(n,e,t={}){const r=t.resolution??1,o=t.weights??n.weights;if(e.length!==n.nodeCount)throw Q(new RangeError(`labels has ${e.length} entries; the snapshot has ${n.nodeCount} nodes`),"E_BAD_OPTION");if(o!==null&&o.length!==n.arcCount)throw Q(new RangeError(`weights has ${o.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const s=new Map,i=new Map,a=(u,d,f)=>{d!==x&&u.set(d,(u.get(d)??0)+f)};let c=0;for(let u=0;u<n.nodeCount;u++){const d=n.rowPtr[u+1];for(let f=n.rowPtr[u];f<d;f++){const h=n.colIdx[f],g=o===null?1:o[f],w=n.directed||h===u?2*g:g;c+=w,n.directed?(a(s,e[u],g),a(s,e[h],g)):a(s,e[u],w),e[u]===e[h]&&a(i,e[u],w)}}if(c===0)return 0;let l=0;for(const[u,d]of s){const f=d/c;l+=(i.get(u)??0)/c-r*f*f}return l}const U3=1e-10;function F3(n,e){const t=new eo(n.nodeCount),r=n.edgeList();for(let o=0;o<n.edgeCount;o++)_e(e,o)&&t.union(r.src[o],r.dst[o]);return t.toLabels()}function yh(n,e={}){if(n.directed)throw Q(new Error("Girvan-Newman requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.maxCommunities??0,r=e.minCommunitySize??1,o=e.maxIterations??100,{nodeCount:s,edgeCount:i}=n,a=Ic(n,li(n)),c=At(i,!0),l=[],u=[],d=[],f=()=>{const{labels:g,count:w}=F3(n,c);l.push(g),d.push(w),u.push(xc(n,g,a===null?{}:{weights:a}));const p=new Uint32Array(w);for(let m=0;m<s;m++)p[g[m]]++;return p.filter(m=>m>=r).length};f();for(let g=0;g<o&&z2(c,i)>0;g++){const w=dc(n,{alive:c}).scores;let p=-1/0;for(let y=0;y<i;y++)_e(c,y)&&w[y]>p&&(p=w[y]);for(let y=0;y<i;y++)_e(c,y)&&Math.abs(w[y]-p)<U3&&pn(c,y,!1);const m=f();if(t>0&&m>=t||m===s)break}let h=0;for(let g=1;g<u.length;g++)(u[g]>u[h]||Number.isNaN(u[h])&&!Number.isNaN(u[g]))&&(h=g);return{...We(l[h],d[h]),bestLevel:h,levels:l,modularity:Float64Array.from(u)}}function B3(n,e={}){const{maxDepth:t=10,minClusterSize:r=2,tolerance:o=1e-6,maxIterations:s=100,seed:i=42,weighted:a=!0}=e,c=n.nodeCount;if(c===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const l=no(i),u=a?n.weights:null;if(u!==null)for(let M=0;M<u.length;M++){const R=u[M];if(!(R>=0)||R===1/0)throw Q(new RangeError(`arc ${String(M)} has weight ${String(R)}; grsbm needs finite, non-negative weights`),"E_BAD_WEIGHT")}const d=a?n.weightedDegree():n.degree(),f=a?n.totalWeight():n.edgeCount,h=n.directed?1:2,g=!n.directed||!a,{rowPtr:w,colIdx:p}=n,m=new Int32Array(c).fill(-1),y=M=>{let R=0,D=0;for(let U=0;U<M.length;U++){const B=M[U];D+=d[B];for(let V=w[B];V<w[B+1];V++){const W=p[V];if(m[W]===m[B]){const q=u===null?1:u[V];R+=W===B?h*q:q}}}return g&&(R/=2),(R-D*D/(4*f))/f},b=M=>{if(f===0)return 0;let R=0;M.forEach((D,U)=>{for(let B=0;B<D.length;B++)m[D[B]]=U});for(const D of M)D.length>0&&(R+=y(D));for(const D of M)for(let U=0;U<D.length;U++)m[D[U]]=-1;return R},v=new Uint32Array(c);for(let M=0;M<c;M++)v[M]=M;const A=b([v]),E=[{serial:0,members:v,depth:0,modularity:A,spectralScore:0,left:x,right:x,split:null}],I=[A];let k=A;const N=new Int32Array(c).fill(-1);let C=1;for(let M=0;M<E.length;M++){const R=E[M],{members:D}=R,U=D.length;if(R.depth>=t||U<r*2||U<4)continue;const B=z3(D,N,n,u,l,o,s),V=Array.from({length:U},(ue,we)=>we).sort((ue,we)=>B[ue]-B[we]),W=Uint32Array.from(V,ue=>D[ue]);let q=Math.floor(U/2),K=-1/0;for(let ue=Math.floor(U*.2);ue<=Math.floor(U*.8);ue++){const we=b([W.subarray(0,ue),W.subarray(ue)]);we>K&&(K=we,q=ue)}const X=W.slice(0,q),H=W.slice(q),Y=Array.from(B).sort((ue,we)=>Math.abs(we)-Math.abs(ue)),ee=Math.abs(Y[Math.floor(U*.1)]),Z=[];for(let ue=0;ue<U&&Z.length<5;ue++)Math.abs(B[ue])>=ee&&Z.push(D[ue]);const J=Math.abs(Y[0]-Y[U-1]),ce=C++,de=C++,ne=K-b([D]);if(ne<=0)continue;k+=ne;const ve=(ue,we)=>({serial:ue,members:we,depth:R.depth+1,modularity:k,spectralScore:J,left:x,right:x,split:null});R.left=E.length,R.right=E.length+1,R.split={improvement:ne,bisectionModularity:k,keyNodes:Uint32Array.from(Z),spectralValues:B},E.push(ve(ce,X),ve(de,H)),I.push(k)}const O=new Uint32Array(c);let T=0;const $=[0];for(;$.length>0;){const M=E[$.pop()??0];if(M.left===x){for(const R of M.members)O[R]=T;T++}else $.push(M.right,M.left)}const{labels:L,count:F}=Je(O);return{...We(L,F),clusters:E,modularityScores:Float64Array.from(I)}}function z3(n,e,t,r,o,s,i){const a=n.length;for(let y=0;y<a;y++)e[n[y]]=y;const c=new Uint32Array(a+1),l=[],u=[],d=new Map;let f=0;for(let y=0;y<a;y++){const b=n[y];d.clear();let v=0;for(let A=t.rowPtr[b];A<t.rowPtr[b+1];A++){const E=e[t.colIdx[A]];if(E>=0&&E!==y){const I=r===null?1:r[A];d.set(E,(d.get(E)??0)-I),v+=I}}d.set(y,v),f=Math.max(f,v);for(const A of[...d.keys()].sort((E,I)=>E-I))l.push(A),u.push(d.get(A)??0);c[y+1]=l.length}for(let y=0;y<a;y++)e[n[y]]=-1;let h=new Float64Array(a);for(let y=0;y<a;y++)h[y]=o()-.5;const g=y=>{let b=0;for(const A of y)b+=A;const v=b/a;for(let A=0;A<a;A++)y[A]-=v},w=y=>{let b=0;for(const v of y)b+=v*v;return Math.sqrt(b)};g(h);const p=w(h);if(p>0)for(let y=0;y<a;y++)h[y]/=p;const m=2*f;for(let y=0;y<i;y++){const b=new Float64Array(a);for(let E=0;E<a;E++){let I=0;for(let k=c[E];k<c[E+1];k++)I+=u[k]*h[l[k]];b[E]=m*h[E]-I}g(b);const v=w(b);if(v<s)break;let A=0;for(let E=0;E<a;E++)b[E]/=v,A+=Math.abs(b[E]-h[E]);if(h=b,A<s)break}return h}function G3(n,e){const t=n.nodeCount;e.fill(x);const r=new Uint32Array(t);for(let o=0;o<t;o++){const s=o*t;e[s+o]=0,r[0]=o;let i=0,a=1;for(;i<a;){const c=r[i++],l=e[s+c]+1,u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++){const f=n.colIdx[d];e[s+f]===x&&(e[s+f]=l,r[a++]=f)}}}}function W3(n){const e=Math.max(0,2*n-1),t=Array.from({length:e},(s,i)=>i<n?`leaf-${i}`:`cluster-${i}`),r=Array.from({length:e},(s,i)=>i).sort((s,i)=>+(t[s]>t[i])-+(t[s]<t[i])),o=new Uint32Array(e);return r.forEach((s,i)=>o[s]=i),o}function V3(n,e={}){const t=e.linkage??"single";if(!["single","complete","average","ward"].includes(t))throw Q(new RangeError(`unknown linkage "${t}"`),"E_BAD_OPTION");const r=n.nodeCount,{hops:o,min:s,max:i,sum:a,count:c}=Lf("hierarchicalClustering",r,e.maxNodes,28*r*r,()=>({hops:new Uint32Array(r*r),min:new Uint32Array(r*r),max:new Uint32Array(r*r),sum:new Float64Array(r*r),count:new Float64Array(r*r)}));G3(n,o);for(let T=0;T<r*r;T++){const $=o[T];$!==x&&(s[T]=$,i[T]=$,a[T]=$,c[T]=1)}const l=Math.max(0,2*r-1),u=W3(r),d=new Uint32Array(l),f=new Float64Array(l),h=new Uint32Array(l);for(let T=0;T<r;T++)d[T]=T,f[T]=1;const g=[],w=[],p=[],m=(T,$)=>{const L=d[T]*r+d[$],F=c[L];if(F===0)return 1/0;switch(t){case"single":return s[L];case"complete":return i[L];case"average":return a[L]/F;default:return a[L]/F*(f[T]*f[$]/(f[T]+f[$]))}},y=(T,$)=>{const[L,F]=T<$?[T,$]:[$,T];return F<r?m(L,F):m(F,L)};let b=Array.from({length:r},(T,$)=>$);for(;b.length>1;){let T=1/0,$=-1,L=-1;for(const D of b)for(const U of b){if(u[D]>=u[U])continue;const B=y(D,U);B<T&&(T=B,$=D,L=U)}if($<0)break;const F=r+g.length;g.push($),w.push(L),p.push(T),h[F]=Math.max(h[$],h[L])+1,f[F]=f[$]+f[L];const M=d[$],R=d[L];for(const D of b){if(D===$||D===L)continue;const U=d[D];for(const[B,V,W]of[[M*r+U,M*r+U,R*r+U],[U*r+M,U*r+M,U*r+R]]){const q=c[V],K=c[W];if(q===0||K===0){const X=q===0?W:V;s[B]=s[X],i[B]=i[X]}else s[B]=Math.min(s[V],s[W]),i[B]=Math.max(i[V],i[W]);a[B]=a[V]+a[W],c[B]=q+K}}d[F]=M,b=b.filter(D=>D!==$&&D!==L),b.push(F)}const v=g.length,A=Uint32Array.from(g),E=Uint32Array.from(w),I=T=>{if(!(T>=0&&T<r+v))throw Q(new RangeError(`cluster ${T} is not in [0, ${r+v})`),"E_BAD_OPTION");const $=[],L=[T];for(;L.length>0;){const F=L.pop();F<r?$.push(F):L.push(E[F-r],A[F-r])}return Uint32Array.from($)},k=Uint32Array.from(b),N=Float64Array.from(p),C=new Uint32Array(v);for(let T=0;T<v;T++)C[T]=A[T]<r?A[T]:C[A[T]-r];const O=T=>T<r?T:C[T-r];return{nodeCount:r,left:A,right:E,distance:N,height:h.slice(0,r+v),roots:k,members:I,cut(T){const $=[],L=F=>{F<r||h[F]<=T?$.push(I(F)):(L(A[F-r]),L(E[F-r]))};return k.forEach(L),$},cutAt(T){let $=0;if("clusters"in T){const R=T.clusters;if(!Number.isInteger(R)||R<k.length||R>r)throw Q(new RangeError(`clusters must be an integer in [${k.length}, ${r}], got ${R}`),"E_BAD_OPTION");$=r-R}else{if(Number.isNaN(T.distance))throw Q(new RangeError("distance must not be NaN"),"E_BAD_OPTION");for(;$<v&&N[$]<=T.distance;)$++}const L=new eo(r);for(let R=0;R<$;R++)L.union(O(A[R]),O(E[R]));const{labels:F,count:M}=L.toLabels();return We(F,M)}}}function bh(n){let e=0;for(let r=0;r<n.length;r++)e+=n[r]*n[r];const t=Math.sqrt(e);if(t>0)for(let r=0;r<n.length;r++)n[r]/=t}function vh(n){let e=0;for(let t=0;t<n.length;t++)n[t]>e&&(e=n[t]);if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function Ah(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.reverse(),i=e.weighted===!0?n.weights:null,a=e.weighted===!0?s.weights:null;let c=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),l=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),u=new Float64Array(t),d=new Float64Array(t),f=0,h=!1;for(;f<r&&!h;f++){for(let w=0;w<t;w++){let p=0;const m=s.rowPtr[w+1];for(let v=s.rowPtr[w];v<m;v++)p+=c[s.colIdx[v]]*(a===null?1:a[v]);d[w]=p;let y=0;const b=n.rowPtr[w+1];for(let v=n.rowPtr[w];v<b;v++)y+=l[n.colIdx[v]]*(i===null?1:i[v]);u[w]=y}bh(d),bh(u);let g=0;for(let w=0;w<t;w++){const p=Math.abs(u[w]-c[w]);p>g&&(g=p);const m=Math.abs(d[w]-l[w]);m>g&&(g=m)}[c,u]=[u,c],[l,d]=[d,l],h=g<o}return e.normalized===!1&&(vh(c),vh(l)),{hubs:c,authorities:l,iterations:f,converged:h}}function Eh(n,e){let t=0,r=!1,o=x;for(let s=n.rowPtr[e];s<n.rowPtr[e+1];s++){const i=n.colIdx[s];i!==o&&(o=i,i===e?r=!0:t++)}return{degree:t,loop:r}}function _h(n){const e=new Float64Array(n.nodeCount),t=n.directed?n.reverse():null;for(let r=0;r<n.nodeCount;r++){const o=Eh(n,r),s=t===null?0:Eh(t,r).degree;e[r]=(o.degree*67108864+s)*2+(o.loop?1:0)}return e}function j3(n,e){const t=new Uint32Array(e),r=new Uint32Array(e).fill(x),o=new Uint8Array(e),s=new Uint8Array(e);let i=0;for(let a=0;a<e;a++){if(s[a]===1)continue;s[a]=1;let c=i;for(t[i++]=a;c<i;)i=q3(n,t[c++],{order:t,parent:r,parentView:o},s,i)}return{order:t,parent:r,parentView:o}}function q3(n,e,t,r,o){const{order:s,parent:i,parentView:a}=t;for(let c=0;c<n.length;c++){const{rowPtr:l,colIdx:u}=n[c];for(let d=l[e];d<l[e+1];d++){const f=u[d];r[f]===0&&(r[f]=1,i[f]=e,a[f]=c,s[o++]=f)}}return o}function Ih(n,e,t,r){const o=n.nodeCount;if(n.directed!==e.directed||o!==e.nodeCount)return;const s=_h(n),i=_h(e),a=s.slice().sort(),c=i.slice().sort();if(a.some((O,T)=>O!==c[T]))return;const l=n.directed?[n,n.reverse()]:[n],u=e.directed?[e,e.reverse()]:[e],{order:d,parent:f,parentView:h}=j3(l,o),g=new Uint32Array(o).fill(x),w=new Uint32Array(o).fill(x),p=u.map(()=>new Uint32Array(o)),m=u.map(()=>new Uint32Array(o));let y=0;const{nodeMatch:b,edgeMatch:v}=t,A=(O,T)=>{if(s[O]!==i[T]||b!==void 0&&!b(O,T,n,e))return!1;if(v!==void 0&&s[O]%2===1){const $=n.arcToEdge[n.findArc(O,O)],L=e.arcToEdge[e.findArc(T,T)];if(!v($,L,n,e))return!1}y++;for(let $=0;$<l.length;$++){const L=l[$],F=u[$];let M=0,R=x;for(let U=F.rowPtr[T];U<F.rowPtr[T+1];U++){const B=F.colIdx[U];B===R||B===T||(R=B,p[$][B]=y,m[$][B]=U,w[B]!==x&&M++)}let D=0;R=x;for(let U=L.rowPtr[O];U<L.rowPtr[O+1];U++){const B=L.colIdx[U];if(B===R||B===O)continue;R=B;const V=g[B];if(V!==x&&(p[$][V]!==y||(D++,v!==void 0&&!v(L.arcToEdge[U],F.arcToEdge[m[$][V]],n,e))))return!1}if(D!==M)return!1}return!0},E=new Uint32Array(o+1);let I=0,k=!1;const N=O=>{const T=f[d[O]];if(T===x)return{view:null,from:0,to:o};const $=u[h[d[O]]],L=g[T];return{view:$,from:$.rowPtr[L],to:$.rowPtr[L+1]}};if(o===0){r(g);return}let C=N(0);for(E[0]=C.from;!k;){const O=d[I];let T=!1;for(;E[I]<C.to;){const L=E[I]++,F=C.view===null?L:C.view.colIdx[L];if(!(C.view!==null&&L>C.from&&C.view.colIdx[L-1]===F)&&!(w[F]!==x||!A(O,F))){if(g[O]=F,w[F]=O,I===o-1){if(k=r(g),g[O]=x,w[F]=x,k)break;continue}I++,C=N(I),E[I]=C.from,T=!0;break}}if(k||T)continue;if(I===0)return;I--;const $=d[I];w[g[$]]=x,g[$]=x,C=N(I)}}function H3(n,e,t={}){let r=null;return Ih(n,e,t,o=>(r=o.slice(),!0)),{isomorphic:r!==null,mapping:r}}function K3(n,e,t={}){const r=[];return Ih(n,e,t,o=>(r.push(o.slice()),!1)),r}function kh(n){if(n.directed)throw Q(new Error("k-core requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const e=n.nodeCount,{rowPtr:t,colIdx:r}=n,o=new Uint32Array(e);let s=0;for(let f=0;f<e;f++){let h=0,g=-1;const w=t[f+1];for(let p=t[f];p<w;p++){const m=r[p];m!==f&&m!==g&&h++,g=m}o[f]=h,h>s&&(s=h)}const i=new Uint32Array(s+1);for(let f=0;f<e;f++)i[o[f]]++;let a=0;for(let f=0;f<=s;f++){const h=i[f];i[f]=a,a+=h}const c=new Uint32Array(e),l=new Uint32Array(e);for(let f=0;f<e;f++)l[f]=i[o[f]],c[l[f]]=f,i[o[f]]++;for(let f=s;f>0;f--)i[f]=i[f-1];i[0]=0;let u=0;for(let f=0;f<e;f++){const h=c[f],g=o[h];g>u&&(u=g);const w=t[h+1];let p=-1;for(let m=t[h];m<w;m++){const y=r[m],b=y===h||y===p;if(p=y,b)continue;const v=o[y];if(v>g){const A=l[y],E=i[v],I=c[E];y!==I&&(c[A]=I,c[E]=y,l[y]=E,l[I]=A),i[v]++,o[y]=v-1}}}let d=null;return{coreness:o,maxCore:u,cores(){if(d===null){const f=new Uint32Array(u+1);for(let w=0;w<e;w++)f[o[w]]++;const h=[];for(let w=0;w<=u;w++)h.push(new Uint32Array(f[w]));const g=new Uint32Array(u+1);for(let w=0;w<e;w++){const p=o[w];h[p][g[p]++]=w}d=h}return d}}}function Sh(n,e={}){const t=n.nodeCount,r=e.alpha??.1,o=e.beta??1,s=e.maxIterations??100,i=e.tolerance??1e-6,a=n.reverse(),c=e.weighted===!0?a.weights:null;let l=new Float64Array(t).fill(o),u=new Float64Array(t),d=0,f=!1;for(;d<s&&!f;d++){let h=0;for(let g=0;g<t;g++){let w=0;const p=a.rowPtr[g+1];for(let y=a.rowPtr[g];y<p;y++)w+=l[a.colIdx[y]]*(c===null?1:c[y]);u[g]=r*w+o;const m=Math.abs(u[g]-l[g]);m>h&&(h=m)}[l,u]=[u,l],f=h<i}if(e.normalized!==!1){let h=1/0,g=-1/0;for(let p=0;p<t;p++)l[p]<h&&(h=l[p]),l[p]>g&&(g=l[p]);const w=g-h;if(w>0)for(let p=0;p<t;p++)l[p]=(l[p]-h)/w}return{scores:l,iterations:d,converged:f}}const Y3=.01,X3=3;function Ph(n,e){const{nodeCount:t,rowPtr:r,colIdx:o,arcToEdge:s}=n,i=new Float64Array(n.arcCount),a=new Float64Array(t);for(let c=0;c<t;c++)for(let l=r[c],u=r[c+1];l<u;l++){const d=e[s[l]];i[l]=d,a[c]+=o[l]===c?2*d:d}return{s:n,edgeW:e,arcW:i,deg:a}}function xh(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=r;for(let r=n-1;r>=1;r--){const o=Math.floor(e()*(r+1)),s=t[r];t[r]=t[o],t[o]=s}return t}function Q3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c),f=new Uint32Array(c);for(let I=0;I<c;I++)d[e[I]]+=a[I],f[e[I]]++;const h=[];for(let I=c-1;I>=0;I--)f[I]===0&&h.push(I);const g=new Float64Array(c),w=new Int32Array(c).fill(-1),p=new Uint32Array(c),m=c+1,y=new Uint32Array(m);y.set(xh(c,t));const b=new Uint8Array(c).fill(1);let v=0,A=c,E=0;for(;v!==A;){const I=y[v];v=v+1===m?0:v+1,b[I]=0,E++;const k=e[I],N=a[I];d[k]-=N,f[k]--;let C=0;for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];if(F===I)continue;const M=e[F];w[M]!==E&&(w[M]=E,g[M]=0,p[C++]=M),g[M]+=i[$]}let O=k,T=(w[k]===E?g[k]:0)-r*N*d[k]/o;for(let $=0;$<C;$++){const L=p[$],F=g[L]-r*N*d[L]/o;L!==k&&F>T&&(T=F,O=L)}if(f[k]>0&&T<0&&(O=h[h.length-1]),O!==k&&f[O]===0&&h.pop(),d[O]+=N,f[O]++,O!==k){e[I]=O,f[k]===0&&h.push(k);for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];b[F]===0&&e[F]!==O&&(b[F]=1,y[A]=F,A=A+1===m?0:A+1)}}}}function J3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c);for(let v=0;v<c;v++)d[e[v]]+=a[v];const f=new Uint32Array(c),h=new Float64Array(c),g=new Uint32Array(c),w=new Float64Array(c);for(let v=0;v<c;v++){f[v]=v,h[v]=a[v],g[v]=1;for(let A=l[v],E=l[v+1];A<E;A++){const I=u[A];I!==v&&e[I]===e[v]&&(w[v]+=i[A])}}const p=new Float64Array(c),m=new Int32Array(c).fill(-1),y=new Uint32Array(c),b=xh(c,t);for(let v=0;v<c;v++){const A=b[v],E=e[A],I=a[A];if(g[A]!==1||w[A]<r*I*(d[E]-I)/o)continue;let k=0;for(let M=l[A],R=l[A+1];M<R;M++){const D=u[M];if(D===A||e[D]!==E)continue;const U=f[D];m[U]!==A&&(m[U]=A,p[U]=0,y[k++]=U),p[U]+=i[M]}const N=M=>p[M]-r*I*h[M]/o;let C=-1/0,O=0;for(let M=0;M<k;M++){const R=y[M],D=N(R);D>=0&&w[R]>=r*h[R]*(d[E]-h[R])/o&&(y[O++]=R,C=Math.max(C,D))}if(O===0)continue;const T=M=>Qr((N(M)-C)*2/o/Y3);let $=0;for(let M=0;M<O;M++)$+=T(y[M]);let L=t()*$,F=y[O-1];for(let M=0;M<O-1;M++)if(L-=T(y[M]),L<0){F=y[M];break}f[A]=F,g[A]=0,g[F]++,h[F]+=I,w[F]+=w[A]-2*p[F]}return f}function Z3(n,e,t,r,o){const s=n.s.nodeCount,i=new Uint32Array(s);for(let d=0;d<s;d++)i[d]=d;let a=n,c=e.slice(),l=0;for(;;){Q3(a,c,t,r,o),l++;const d=Je(c);if(d.count===a.s.nodeCount)break;let f=J3(a,d.labels,t,r,o);Je(f).count===a.s.nodeCount&&(f=d.labels);const h=a.s.contract(f),{nodeRemap:g,edgeRemap:w}=h,p=h.snapshot,m=new Float64Array(p.edgeCount);for(let b=0;b<a.edgeW.length;b++)m[w===null?b:w[b]]+=a.edgeW[b];const y=new Uint32Array(p.nodeCount);for(let b=0;b<a.s.nodeCount;b++)y[g===null?b:g[b]]=d.labels[b];if(g!==null)for(let b=0;b<s;b++)i[b]=g[i[b]];c=Je(y).labels,a=Ph(p,m)}const u=new Uint32Array(s);for(let d=0;d<s;d++)u[d]=c[i[d]];return{comm:u,levels:l}}function eE(n){const e=li(n)??n.edgeList().weights,t=e===null?new Float64Array(n.edgeCount).fill(1):Float64Array.from(e);for(let r=0;r<t.length;r++){const o=t[r];if(!(o>=0)||o===1/0)throw Q(new RangeError(`edge ${r} has weight ${o}; Leiden needs finite, non-negative weights`),"E_BAD_WEIGHT")}return t}function Ch(n,e={}){if(n.directed)throw Q(new Error("Leiden requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.randomSeed??42,o=e.maxIterations??100,s=e.threshold??1e-7;if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const i=n.nodeCount,a=Ph(n,eE(n));let c=0;for(let w=0;w<i;w++)c+=a.deg[w];let l=new Uint32Array(i);for(let w=0;w<i;w++)l[w]=w;if(c===0)return{...We(l,i),modularity:0,iterations:0};const u=w=>xc(n,w,{resolution:t,weights:a.arcW}),d=no(r);let f=u(l),h=0,g=0;for(let w=0;w<o&&g<X3;w++){const{comm:p,levels:m}=Z3(a,l,d,t,c);h+=m;const y=Je(p).labels,b=u(y);b>f?(g=b-f<=s?g+1:0,l=y,f=b):g++}return{...We(l,Je(l).count),modularity:f,iterations:h}}const Nh=2**36;function tE(n){return n>1?Math.round(Nh/Ge(n))/Nh:n===1?1:0}function Th(n,e){const t=n.rowPtr[e],r=n.rowPtr[e+1];let o=0;for(let s=t;s<r;s++)(s===t||n.colIdx[s]!==n.colIdx[s-1])&&o++;return o}function Oh(n,e){const t=n.directed&&!e?n.reverse():void 0;return r=>tE(Th(n,r)+(t===void 0?0:Th(t,r)))}function ro(n,e,t){const r=e.directed===!0?n.reverse():n,o=n.nodeCount;return(s,i)=>s<o&&i<o?Zf(n,r,s,i,t):0}function ui(n,e){const t=Oh(n,e.directed===!0),r=Float64Array.from({length:n.nodeCount},(o,s)=>t(s));return ro(n,e,o=>r[o])}function $h(n,e,t,r){const o=Array.from(t,(s,i)=>i).sort((s,i)=>t[i]-t[s]).slice(0,r);return{sources:Uint32Array.from(o,s=>n[s]),targets:Uint32Array.from(o,s=>e[s]),scores:Float64Array.from(o,s=>t[s])}}function nE(n,e,t,r,o,s,i){n.push(r),e.push(o),t.push(s),i&&(n.push(o),e.push(r),t.push(s))}function Rh(n,e,t){const r=[],o=[],s=[],i=e.directed!==!0&&e.uniquePairs!==!0;for(let c=0;c<n.nodeCount;c++)for(let l=c+1;l<n.nodeCount;l++){if(e.includeExisting!==!0&&n.hasArc(c,l))continue;const u=t(c,l);u>0&&nE(r,o,s,c,l,u,i)}const{topK:a}=e;return $h(r,o,s,a!==void 0&&a>0?a:s.length)}function oo(n,e){return Float64Array.from(n.sources,(t,r)=>e(t,n.targets[r]))}function Dh(n,e,t,r){const o=n.nodeCount,s=[],i=[],a=[];if(e<o){const c=t.candidates===void 0?Array.from({length:o},(l,u)=>u):ss(n,t.candidates);for(let l=0;l<c.length;l++){const u=c[l];if(u===e||t.includeExisting!==!0&&u<o&&n.hasArc(e,u))continue;const d=r(e,u);d>0&&(s.push(e),i.push(u),a.push(d))}}return $h(s,i,a,t.topK??10)}function Lh(n,e){const t=[...n,...e],r=Array.from(t,(u,d)=>d).sort((u,d)=>t[d]-t[u]);let o=0,s=0,i=0,a=0,c=0,l=0;for(const u of r){u<n.length?o++:(l+=o,s++);const d=o/(o+s),f=o/n.length,h=d+f>0?2*(d*f)/(d+f):0;h>i&&(i=h,a=d,c=f)}return l=o>0&&s>0?l/(o*s):.5,{precision:a,recall:c,f1Score:i,auc:l}}function Mh(n,e={}){return Rh(n,e,ro(n,e))}function rE(n,e,t={}){return oo(e,ro(n,t))}function oE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ro(n,t))}function Uh(n,e,t,r={}){const o=ro(n,r);return Lh(oo(e,o),oo(t,o))}function sE(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);return ro(n,r,Oh(n,r.directed===!0))(o,s)}function Fh(n,e={}){return Rh(n,e,ui(n,e))}function iE(n,e,t={}){return oo(e,ui(n,t))}function aE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ui(n,t))}function Bh(n,e,t,r={}){const o=ui(n,r);return Lh(oo(e,o),oo(t,o))}function cE(n){const e=n.nodeCount,t=new Uint32Array(e+1);for(let r=0;r<e;r++){let o=0;const s=n.rowPtr[r+1];for(let i=n.rowPtr[r];i<s;i++)n.colIdx[i]!==r&&o++;t[r+1]=t[r]+o}return t}function lE(n){const e=n.nodeCount,t=cE(n),r=t[e],o=new Uint32Array(r),s=new Float64Array(r),i=new Float64Array(e),a=new Float64Array(e);let c=0;for(let l=0;l<e;l++){let u=0;const d=n.rowPtr[l+1];for(let f=n.rowPtr[l];f<d;f++){const h=n.colIdx[f],g=n.weights===null?1:n.weights[f];h===l?i[l]+=g:(o[c]=h,s[c]=g,c++,u+=g)}a[l]=u+2*i[l]}return{n:e,rowPtr:t,colIdx:o,w:s,loop:i,deg:a}}function zh(n,e,t,r,o){const s=new Float64Array(t),i=new Float64Array(t);for(let c=0;c<n.n;c++){const l=e[c];i[l]+=n.deg[c],s[l]+=2*n.loop[c];const u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++)e[n.colIdx[d]]===l&&(s[l]+=n.w[d])}let a=0;for(let c=0;c<t;c++){const l=i[c]/o;a+=s[c]/o-r*l*l}return a}function uE(n,e,t,r,o){const{n:s}=n,i=new Float64Array(s);for(let b=0;b<s;b++)e[b]=b,i[b]=n.deg[b];const a=new Float64Array(s),c=new Int32Array(s).fill(-1),l=new Uint32Array(s),u=s+1,d=new Uint32Array(u),f=new Uint8Array(s);let h=0,g=s;for(let b=0;b<s;b++)d[b]=b,f[b]=1;let w=0,p=0;const m=o*s;let y=!1;for(;h!==g&&p<m;){const b=d[h];h=h+1===u?0:h+1,f[b]=0,p++;const v=e[b],A=n.deg[b];i[v]-=A,w++;let E=0;const I=n.rowPtr[b+1];for(let C=n.rowPtr[b];C<I;C++){const O=e[n.colIdx[C]];c[O]!==w&&(c[O]=w,a[O]=0,l[E++]=O),a[O]+=n.w[C]}let k=v,N=(c[v]===w?a[v]:0)-t*A*i[v]/r;for(let C=0;C<E;C++){const O=l[C];if(O===v)continue;const T=a[O]-t*A*i[O]/r;T>N&&(N=T,k=O)}if(i[k]+=A,k!==v){e[b]=k,y=!0;for(let C=n.rowPtr[b];C<I;C++){const O=n.colIdx[C];f[O]===0&&e[O]!==k&&(f[O]=1,d[g]=O,g=g+1===u?0:g+1)}}}return y}function dE(n,e,t){const r=new Uint32Array(t+1);for(let i=0;i<n;i++)r[e[i]+1]++;for(let i=0;i<t;i++)r[i+1]+=r[i];const o=new Uint32Array(n),s=r.slice(0,t);for(let i=0;i<n;i++)o[s[e[i]]++]=i;return{start:r,members:o}}function fE(n,e,t,r,o,s){let i=0;for(let a=0;a<e;a++){const c=n[a];r[s+a]=c,o[s+a]=t[c],i+=t[c]}return i}function hE(n,e,t){const{start:r,members:o}=dE(n.n,e,t),s=new Uint32Array(t+1),i=new Uint32Array(n.colIdx.length),a=new Float64Array(n.colIdx.length),c=new Float64Array(t),l=new Float64Array(t),u=new Float64Array(t),d=new Int32Array(t).fill(-1),f=new Uint32Array(t);let h=0;for(let g=0;g<t;g++){s[g]=h;let w=0,p=0;for(let y=r[g];y<r[g+1];y++){const b=o[y];c[g]+=n.loop[b];const v=n.rowPtr[b+1];for(let A=n.rowPtr[b];A<v;A++){const E=e[n.colIdx[A]];if(E===g){w+=n.w[A];continue}d[E]!==g&&(d[E]=g,u[E]=0,f[p++]=E),u[E]+=n.w[A]}}c[g]+=w/2;const m=fE(f,p,u,i,a,h);h+=p,l[g]=m+2*c[g]}return s[t]=h,{n:t,rowPtr:s,colIdx:i.subarray(0,h),w:a.subarray(0,h),loop:c,deg:l}}function Gh(n,e={}){if(n.directed)throw Q(new Error("Louvain requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.nodeCount,i=new Uint32Array(s);for(let f=0;f<s;f++)i[f]=f;let a=lE(n),c=0;for(let f=0;f<s;f++)c+=a.deg[f];if(c===0)return{...We(i,s),modularity:0,iterations:0};let l=zh(a,i,s,t,c),u=0;for(let f=0;f<r;f++){const h=new Uint32Array(a.n);if(!uE(a,h,t,c,r))break;const g=Je(h),{count:w}=g,p=g.labels,m=zh(a,p,w,t,c);for(let b=0;b<s;b++)i[b]=p[i[b]];u=f+1;const y=m-l;if(l=m,y<o||w===a.n)break;a=hE(a,p,w)}const d=Je(i);return{...We(d.labels,d.count),modularity:l,iterations:u}}function Cc(n){for(let e=0;e+1<n.ptr.length;e++){let t=0;for(let r=n.ptr[e];r<n.ptr[e+1];r++)t+=n.val[r];if(t>0)for(let r=n.ptr[e];r<n.ptr[e+1];r++)n.val[r]/=t}}function gE(n,e,t,r){const o=t.length,s=new Uint32Array(o+1),i=[],a=[],c=[];for(let l=0;l<o;l++){c.length=0;for(let u=e.ptr[l];u<e.ptr[l+1];u++){const d=e.row[u],f=e.val[u];for(let h=n.ptr[d];h<n.ptr[d+1];h++){const g=n.row[h];r[g]===0&&(r[g]=1,c.push(g)),t[g]+=n.val[h]*f}}c.sort((u,d)=>u-d);for(const u of c)i.push(u),a.push(t[u]),t[u]=0,r[u]=0;s[l+1]=i.length}return{ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)}}function wE(n,e,t){const r={ptr:n.ptr,row:n.row,val:n.val.map(l=>JA(l,e))};Cc(r);const o=n.ptr.length-1,s=new Uint32Array(o+1),i=[],a=[];for(let l=0;l<o;l++){for(let u=r.ptr[l];u<r.ptr[l+1];u++)r.val[u]>=t&&(i.push(r.row[u]),a.push(r.val[u]));s[l+1]=i.length}const c={ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)};return Cc(c),c}function pE(n,e,t){for(let r=0;r+1<n.ptr.length;r++){let o=n.ptr[r],s=e.ptr[r];const i=n.ptr[r+1],a=e.ptr[r+1];for(;o<i||s<a;){let c;if(s>=a||o<i&&n.row[o]<e.row[s]?c=n.val[o++]:o>=i||e.row[s]<n.row[o]?c=e.val[s++]:c=n.val[o++]-e.val[s++],Math.abs(c)>t)return!1}}return!0}function mE(n,e){const t=n===null?1:n[e];if(!(t>=0)||t===1/0)throw Q(new RangeError(`arc ${e} has weight ${t}; Markov clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");return t}function yE(n,e,t){const r=n.nodeCount,o=new Uint32Array(r+1);for(let h=0;h<n.arcCount;h++)o[n.colIdx[h]+1]++;if(t)for(let h=0;h<r;h++)o[h+1]++;for(let h=0;h<r;h++)o[h+1]+=o[h];const s=o.slice(0,r),i=new Uint32Array(o[r]),a=new Float64Array(o[r]),c=(h,g,w,p)=>{const m=s[g]-1;m>=o[g]&&i[m]===h?a[m]=p?w:a[m]+w:(i[s[g]]=h,a[s[g]++]=w)};for(let h=0;h<r;h++){for(let g=n.rowPtr[h];g<n.rowPtr[h+1];g++){const w=n.colIdx[g];c(h,w,mE(e,g),!1)}t&&c(h,h,1,!0)}const l=new Uint32Array(r+1),u=[],d=[];for(let h=0;h<r;h++){for(let g=o[h];g<s[h];g++)u.push(i[g]),d.push(a[g]);l[h+1]=u.length}const f={ptr:l,row:Uint32Array.from(u),val:Float64Array.from(d)};return Cc(f),f}function bE(n,e={}){const t=e.expansion??2,r=e.inflation??2,o=e.maxIterations??100,s=e.tolerance??1e-6,i=e.pruningThreshold??1e-5;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`expansion must be an integer of at least 1, got ${t}`),"E_BAD_OPTION");if(!(r>0)||r===1/0)throw Q(new RangeError(`inflation must be finite and above 0, got ${r}`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${o}`),"E_BAD_OPTION");if(!(s>=0)||!(i>=0))throw Q(new RangeError("tolerance and pruningThreshold must be non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;let l=yE(n,a,e.selfLoops??!0);const u=new Float64Array(c),d=new Uint8Array(c);let f=c===0,h=0;for(;!f&&h<o;){let b=l;for(let A=1;A<t;A++)b=gE(b,l,u,d);const v=wE(b,r,i);h++,f=pE(l,v,s),l=v}const g=[],w=new Int32Array(c).fill(-1);for(let b=0;b<c;b++){let v=0;for(let A=l.ptr[b];A<l.ptr[b+1];A++)l.row[A]===b&&l.val[A]>0&&g.push(b),l.val[A]>v&&(v=l.val[A],w[b]=l.row[A])}const p=new Uint32Array(c),m=new Map;for(let b=0;b<c;b++){const v=w[b];if(v>=0){let A=m.get(v);A===void 0&&(A=m.size,m.set(v,A)),p[b]=A}}let y=m.size;for(let b=0;b<c;b++)w[b]<0&&(p[b]=y++);return{...We(p,y),attractors:Uint32Array.from(g),iterations:h,converged:f}}function Wh(n,e){return e instanceof Uint32Array?e:Df(n,e)}function Vh(n,e){const t=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n];if(e.left!==void 0&&e.right!==void 0)return{left:Wh(n,e.left),right:Wh(n,e.right),views:t};const{sides:r}=Yf(n,{arcs:e.arcs});if(r===null)throw Q(new Error("Graph is not bipartite"),"E_NOT_BIPARTITE");const o=At(n.nodeCount);for(let i=0;i<o.length;i++)o[i]=~r[i];const s=n.nodeCount%32;return s!==0&&(o[o.length-1]&=(1<<s)-1),{left:o,right:r,views:t}}function vE(n,e,t){const r=new Uint32Array(e+1),o=new Uint32Array(t+1);for(const{rowPtr:u,arcToEdge:d}of n){for(let f=0;f<e;f++)r[f+1]+=u[f+1]-u[f];for(const f of d)o[f+1]++}for(let u=0;u<e;u++)r[u+1]+=r[u];for(let u=0;u<t;u++)o[u+1]+=o[u];const s=r[e],i=new Uint32Array(s),a=new Uint32Array(s);for(const{rowPtr:u,colIdx:d,arcToEdge:f}of n)for(let h=0;h<e;h++)for(let g=u[h];g<u[h+1];g++){const w=o[f[g]]++;i[w]=h,a[w]=d[g]}const c=r.slice(0,e),l=new Uint32Array(s);for(let u=0;u<s;u++)l[c[i[u]]++]=a[u];return{start:r,nbr:l}}function jh(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,{start:i,nbr:a}=vE(o,s,n.edgeCount),c=new Uint32Array(s),l=new Uint8Array(s);let u=0;for(let y=0;y<s;y++){if(l[y]===1)continue;l[y]=1;let b=u;for(c[u++]=y;b<u;){const v=c[b++];for(let A=i[v];A<i[v+1];A++)l[a[A]]===0&&(l[a[A]]=1,c[u++]=a[A])}}const d=new Uint32Array(s).fill(x),f=new Uint32Array(s).fill(x),h=new Uint32Array(s),g=new Uint32Array(s),w=new Uint32Array(s),p=new Uint32Array(s);let m=0;for(let y=0;y<s;y++){const b=c[y];if(!_e(t,b))continue;const v=y+1;let A=0;g[A++]=b,w[b]=i[b];let E=x;e:for(;A>0;){const I=g[A-1];for(;w[I]<i[I+1];){const k=a[w[I]++];if(h[k]===v||!_e(r,k))continue;h[k]=v;const N=f[k];if(N===x){E=k;break e}p[I]=k,g[A++]=N,w[N]=i[N];continue e}A--}if(E!==x){for(let I=A-1;I>=0;I--){const k=g[I],N=I===A-1?E:p[k];d[k]=N,f[N]=k}m++}}return{matching:d,size:m}}function AE(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,i=new Uint32Array(s).fill(x),a=new Uint8Array(s);let c=0;for(let l=0;l<s;l++)if(_e(t,l))e:for(const{rowPtr:u,colIdx:d}of o){const f=u[l+1];for(let h=u[l];h<f;h++){const g=d[h];if(a[g]===0&&_e(r,g)){a[g]=1,i[l]=g,c++;break e}}}return{matching:i,size:c}}function qh(n,e={}){const t=n.nodeCount,r=Ac(n,e.weights);if(t<2){const y=At(t,!0);return{...to(y,t),cutValue:0,side:y,cutEdges:new Uint32Array(0)}}const{src:o,dst:s}=n.edgeList(),i=new Uint32Array(t+1);for(let y=0;y<n.edgeCount;y++)i[o[y]+1]++,i[s[y]+1]++;for(let y=0;y<t;y++)i[y+1]+=i[y];const a=i.slice(0,t),c=new Uint32Array(i[t]),l=new Float64Array(i[t]);for(let y=0;y<n.edgeCount;y++)c[a[o[y]]]=s[y],l[a[o[y]]++]=r[y],c[a[s[y]]]=o[y],l[a[s[y]]++]=r[y];const u=new Uint32Array(t),d=new Uint32Array(t).fill(x),f=new Uint32Array(t);for(let y=0;y<t;y++)u[y]=y,f[y]=y;const h=new Float64Array(t),g=new Uint8Array(t),w=new sh(t);let p=1/0,m=At(t);for(let y=t;y>1;y--){let b=x;for(let E=0;E<t;E++)u[E]===E&&(g[E]=0,h[E]=0,b===x?b=E:w.push(E,0));let v=x,A=b;for(;;){g[A]=1;for(let E=A;E!==x;E=d[E])for(let I=i[E];I<i[E+1];I++){const k=u[c[I]];g[k]===0&&(h[k]+=l[I],w.pushOrIncrease(k,h[k]))}if(w.isEmpty())break;v=A,A=w.pop()}if(h[A]<p){p=h[A],m=At(t);for(let E=A;E!==x;E=d[E])pn(m,E,!0)}for(let E=A;E!==x;E=d[E])u[E]=v;d[f[v]]=A,f[v]=f[A]}return{...to(m,t),cutValue:p,side:m,cutEdges:Ec(n,m,!1,r,!1)}}function Hh(n,e={}){const t=e.iterations??100,r=e.randomSeed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`iterations must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const o=n.nodeCount,s=Ac(n,e.weights);if(o<2){const f=At(o);return{...to(f,o),cutValue:0,side:f,cutEdges:new Uint32Array(0)}}const{src:i,dst:a}=n.edgeList(),c=no(r),l=new Uint32Array(n.edgeCount);let u=1/0,d=At(o);for(let f=0;f<t;f++){for(let m=0;m<l.length;m++)l[m]=m;for(let m=l.length-1;m>0;m--){const y=Math.floor(c()*(m+1)),b=l[m];l[m]=l[y],l[y]=b}const h=new eo(o);let g=o;for(let m=0;m<l.length&&g>2;m++)h.union(i[l[m]],a[l[m]])&&g--;const w=h.find(0);let p=0;for(let m=0;m<n.edgeCount;m++)h.find(i[m])===w!=(h.find(a[m])===w)&&(p+=s[m]);if(p<u){u=p,d=At(o);for(let m=0;m<o;m++)pn(d,m,h.find(m)===w)}}return{...to(d,o),cutValue:u,side:d,cutEdges:Ec(n,d,!1,s,!1)}}function Kh(n,e={}){const t=n.edgeList(),r=n.edgeCount,o=new Float64Array(r);if(e.weights!==void 0)for(let u=0;u<r;u++)o[u]=e.weights[t.arc[u]];else if(t.weights!==null)for(let u=0;u<r;u++)o[u]=t.weights[u];else o.fill(1);const s=new Array(r);for(let u=0;u<r;u++)s[u]=u;s.sort((u,d)=>o[u]-o[d]||u-d);const i=new eo(n.nodeCount),a=new Uint32Array(Math.max(n.nodeCount-1,0));let c=0,l=0;for(const u of s)i.union(t.src[u],t.dst[u])&&(a[c++]=u,l+=o[u]);return{edges:a.subarray(0,c),totalWeight:l}}function Yh(n,e={}){if(n.directed)throw Q(new Error("Prim's algorithm requires an undirected graph"),"E_NEEDS_UNDIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=e.weights??n.weights,i=new Float64Array(t).fill(1/0),a=new Uint32Array(t).fill(x),c=new Uint8Array(t),l=new Yn(t),u=new Uint32Array(Math.max(t-1,0));let d=0,f=0;const h=g=>{for(l.push(g,0);!l.isEmpty();){const w=l.pop();c[w]=1,a[w]!==x&&(u[d++]=n.arcToEdge[a[w]],f+=i[w]);for(let p=r[w];p<r[w+1];p++){const m=o[p],y=s===null?1:s[p];c[m]===0&&y<i[m]&&(i[m]=y,a[m]=p,l.pushOrDecrease(m,y))}}};if(t>0&&h(e.start===void 0?0:xe(n,e.start)),e.forest===!0)for(let g=0;g<t;g++)c[g]===0&&h(g);else if(d<t-1)throw Q(new Error("Graph is not connected"),"E_NOT_CONNECTED");return{edges:u.subarray(0,d),totalWeight:f,predArc:a}}function Xh(n,e={}){return Jh(n,null,e)}function Qh(n,e,t={}){return Jh(n,eg(e,n.nodeCount,"personalization"),t)}function Jh(n,e,t){const r=n.nodeCount,o=t.dampingFactor??.85,s=t.maxIterations??100,i=t.tolerance??1e-6,a=t.convergenceNorm==="max";if(r===0)return{scores:new Float64Array(0),iterations:0,converged:!0};const c=n.reverse(),l=t.weighted===!0&&c.weights!==null,u=l?n.edges.byRole("weight"):null,d=u?.dtype==="f64"?u.data:null;let f=l?c.weights:null,h=l?n.weightedOutDegree():n.outDegree();d!==null&&(f=Zh(d,c.arcToEdge),h=EE(n,Zh(d,n.arcToEdge)));let g=(t.initialRanks===void 0?null:eg(t.initialRanks,r,"initialRanks"))??new Float64Array(r).fill(t.initialRanks===void 0?1/r:0),w=new Float64Array(r),p=0,m=!1;for(;p<s&&!m;p++){let y=0;for(let A=0;A<r;A++)h[A]===0&&(y+=g[A]);const b=1-o+o*y*(e===null?1:1/r);let v=0;for(let A=0;A<r;A++){let E=0;const I=c.rowPtr[A+1];for(let N=c.rowPtr[A];N<I;N++){const C=c.colIdx[N],O=h[C];O>0&&(E+=g[C]*(f===null?1:f[N])/O)}w[A]=b*(e===null?1/r:e[A])+o*E;const k=Math.abs(w[A]-g[A]);v=a?Math.max(v,k):v+k}[g,w]=[w,g],m=v<i}return{scores:g,iterations:p,converged:m}}function Zh(n,e){const t=new Float64Array(e.length);for(let r=0;r<t.length;r++)t[r]=n[e[r]];return t}function EE(n,e){const t=new Float64Array(n.nodeCount);for(let r=0;r<n.nodeCount;r++)for(let o=n.rowPtr[r];o<n.rowPtr[r+1];o++)t[r]+=e[o];return t}function eg(n,e,t){if(n.length!==e)throw Q(new Error(`PageRank: ${t} has ${String(n.length)} entries for ${String(e)} nodes`),"E_BAD_OPTION");let r=0;for(const s of n){if(!Number.isFinite(s)||s<0)throw Q(new Error(`PageRank: ${t} must be finite and non-negative, got ${String(s)}`),"E_BAD_OPTION");r+=s}if(r===0)return null;const o=new Float64Array(e);for(let s=0;s<e;s++)o[s]=n[s]/r;return o}const tg={distance:1/0,path:new Uint32Array(0),edges:new Uint32Array(0)};function _E(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);if(o===s)return{distance:0,path:Uint32Array.of(o),edges:new Uint32Array(0)};const i=n.nodeCount,a=r.weights??n.weights;if(a?.some(C=>C<0)===!0)throw Q(new Error("Bidirectional Dijkstra does not support negative edge weights"),"E_BAD_WEIGHT");const c=n.reverse(),l=C=>a===null?1:a[C],u=new Float64Array(i).fill(1/0),d=new Float64Array(i).fill(1/0),f=new Uint32Array(i).fill(x),h=new Uint32Array(i).fill(x),g=new Uint32Array(i).fill(x),w=new Yn(i),p=new Yn(i);u[o]=0,d[s]=0,w.push(o,0),p.push(s,0);let m=1/0,y=x,b=x,v=x,A=0;for(;w.peekKey()+p.peekKey()<m;)if(w.peekKey()<=p.peekKey()){const C=w.pop();for(let O=n.rowPtr[C];O<n.rowPtr[C+1];O++){const T=n.colIdx[O],$=l(O),L=u[C]+$;L<u[T]&&(u[T]=L,f[T]=O,w.pushOrDecrease(T,L)),L+d[T]<m&&(m=L+d[T],[y,b,v,A]=[C,T,n.arcToEdge[O],$])}}else{const C=p.pop();for(let O=c.rowPtr[C];O<c.rowPtr[C+1];O++){const T=c.colIdx[O],$=l(c.fwdArc[O]),L=d[C]+$;L<d[T]&&(d[T]=L,h[T]=O,g[T]=C,p.pushOrDecrease(T,L)),u[T]+L<m&&(m=u[T]+L,[y,b,v,A]=[T,C,c.arcToEdge[O],$])}}if(y===x)return tg;const E=[],I=[],k=[];for(let C=y;C!==o;C=n.arcSource(f[C]))E.push(C),I.push(n.arcToEdge[f[C]]),k.push(l(f[C]));E.push(o),E.reverse(),I.reverse(),k.reverse(),I.push(v),k.push(A),E.push(b);for(let C=b;C!==s;C=g[C])I.push(c.arcToEdge[h[C]]),k.push(l(c.fwdArc[h[C]])),E.push(g[C]);let N=0;for(const C of k)N+=C;return{distance:N,path:Uint32Array.from(E),edges:Uint32Array.from(I)}}function IE(n,e,t,r,o){const{gScore:s,fScore:i,predArc:a,closed:c,heap:l}=o;for(let u=n.rowPtr[e];u<n.rowPtr[e+1];u++){const d=n.colIdx[u];if(c[d]===1)continue;const f=s[e]+(t===null?1:t[u]);f<s[d]&&(s[d]=f,i[d]=f+r(d),a[d]=u,l.pushOrDecrease(d,i[d]))}}function kE(n,e,t,r,o={}){const s=xe(n,e),i=xe(n,t),a=n.nodeCount;if(!(i>=0&&i<a))throw Q(new RangeError(`Target index ${String(i)} is outside the graph's ${String(a)} nodes`),"E_BAD_NODE");const c=o.weights??n.weights,l=new Float64Array(a).fill(1/0),u=new Float64Array(a).fill(1/0),d=new Uint32Array(a).fill(x),f=new Uint8Array(a),h=[],g=new Yn(a);for(l[s]=0,u[s]=r(s,i),g.push(s,u[s]);!g.isEmpty();){const m=g.pop();if(m===i)break;f[m]=1,h.push(m),IE(n,m,c,y=>r(y,i),{gScore:l,fScore:u,predArc:d,closed:f,heap:g})}const w={gScore:l,fScore:u,visited:Uint32Array.from(h)};if(l[i]===1/0)return{...tg,...w};const p=Jr(n,d,s,i);return{distance:l[i],path:p,edges:Zr(n,d,s,i),...w}}function Nc(n,e={}){const{labels:t,count:r}=SE(n,e);return We(t,r)}function SE(n,e={}){if(!n.directed)throw Q(new Error("Strongly connected components require a directed graph. Use connectedComponents for an undirected one."),"E_NEEDS_DIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=ci(n,e.arcOrder),i=new Uint32Array(t).fill(x),a=new Uint32Array(t),c=new Uint32Array(t),l=new Uint8Array(t),u=new Uint32Array(t),d=new Uint32Array(t),f=new Uint32Array(t),h=new Uint32Array(t);let g=0,w=0,p=0,m=0,y=0;const b=v=>{i[v]=w,a[v]=w,w++,c[v]=r[v],d[m++]=v,l[v]=1,u[y++]=v};for(let v=0;v<t;v++)if(i[v]===x)for(b(v);y>0;){const A=u[y-1];if(c[A]<r[A+1]){const E=c[A]++,I=o[s===null?E:s[E]];i[I]===x?b(I):l[I]===1&&i[I]<a[A]&&(a[A]=i[I]);continue}if(y--,a[A]===i[A]){let E;do E=d[--m],l[E]=0,f[E]=p,h[g++]=E;while(E!==A);p++}y>0&&a[A]<a[u[y-1]]&&(a[u[y-1]]=a[A])}return{labels:f,count:p,popped:h}}function PE(n,e={}){const t=Nc(n,e),r=n.contract(t.labels,{selfLoops:"drop",parallel:"merge",weights:"first"});return{components:t,condensed:r}}const xE=1e-11,ng=3e3;function CE(n,e){const t=n.nodeCount,r=[{view:n,arcOf:l=>l}];if(n.directed){const l=n.reverse();r.push({view:l,arcOf:u=>l.fwdArc[u]})}const o=new Uint32Array(t+1);for(let l=0;l<t;l++){let u=0;for(const{view:d}of r)for(let f=d.rowPtr[l];f<d.rowPtr[l+1];f++)u+=d.colIdx[f]===l?0:1;o[l+1]=o[l]+u}const s=new Uint32Array(o[t]),i=new Float64Array(o[t]),a=new Float64Array(t);let c=0;for(let l=0;l<t;l++)for(const{view:u,arcOf:d}of r)for(let f=u.rowPtr[l];f<u.rowPtr[l+1];f++){const h=e===null?1:e[d(f)];if(!(h>=0)||h===1/0)throw Q(new RangeError(`an arc has weight ${h}; spectral clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");u.colIdx[f]!==l&&(s[c]=u.colIdx[f],i[c++]=h,a[l]+=h)}return{rowPtr:o,colIdx:s,w:i,degree:a}}function rg(n,e){for(let t=0;t<n.length;t++){const r=n[t];for(let o=0;;o++){for(let i=0;i<2;i++)for(let a=0;a<t;a++){const c=n[a];let l=0;for(let u=0;u<r.length;u++)l+=c[u]*r[u];for(let u=0;u<r.length;u++)r[u]-=l*c[u]}let s=0;for(let i=0;i<r.length;i++)s+=r[i]*r[i];if(s=Math.sqrt(s),s>1e-10||o===3){for(let i=0;i<r.length;i++)r[i]=s>0?r[i]/s:0;break}for(let i=0;i<r.length;i++)r[i]=e()-.5}}}function NE(n,e){const t=new Float64Array(e*e);for(let r=0;r<e;r++)t[r*e+r]=1;for(let r=0;r<100;r++){let o=0;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)o+=n[s*e+i]*n[s*e+i];if(o<1e-30)break;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++){const a=n[s*e+i];if(a===0)continue;const c=(n[i*e+i]-n[s*e+s])/(2*a),l=Math.sign(c||1)/(Math.abs(c)+Math.sqrt(c*c+1)),u=1/Math.sqrt(l*l+1),d=l*u;for(let f=0;f<e;f++){const h=n[f*e+s],g=n[f*e+i];n[f*e+s]=u*h-d*g,n[f*e+i]=d*h+u*g}for(let f=0;f<e;f++){const h=n[s*e+f],g=n[i*e+f];n[s*e+f]=u*h-d*g,n[i*e+f]=d*h+u*g}for(let f=0;f<e;f++){const h=t[f*e+s],g=t[f*e+i];t[f*e+s]=u*h-d*g,t[f*e+i]=d*h+u*g}}}return{values:Float64Array.from({length:e},(r,o)=>n[o*e+o]),vectors:t}}function TE(n,e,t){const r=n.length,o=new Float64Array(r*r);for(let s=0;s<r;s++)for(let i=s;i<r;i++){let a=0;for(let c=0;c<t;c++)a+=n[s][c]*e[i][c];o[s*r+i]=a,o[i*r+s]=a}return o}function OE(n,e,t,r,o){const s=Math.min(e,t+Math.max(t,8));let i=Array.from({length:s},()=>Float64Array.from({length:e},()=>o()-.5));rg(i,o);const a=new Float64Array(e),c=w=>(n(w,a),w.map((p,m)=>r*p-a[m]));let l=new Float64Array(s),u=[],d=new Float64Array(s*s),f=!1;for(let w=0;w<ng;w++){const p=i.map(c);if({values:l,vectors:d}=NE(TE(i,p,e),s),u=Array.from({length:s},(y,b)=>b).sort((y,b)=>l[b]-l[y]),f=u.slice(0,t).every(y=>{let b=0;for(let v=0;v<e;v++){let A=0;for(let E=0;E<s;E++)A+=d[E*s+y]*(p[E][v]-l[y]*i[E][v]);b+=A*A}return Math.sqrt(b)<=xE*r}),f||w===ng-1)break;i=p,rg(i,o)}const h=new Float64Array(t),g=[];for(let w=0;w<t;w++){const p=u[w];h[w]=Math.max(0,r-l[p]);const m=new Float64Array(e);for(let y=0;y<s;y++){const b=d[y*s+p];for(let v=0;v<e;v++)m[v]+=b*i[y][v]}g.push(m)}return{values:h,vectors:g,converged:f}}const $E=10;function RE(n,e,t,r,o){const s=new Float64Array(o*r),i=new Float64Array(o);for(let c=0;c<t;c++){i[e[c]]++;for(let l=0;l<r;l++)s[e[c]*r+l]+=n[c*r+l]}let a=0;for(let c=0;c<t;c++){const l=e[c];for(let u=0;u<r;u++){const d=n[c*r+u]-s[l*r+u]/i[l];a+=d*d}}return a}function DE(n,e,t,r,o,s,i){const a=(f,h,g)=>{let w=0;for(let p=0;p<t;p++){const m=n[f*t+p]-h[g*t+p];w+=m*m}return w},c=new Float64Array(r*t),l=new Float64Array(e).fill(1/0);let u=Math.floor(i()*e);for(let f=0;f<r;f++){c.set(n.subarray(u*t,u*t+t),f*t);let h=0;for(let w=0;w<e;w++)l[w]=Math.min(l[w],a(w,c,f)),h+=l[w];let g=i()*h;u=0;for(let w=0;w<e&&h>0;w++)if(g-=l[w],g<0){u=w;break}}const d=new Uint32Array(e);for(let f=0;f<o;f++){let h=f===0;for(let m=0;m<e;m++){let y=0,b=1/0;for(let v=0;v<r;v++){const A=a(m,c,v);A<b&&(b=A,y=v)}h||(h=d[m]!==y),d[m]=y}if(!h)break;const g=new Float64Array(r*t),w=new Float64Array(r);for(let m=0;m<e;m++){w[d[m]]++;for(let y=0;y<t;y++)g[d[m]*t+y]+=n[m*t+y]}let p=0;for(let m=0;m<r;m++){if(w[m]===0)continue;let y=0;for(let b=0;b<t;b++){const v=g[m*t+b]/w[m],A=v-c[m*t+b];y+=A*A,c[m*t+b]=v}p=Math.max(p,Math.sqrt(y))}if(p<s)break}return d}function LE(n,e){const{k:t}=e,r=e.laplacianType??"normalized",o=e.maxIterations??100,s=e.tolerance??1e-4,i=e.seed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`k must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!["unnormalized","normalized","randomWalk"].includes(r))throw Q(new RangeError(`unknown laplacianType "${r}"`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0||!(s>=0)||!Number.isInteger(i))throw Q(new RangeError("maxIterations and seed must be integers, maxIterations and tolerance non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;if(t>=c){const A=Uint32Array.from({length:c},(E,I)=>I);return{...We(A,c),eigenvalues:new Float64Array(0),eigenvectors:[],converged:!0}}const l=CE(n,a),u=l.degree.map(A=>A>0?1/Math.sqrt(A):0),d=r!=="unnormalized",f=(A,E)=>{for(let I=0;I<c;I++){let k=0;for(let N=l.rowPtr[I];N<l.rowPtr[I+1];N++){const C=l.colIdx[N];k+=d?l.w[N]*u[C]*A[C]:l.w[N]*A[C]}d?E[I]=l.degree[I]>0?A[I]-u[I]*k:0:E[I]=l.degree[I]*A[I]-k}};let h=2;if(!d){h=1;for(let A=0;A<c;A++)for(let E=l.rowPtr[A];E<l.rowPtr[A+1];E++)h=Math.max(h,l.degree[A]+l.degree[l.colIdx[E]])}const g=no(i),w=OE(f,c,t,h,g);if(r==="randomWalk")for(const A of w.vectors)for(let E=0;E<c;E++)A[E]*=l.degree[E]>0?u[E]:1;const p=new Float64Array(c*t);for(let A=0;A<t;A++)for(let E=0;E<c;E++)p[E*t+A]=w.vectors[A][E];if(r==="normalized")for(let A=0;A<c;A++){const E=p.subarray(A*t,A*t+t),I=YA(...E);I>0&&E.forEach((k,N)=>E[N]=k/I)}let m=new Uint32Array(c),y=1/0;for(let A=0;A<$E;A++){const E=DE(p,c,t,t,o,s,g),I=RE(p,E,c,t,t);I<y&&(y=I,m=E)}const{labels:b,count:v}=Je(m);return{...We(b,v),eigenvalues:w.values,eigenvectors:w.vectors,converged:w.converged}}const ME=10;function di(n,e,t,r,o){let s=0;for(let i=0;i<o;i++){const a=n[e*o+i]-t[r*o+i];s+=a*a}return Math.sqrt(s)}function UE(n,e,t){const r=n.nodeCount,o=new Float64Array(r*t),s=n.directed?n.degree():n.outDegree();for(let i=0;i<r;i++){const a=s[i]/Math.max(1,r-1);for(let c=0;c<t;c++)o[i*t+c]=(e()-.5)*.1+a*.1}return o}function FE(n,e){let t=1/0;for(let r=0;r<n.centreCount;r++)t=Math.min(t,di(n.emb,e,n.centres,r,n.dim));return t}function BE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n;for(let a=0;a<r;a++)if(t-=e[a],t<=0){i.set(s.subarray(a*o,(a+1)*o),n.centreCount*o),n.centreCount++;return}}function zE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n,a=Math.floor(t()*r);i.set(s.subarray(a*o,(a+1)*o),0),n.centreCount=1;const c=new Float64Array(r);for(let l=1;l<e;l++){let u=0;for(let d=0;d<r;d++){const f=FE(n,d);c[d]=f*f,u+=f*f}BE(n,c,t()*u)}}function og(n){const{n:e,dim:t,emb:r,centres:o,centreCount:s,labels:i}=n;for(let a=0;a<e;a++){let c=0,l=1/0;for(let u=0;u<s;u++){const d=di(r,a,o,u,t);d<l&&(l=d,c=u)}i[a]=c}}function GE(n,e,t,r){const{n:o,dim:s,rowPtr:i,colIdx:a,emb:c}=n;e.fill(0);for(let l=0;l<o;l++){const u=l*s;for(let d=i[l];d<i[l+1];d++){const f=a[d]*s;for(let h=0;h<s;h++)e[u+h]+=t*(c[u+h]-c[f+h])}}for(let l=0;l<o;l++){const u=i[l+1]-i[l],d=t===0||u===0?0:r/(t*u);for(let f=l*s;f<(l+1)*s;f++)c[f]-=d*e[f]}}function WE(n,e,t){const{n:r,dim:o,emb:s,centres:i,centreCount:a,labels:c}=n;e.fill(0),t.fill(0);for(let l=0;l<r;l++){const u=c[l];for(let d=0;d<o;d++)e[u*o+d]+=s[l*o+d];t[u]++}for(let l=0;l<a;l++)if(t[l]>0)for(let u=0;u<o;u++)i[l*o+u]=e[l*o+u]/t[l]}function VE(n,e){const{n:t,dim:r,rowPtr:o,colIdx:s,emb:i,centres:a,labels:c}=n;let l=0,u=0,d=0;for(let f=0;f<t;f++){const h=di(i,f,a,c[f],r);l+=h*h}for(let f=0;f<t;f++)for(let h=o[f];h<o[f+1];h++){const g=di(i,f,i,s[h],r);u+=g*g}for(const f of i)d+=f*f;return l+e*u+e*d}function jE(n,e){return n.every((t,r)=>t===e[r])}function qE(n,e){const{numClusters:t,maxIterations:r=1e3,tolerance:o=1e-6,seed:s=42,learningRate:i=.5,lambda:a=.1}=e,c=n.nodeCount;if(c===0)return{...We(new Uint32Array(0),t),embeddings:new Float64Array(0),dimensions:0,loss:0,previousLoss:1/0,iterations:0,converged:!0};if(!Number.isInteger(t)||t<=0||t>c)throw Q(new Error(`Invalid number of clusters: ${String(t)}. Must be between 1 and ${String(c)}`),"E_BAD_OPTION");const l=no(s),u=Math.min(64,c),d={n:c,dim:u,rowPtr:n.rowPtr,colIdx:n.colIdx,emb:UE(n,l,u),centres:new Float64Array(t*u),centreCount:0,labels:new Uint32Array(c)};zE(d,t,l);const f=new Float64Array(c*u),h=new Float64Array(t*u),g=new Uint32Array(t);let w=1/0,p=1/0,m=0,y=!1;const b=new Uint32Array(c);let v=0;for(;m<r;)if(m++,og(d),v=m>1&&jE(d.labels,b)?v+1:0,b.set(d.labels),GE(d,f,a,i),WE(d,h,g),m>1&&(w=p),p=VE(d,a),Math.abs(w-p)<o||v>=ME){y=!0;break}return og(d),{...We(d.labels,t),embeddings:d.emb,dimensions:u,loss:p,previousLoss:w,iterations:m,converged:y}}const HE=100;function KE(n,e,t){const r=n.nodeCount;if(!e){for(let s=0;s<r;s++)for(let i=s+1;i<r;i++)t[s*r+i]=t[i*r+s]=n.hasArc(s,i)?1:2;return}t.fill(1/0);const o=new Uint32Array(r);for(let s=0;s<r;s++)YE(n,s,t,o)}function YE(n,e,t,r){const o=e*n.nodeCount;t[o+e]=0,r[0]=e;let s=0,i=1;for(;s<i;){const a=r[s++],c=t[o+a]+1;for(let l=n.rowPtr[a];l<n.rowPtr[a+1];l++){const u=n.colIdx[l];t[o+u]===1/0&&(t[o+u]=c,r[i++]=u)}}}function XE(n,e={}){const{linkage:t="average",numClusters:r,distanceThreshold:o,useGraphDistance:s=!0}=e;if(r!==void 0&&(r<1||!Number.isInteger(r)))throw Q(new Error("numClusters must be a positive integer"),"E_BAD_OPTION");const i=n.nodeCount;if(i===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const a=Lf("teraHAC",i,e.maxNodes,8*i*i,()=>new Float64Array(i*i));if(KE(n,s,a),t==="ward")for(let D=0;D<a.length;D++)a[D]*=a[D];const l={single:Math.min,complete:Math.max,average:null,ward:null}[t],u=Math.max(0,i-1),d=new Uint32Array(u),f=new Uint32Array(u),h=new Float64Array(u),g=new Uint32Array(u),w=new Uint32Array(i),p=new Uint32Array(i).fill(1),m=new Uint8Array(i).fill(1);for(let D=0;D<i;D++)w[D]=D;const y=(D,U)=>{const B=w[D],V=w[U];return B<i&&V<i?B<V:B>V},b=(D,U)=>{const[B,V]=y(D,U)?[D,U]:[U,D];let W=a[B*i+V];return w[B]<i&&w[V]<i?W=t==="ward"?Math.sqrt(W):W:l||(W/=p[B]*p[V]),W===1/0?HE:W},v=(D,U)=>{const B=w[D],V=w[U],W=Math.min(B,V),q=Math.max(B,V);return q<i?W*i+q:i*i+q*2*i+W},A=new Int32Array(i).fill(-1),E=new Float64Array(i),I=new Float64Array(i),k=(D,U)=>{const B=b(D,U),V=v(D,U);(A[D]===-1||B<E[D]||B===E[D]&&V<I[D])&&(A[D]=U,E[D]=B,I[D]=V)},N=D=>{A[D]=-1;for(let U=0;U<i;U++)m[U]&&U!==D&&k(D,U)};for(let D=0;D<i;D++)N(D);let C=i,O=0;for(;C>1&&(r===void 0||C>r);){let D=-1;for(let W=0;W<i;W++)m[W]&&(D===-1||E[W]<E[D]||E[W]===E[D]&&I[W]<I[D])&&(D=W);const U=E[D];if(o!==void 0&&U>o)break;const[B,V]=y(D,A[D])?[D,A[D]]:[A[D],D];d[O]=w[B],f[O]=w[V],h[O]=U,g[O]=p[B]+p[V];for(let W=0;W<i;W++)if(m[W]&&W!==B&&W!==V){const q=B*i+W,K=V*i+W,X=W*i+B,H=W*i+V;a[q]=l?l(a[q],a[K]):a[q]+a[K],a[X]=l?l(a[X],a[H]):a[X]+a[H]}w[B]=i+O,p[B]=g[O],m[V]=0,O++,C--,N(B);for(let W=0;W<i;W++)m[W]&&W!==B&&(A[W]===B||A[W]===V?N(W):k(W,B))}const T=Array.from(w.filter((D,U)=>m[U]===1)).sort((D,U)=>D-U);let $=T[0];const L=D=>D<i?1:g[D-i];for(let D=1;D<T.length;D++){const U=O+D-1;d[U]=$,f[U]=T[D],h[U]=1/0,g[U]=L($)+L(T[D]),$=i+U}const F=QE(i,d,f,$,r??C),{labels:M,count:R}=Je(F);return{...We(M,R),left:d,right:f,distance:h,size:g,merges:O,root:$}}function QE(n,e,t,r,o){const s=[],i=[r];let a=0;for(;a<i.length&&s.length<o;){const l=i[a++];l<n||o===1||s.length+(i.length-a)+1>=o?s.push(l):i.push(e[l-n],t[l-n])}const c=new Uint32Array(n);return s.forEach((l,u)=>{const d=[l];for(;d.length>0;){const f=d.pop()??0;f<n?c[f]=u:d.push(e[f-n],t[f-n])}}),c}function JE(n,e,t){let r=e;for(let o=e;o<t;o++)(o===e||n[o]!==n[o-1])&&(n[r++]=n[o]);return r}function sg(n){const e=n.nodeCount,t=n.directed?[n,n.reverse()]:[n],r=new Uint32Array(e+1),o=new Uint32Array(t.reduce((i,a)=>i+a.colIdx.length,0));let s=0;for(let i=0;i<e;i++){r[i]=s;const a=s;for(const l of t)for(let u=l.rowPtr[i];u<l.rowPtr[i+1];u++)l.colIdx[u]!==i&&(o[s++]=l.colIdx[u]);const c=o.subarray(a,s);t.length>1&&c.sort(),s=JE(o,a,s)}return r[e]=s,{rowPtr:r,colIdx:o.slice(0,s)}}function ig(n,e,t){const r=n.length,o=new Float64Array(r);let s=0;for(let i=0;i<r;i++){const a=t[i+1]-t[i],c=a*(a-1)/2;s+=c,o[i]=c>0?n[i]/c:0}return{coefficient:o,transitivity:s>0?3*e/s:0}}function ZE(n,e,t,r,o){let s=0,i=e[t],a=e[r];const c=e[t+1],l=e[r+1];for(;i<c&&a<l;)n[i]<n[a]?i++:(n[i]>n[a]||(o[t]++,o[r]++,o[n[i]]++,s++,i++),a++);return s}function ag(n){const e=n.nodeCount,{rowPtr:t,colIdx:r}=sg(n),o=(u,d)=>{const f=t[u+1]-t[u],h=t[d+1]-t[d];return h>f||h===f&&d>u},s=new Uint32Array(e+1),i=new Uint32Array(r.length/2);let a=0;for(let u=0;u<e;u++){s[u]=a;for(let d=t[u];d<t[u+1];d++)o(u,r[d])&&(i[a++]=r[d])}s[e]=a;const c=new Uint32Array(e);let l=0;for(let u=0;u<e;u++){const d=s[u+1];for(let f=s[u];f<d;f++)l+=ZE(i,s,u,i[f],c)}return{perNode:c,total:l,...ig(c,l,t)}}function $t(n){return new Promise(e=>{e(n())})}function cg(n,e){if(n.sigmaOverflow===!0)throw new ZA(e);return n}function lg(n,e){return{normalized:e?.normalized,sources:is(n,e?.sources,e?.k)}}function e_(n,e,t){const r=t?.sources!==void 0||t?.k!==void 0,o=t?.harmonic===!0;return(!r||!e.directed)&&(!o||n.harmonicCloseness===!0&&!r)&&t?.normalized!==!0&&t?.cutoff===void 0&&t?.weights===void 0}function t_(n,e){const t=e?.weighted===!0;return e?.sources===void 0&&e?.k===void 0?e?.harmonic===!0?{weighted:t,harmonic:!0}:{weighted:t}:{weighted:t,sources:is(n,e.sources,e.k,"closenessCentrality")}}function n_(n,e){return e?.weights===void 0&&(e?.method??"auto")==="auto"&&e?.maxNodes===void 0&&e?.paths!==!0&&e?.weighted!==!1&&n.nodeCount<=zf&&n.flags.nonNegativeWeights&&n.flags.finiteWeights}function ug(n){return n?.initialRanks!==void 0||n?.convergenceNorm==="max"}function dg(n){return{dampingFactor:n?.dampingFactor,maxIterations:n?.maxIterations,tolerance:n?.tolerance,weighted:n?.weighted===!0}}function r_(n,e,t){const r=t?.weighted===!0&&n.weights!==null?n.weightedOutDegree():n.outDegree();return ug(t)||!e.some(o=>o>0)||r.includes(0)}function o_(n,e){return e?.startVector===void 0&&!n.directed&&!n.flags.multigraph&&!s_(n)}function s_(n){const e=n.nodeCount,t=new Int8Array(e).fill(-1),r=new Uint32Array(e);for(let o=0;o<e;o++){if(t[o]!==-1||n.rowPtr[o]===n.rowPtr[o+1])continue;t[o]=0;let s=0;r[s++]=o;let i=!1;for(let a=0;a<s;a++){const c=r[a];for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];t[u]===-1?(t[u]=1-t[c],r[s++]=u):t[u]===t[c]&&(i=!0)}}if(!i)return!0}return!1}function i_(n,e){if(!n.converged)throw new Mf("eigenvectorCentrality",e?.maxIterations??100,e?.tolerance??1e-6);if(e?.normalized===!1)return n;const t=Float64Array.from(n.scores);return dh(t),{scores:t,iterations:n.iterations,converged:!0}}function a_(n,e){if(e?.normalized===!1||e?.alpha===0)return!1;const t=n.reverse(),r=e?.weighted===!0?t.weights:null,o=new Float64Array(n.nodeCount);let s,i=!1;for(let l=0;l<n.nodeCount;l++){let u=0;for(let d=t.rowPtr[l];d<t.rowPtr[l+1];d++)u+=r===null?1:r[d],o[l]+=r===null?1:Math.abs(r[d]);s??(s=u),i||(i=u!==s)}if(!i)return!1;let a=0;for(let l=0;l<n.nodeCount;l++)for(let u=t.rowPtr[l];u<t.rowPtr[l+1];u++)a=Math.max(a,o[l]*o[t.colIdx[u]]);const c=e?.alpha??.1;return c*c*a<1}function c_(n){let e=1/0,t=-1/0;for(const o of n)e=Math.min(e,o),t=Math.max(t,o);const r=t-e;if(r>0)for(let o=0;o<n.length;o++)n[o]=(n[o]-e)/r}function l_(n){const e=Float64Array.from(n.scores);return c_(e),{scores:e,iterations:n.iterations,converged:n.converged}}function fg(n,e){let t=0;for(const r of n)t=e==="l2"?t+r*r:Math.max(t,r);if(t=e==="l2"?Math.sqrt(t):t,t>0)for(let r=0;r<n.length;r++)n[r]/=t}function u_(n,e){const t=e?.normalized===!1?"max":"l2",r=Float64Array.from(n.hubs),o=Float64Array.from(n.authorities);return fg(r,t),fg(o,t),{hubs:r,authorities:o,iterations:n.iterations,converged:n.converged}}function hg(n,e,t){const{predArc:r}=t;return{dist:t.dist,predArc:r,pathTo:o=>Jr(n,r,e,o),pathEdges:o=>Zr(n,r,e,o)}}function d_(n,e){const{perNode:t,total:r,coefficient:o,transitivity:s}=e;return o!==void 0&&s!==void 0?{perNode:t,total:r,coefficient:o,transitivity:s}:{perNode:t,total:r,...ig(t,r,sg(n).rowPtr)}}function f_(n){return{accelerator:n??null,pageRank:(e,t)=>n?.pageRank!==void 0&&!ug(t)?n.pageRank(e,dg(t)):Promise.resolve(Xh(e,t)),personalizedPageRank:(e,t,r)=>n?.personalizedPageRank!==void 0&&!r_(e,t,r)?n.personalizedPageRank(e,t,dg(r)):Promise.resolve(Qh(e,t,r)),eigenvectorCentrality:(e,t)=>n?.eigenvectorCentrality!==void 0&&o_(e,t)?n.eigenvectorCentrality(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:!1}).then(r=>i_(r,t)):new Promise(r=>{r(uh(e,t))}),sssp:(e,t,r)=>{const o=xe(e,t);return n?.sssp!==void 0?n.sssp(e,o,r).then(s=>hg(e,o,s)):Promise.resolve(Bf(e,o,r))},bellmanFord:(e,t,r)=>{const o=xe(e,t);return n?.bellmanFord!==void 0&&(r?.weights===void 0||r.weights instanceof Float32Array)?n.bellmanFord(e,o,r).then(s=>({...hg(e,o,s),hasNegativeCycle:s.hasNegativeCycle})):Promise.resolve(Wf(e,o,r))},breadthFirstSearch:(e,t,r)=>{const o=xe(e,t);return n?.breadthFirstSearch!==void 0&&r?.target===void 0&&r?.arcOrder===void 0?n.breadthFirstSearch(e,o,r):Promise.resolve(Kf(e,o,r))},connectedComponents:e=>n?.connectedComponents!==void 0?n.connectedComponents(e):Promise.resolve(th(e)),weaklyConnectedComponents:e=>n?.weaklyConnectedComponents!==void 0?n.weaklyConnectedComponents(e):Promise.resolve(nh(e)),minimumSpanningTree:(e,t)=>n?.minimumSpanningTree!==void 0&&t?.weights===void 0?n.minimumSpanningTree(e):Promise.resolve(Kh(e,t)),kCoreDecomposition:e=>n?.kCoreDecomposition!==void 0?n.kCoreDecomposition(e):Promise.resolve(kh(e)),katzCentrality:(e,t)=>n?.katzCentrality!==void 0&&a_(e,t)?n.katzCentrality(e,{alpha:t?.alpha,beta:t?.beta,maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(l_):Promise.resolve(Sh(e,t)),hits:(e,t)=>n?.hits!==void 0?n.hits(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(r=>u_(r,t)):Promise.resolve(Ah(e,t)),louvain:(e,t)=>n?.louvain!==void 0?n.louvain(e,t):Promise.resolve(Gh(e,t)),allPairsShortestPath:(e,t)=>n?.allPairsShortestPath!==void 0&&n_(e,t)?n.allPairsShortestPath(e).then(({dist:r,n:o})=>({dist:r,n:o,hasNegativeCycle:!1})):Promise.resolve(Gf(e,t)),betweennessCentrality:(e,t)=>n?.betweennessCentrality!==void 0&&!e.flags.multigraph&&t?.endpoints!==!0?n.betweennessCentrality(e,lg(e,t)).then(r=>cg(r,"betweennessCentrality")):Promise.resolve(qf(e,t)),edgeBetweennessCentrality:(e,t)=>n?.edgeBetweennessCentrality!==void 0&&!e.flags.multigraph&&t?.alive===void 0?n.edgeBetweennessCentrality(e,lg(e,t)).then(r=>cg(r,"edgeBetweennessCentrality")):Promise.resolve(dc(e,t)),closenessCentrality:(e,t)=>n?.closenessCentrality!==void 0&&e_(n,e,t)?n.closenessCentrality(e,t_(e,t)):Promise.resolve(Jf(e,t)),labelPropagation:(e,t)=>n?.labelPropagation!==void 0&&t?.randomSeed===void 0?n.labelPropagation(e,t):Promise.resolve(ph(e,t)),labelPropagationSynchronous:(e,t)=>n?.labelPropagation!==void 0?n.labelPropagation(e,{maxIterations:t?.maxIterations,weighted:t?.weighted}):Promise.resolve(mh(e,t)),triangleCount:e=>n?.triangleCount!==void 0?n.triangleCount(e).then(t=>d_(e,t)):Promise.resolve(ag(e)),depthFirstSearch:(e,t,r)=>$t(()=>lh(e,t,r)),degrees:e=>$t(()=>oh(e)),stronglyConnectedComponents:(e,t)=>$t(()=>Nc(e,t)),leiden:(e,t)=>$t(()=>Ch(e,t)),girvanNewman:(e,t)=>$t(()=>yh(e,t)),maxFlow:(e,t,r,o)=>$t(()=>_c(e,t,r,o)),minSTCut:(e,t,r,o)=>$t(()=>hh(e,t,r,o)),stoerWagner:(e,t)=>$t(()=>qh(e,t)),kargerMinCut:(e,t)=>$t(()=>Hh(e,t)),commonNeighborsPrediction:(e,t)=>$t(()=>Mh(e,t)),adamicAdarPrediction:(e,t)=>$t(()=>Fh(e,t)),primMST:(e,t)=>$t(()=>Yh(e,t)),maximumBipartiteMatching:(e,t)=>$t(()=>jh(e,t))}}const h_={graphtyAStar:["directed","goal","gpu","heuristic","root","weight"],graphtyAdamicAdarForPairs:["directed","gpu","pairs"],graphtyAdamicAdarPrediction:["directed","gpu","includeExisting","topK"],graphtyAdamicAdarScore:["directed","gpu","source","target"],graphtyAllPairsShortestPath:["directed","gpu","maxNodes","method","paths","weight"],graphtyBellmanFord:["cutoff","directed","field","gpu","root","weight"],graphtyBetweennessCentrality:["directed","endpoints","field","gpu","k","normalized","sources"],graphtyBidirectionalDijkstra:["directed","goal","gpu","root","weight"],graphtyBreadthFirstSearch:["directed","field","goal","gpu","maxDepth","root"],graphtyClosenessCentrality:["cutoff","directed","field","gpu","harmonic","k","normalized","sources","weight"],graphtyCommonNeighborsForPairs:["directed","gpu","pairs"],graphtyCommonNeighborsPrediction:["directed","gpu","includeExisting","topK"],graphtyCommonNeighborsScore:["directed","gpu","source","target"],graphtyCompareAdamicAdarWithCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyCondensation:["directed","field","gpu"],graphtyConnectedComponents:["directed","field","gpu"],graphtyDegreeCentrality:["directed","field","gpu","mode","normalized"],graphtyDegrees:["directed","gpu"],graphtyDeltaPageRank:["dampingFactor","deltaThreshold","directed","field","gpu","maxIterations","personalization","priority","tolerance","weight"],graphtyDepthFirstSearch:["directed","field","goal","gpu","order","root"],graphtyDijkstra:["cutoff","directed","field","gpu","root","weight"],graphtyDirectionOptimizedBfs:["alpha","beta","directed","field","gpu","root"],graphtyEdgeBetweennessCentrality:["directed","field","gpu","k","normalized","sources"],graphtyEigenvectorCentrality:["directed","field","gpu","maxIterations","mode","normalized","startVector","tolerance"],graphtyEvaluateAdamicAdar:["directed","edges","gpu","nonEdges"],graphtyEvaluateCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyFindAllIsomorphisms:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyGirvanNewman:["directed","field","gpu","maxCommunities","maxIterations","minCommunitySize","weight"],graphtyGreedyBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyGrsbm:["directed","field","gpu","maxDepth","maxIterations","minClusterSize","seed","tolerance","weight"],graphtyHasCycle:["directed","gpu"],graphtyHierarchicalClustering:["directed","gpu","linkage","maxNodes"],graphtyHits:["directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyIsBipartite:["arcs","directed","field","gpu"],graphtyIsGraphIsomorphic:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyKCoreDecomposition:["directed","field","gpu"],graphtyKargerMinCut:["directed","field","gpu","iterations","randomSeed","weight"],graphtyKatzCentrality:["alpha","beta","directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyKruskalMST:["directed","gpu","weight"],graphtyLabelPropagation:["directed","field","gpu","maxIterations","randomSeed","weight"],graphtyLabelPropagationSemiSupervised:["directed","field","gpu","maxIterations","randomSeed","seeds","weight"],graphtyLabelPropagationSynchronous:["directed","field","gpu","maxIterations","weight"],graphtyLeiden:["directed","field","gpu","maxIterations","randomSeed","resolution","threshold","weight"],graphtyLouvain:["directed","field","gpu","maxIterations","resolution","tolerance","weight"],graphtyMarkovClustering:["directed","expansion","field","gpu","inflation","maxIterations","pruningThreshold","selfLoops","tolerance","weight"],graphtyMaxFlow:["algorithm","directed","field","gpu","sink","source","weight"],graphtyMaximumBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyMinSTCut:["algorithm","directed","field","gpu","sink","source","weight"],graphtyModularity:["clusters","directed","gpu","resolution","weight"],graphtyNodeClosenessCentrality:["cutoff","directed","gpu","harmonic","normalized","root","weight"],graphtyPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","tolerance","weight"],graphtyPersonalizedPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","personalization","tolerance","weight"],graphtyPrimMST:["directed","forest","gpu","root","weight"],graphtySpectralClustering:["directed","field","gpu","k","laplacianType","maxIterations","seed","tolerance","weight"],graphtyStoerWagner:["directed","field","gpu","weight"],graphtyStronglyConnectedComponents:["directed","field","gpu"],graphtySyncClustering:["directed","field","gpu","lambda","learningRate","maxIterations","numClusters","seed","tolerance"],graphtyTeraHAC:["directed","distanceThreshold","field","gpu","linkage","maxNodes","numClusters","useGraphDistance"],graphtyTopAdamicAdarCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopologicalSort:["directed","gpu"],graphtyTriangleCount:["directed","field","gpu"],graphtyWeaklyConnectedComponents:["directed","field","gpu"]},g_={ak:["k"],"balanced-tree":["branching","height","seed","weights"],"barabasi-albert":["m","n","seed","triadProbability","weights"],barbell:["cliqueSize","pathLength","seed","weights"],"bianconi-barabasi":["fitness","m","n","seed","weights"],"bipartite-configuration-model":["leftDegrees","multiEdges","rightDegrees","seed","weights"],caveman:["cliques","seed","size","weights"],"chung-lu":["expectedDegrees","seed","weights"],"circular-ladder":["n","seed","weights"],complete:["n","seed","weights"],"complete-bipartite":["a","b","seed","weights"],"complete-multipartite":["seed","sizes","weights"],"configuration-model":["degrees","multiEdges","seed","selfLoops","weights"],"connected-caveman":["cliques","seed","size","weights"],cycle:["n","seed","weights"],"degree-corrected-sbm":["expectedDegrees","mixing","seed","sizes","weights"],"directed-configuration-model":["inDegrees","multiEdges","outDegrees","seed","selfLoops","weights"],"duplication-divergence":["n","retention","seed","weights"],empty:["n","seed","weights"],"erdos-renyi":["directed","n","p","seed","weights"],"erdos-renyi-gnm":["m","n","seed","weights"],"forest-fire":["backward","forward","maxBurn","n","seed","weights"],genrmf:["a","b","c1","c2","seed"],grid:["cols","diagonals","directed","obstacles","periodic","positions","rows","seed","weights"],"grid-3d":["cols","diagonals","directed","layers","obstacles","periodic","positions","rows","seed","weights"],"grid-flow-network":["cols","maxCapacity","minCapacity","rows","seed"],"hexagonal-lattice":["cols","positions","rows","seed","weights"],hyperbolic:["averageDegree","exponent","n","seed","temperature","weights"],hypercube:["dimension","seed","weights"],knn:["clusters","dimension","directed","k","n","seed","spread","weights"],kronecker:["directed","edges","initiator","multiEdges","permute","power","seed","selfLoops","weights"],ladder:["n","seed","weights"],"layered-flow-network":["layers","maxCapacity","minCapacity","p","seed"],lfr:["communityExponent","degreeExponent","maxCommunity","maxDegree","minCommunity","minDegree","mixing","n","seed","weights"],lollipop:["cliqueSize","pathLength","seed","weights"],"mobius-ladder":["n","seed","weights"],named:["name","seed","weights"],"newman-watts":["k","n","p","seed","weights"],path:["n","seed","weights"],petersen:["seed","weights"],"planted-partition":["groupSize","groups","pIn","pOut","seed","weights"],price:["attractiveness","citations","n","seed","weights"],"random-apollonian":["n","seed","weights"],"random-bipartite":["n1","n2","p","perfectMatching","seed","weights"],"random-dag":["layers","p","seed","weights"],"random-geometric":["dimension","n","periodic","radius","seed","weights"],"random-order-dag":["n","p","seed","weights"],"random-recursive-tree":["n","seed","weights"],"random-regular":["d","n","seed","weights"],"random-tree":["n","seed","weights"],"ring-of-cliques":["cliques","seed","size","weights"],rmat:["a","b","c","d","directed","edgeFactor","multiEdges","permute","scale","seed","selfLoops","weights"],star:["n","seed","weights"],"stochastic-block-model":["probabilities","seed","sizes","weights"],"triangular-lattice":["cols","positions","rows","seed","weights"],"watts-strogatz":["beta","k","n","seed","weights"],waxman:["alpha","beta","n","seed","weights"],wheel:["n","seed","weights"],"wilson-maze":["cols","rows","seed","weights"]},gg=5e3;function as(n,e){const t=setTimeout(()=>{console.warn(`graphty: ${e} has waited ${String(gg/1e3)} s for part of @graphty/cytoscape-extensions to load. If a module awaits ${e} at its top level, a Vite 6 or 7 production build never loads it: call it inside an async function, or with .then(), instead. On a slow network the call carries on.`)},gg),r=()=>{clearTimeout(t)};return n.then(r,r),n}const wg=new WeakMap,so=new Map,Tc=new Map;function fi(n){return n.cy()}function pg(n){let e=wg.get(n);if(e===void 0){const t={version:0,entries:[],dropListeners:new Set};n.on("add remove data move",()=>{t.version++,mg(t,t.entries),t.entries=[]}),wg.set(n,t),e=t}return e}function mg(n,e){const t=[];for(const{value:r}of e)so.has(r.snapshot)?Tc.set(r.snapshot,n):t.push(r.snapshot);yg(n,t)}function yg(n,e){if(e.length>0)for(const t of n.dropListeners)t(e)}function bg(n){so.set(n,(so.get(n)??0)+1);let e=!0;return()=>{if(!e)return;e=!1;const t=(so.get(n)??1)-1;if(t>0){so.set(n,t);return}so.delete(n);const r=Tc.get(n);r!==void 0&&(Tc.delete(n),yg(r,[n]))}}function w_(n,e){const t=pg(n);return t.dropListeners.add(e),()=>{t.dropListeners.delete(e)}}function hi(n,e={}){const t=e.directed??!1,r=n;if(typeof e.weight=="function")return vg(r,t,e.weight);const o=`${String(t)}|${e.weight??""}`,s=pg(fi(n)),i=s.entries.find(c=>c.key===o&&c.version===s.version&&p_(c.eles,r));if(i!==void 0)return i.value;const a=vg(r,t,e.weight);return mg(s,s.entries.filter(c=>c.key===o)),s.entries=[...s.entries.filter(c=>c.key!==o),{key:o,eles:r,version:s.version,value:a}],a}function p_(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function vg(n,e,t){const r=n.nodes(),o=[],s=new Map;r.forEach((d,f)=>{o.push(d.id()),s.set(d.id(),f)});const i=n.edges().filter(d=>s.has(d.source().id())&&s.has(d.target().id())),a=new Uint32Array(i.length),c=new Uint32Array(i.length),l=t===void 0?void 0:new Float64Array(i.length);return i.forEach((d,f)=>{if(a[f]=s.get(d.source().id())??0,c[f]=s.get(d.target().id())??0,l!==void 0&&t!==void 0){const h=typeof t=="function"?t(d):d.data(t);l[f]=typeof h=="number"&&Number.isFinite(h)?h:1}}),{snapshot:sc({directed:e,ids:o,src:a,dst:c,weights:l}),nodes:r,edges:i}}function io(n,e,t){fi(n).batch(()=>{n.forEach((r,o)=>{r.data(t,e[o])})})}function Gt(n,e){return(typeof e=="string"?n.nodes.filter(e):n.nodes.intersection(e)).map(r=>n.snapshot.ids.requireIndex(r.id()))}function ao(n,e,t){if(e===void 0)return;const[r]=Gt(n,e);if(r===void 0)throw new Error(`${t} matches no node of the collection`);return r}class Oc extends Error{constructor(e,t,r=null){super(t),this.name="GpuUnavailableError",this.code=e,this.fix=r}}function cs(){return Object.assign(new Error("graphty: the Cytoscape core was destroyed"),{code:"E_CORE_DESTROYED"})}const m_=["auto","off","require"];function $c(n,e){if(e!==void 0&&!m_.includes(e)){const r=e===null||typeof e=="number"||typeof e=="boolean"?String(e):`a value of type ${typeof e}`,o=typeof e=="string"?JSON.stringify(e):r;throw new TypeError(`${n}: gpu must be "auto", "off" or "require"; got ${o}`)}}const Ag=5e3;let Eg={},y_,Pr=null,Xn=null,Rc=!1;const _g=new WeakMap;function b_(n={}){Eg={...n},Pr=null,Xn=null,Rc=!1}function Ig(){const n=globalThis.navigator;return n?.gpu!==void 0&&n.gpu!==null?null:globalThis.process?.versions?.node===void 0?"this runtime has no WebGPU (navigator.gpu is undefined)":null}function v_(){if(Pr===null){const n=Ig();if(n!==null)Xn={reason:n??"WebGPU was disabled",fix:null},Pr=Promise.resolve(Xn);else{const e=as(Promise.resolve().then(()=>jO),"an ...Async method or a simulation layout").then(t=>t.gpuProvider(Eg),t=>({reason:`@graphty/webgpu-graph-algorithms did not load: ${Sg(t)}`,fix:"check that @graphty/webgpu-graph-algorithms is installed and that your bundler serves its chunk"}));Pr=e,e.then(t=>{Pr===e&&(Xn=t)})}}return Pr}function kg(n){return"acquire"in n}function Sg(n){return n instanceof Error?n.message:String(n)}function Pg(n){n?.then(e=>e.gpu?.accelerator.dispose(),()=>{})}function A_(n){let e=_g.get(n);if(e===void 0){const t={decision:null,by:null,destroyed:!1};n.one("destroy",()=>{t.destroyed=!0,Pg(t.decision),t.decision=null}),_g.set(n,t),e=t}return e}async function E_(n,e,t){let r;try{r=await t.acquire()}catch(i){const a=i instanceof Oc?i.fix:null;return{gpu:null,reason:`no usable WebGPU device: ${Sg(i)}`,fix:a}}if(e.destroyed)return r.accelerator.dispose(),{gpu:null,reason:"the core was destroyed"};const o=w_(n,i=>{for(const a of i)r.accelerator.release(a)}),s=e.decision;return r.lost.then(()=>{o(),e.decision===s&&(e.decision=null)}),{gpu:r,reason:null}}function xg(n="auto"){if(n==="off")return{gpu:null,reason:'gpu: "off" was requested',fix:null};if(Pr===null&&y_===void 0){const e=Ig();if(e!==null)return{gpu:null,reason:e,fix:null}}return Xn===null||kg(Xn)?null:{gpu:null,...Xn}}async function Cg(n,e="auto"){let t=xg(e);if(t===null){const r=A_(n),o=v_(),s=Xn??await o;if(!kg(s))t={gpu:null,...s};else{if(r.destroyed)throw cs();(r.decision===null||r.by!==s)&&(Pg(r.decision),r.decision=Promise.resolve().then(()=>E_(n,r,s)),r.by=s),t=await r.decision}}if(e==="require"&&t.gpu===null)throw new Error(`graphty: gpu: "require" but ${t.reason??"no device"}`);return t}function Dc(n,e){Rc||n.gpu!==null||n.fix===void 0||n.fix===null||e<Ag||(Rc=!0,console.warn(`graphty: a ${e.toLocaleString("en-US")}-node graph ran on the CPU because ${n.reason??"no GPU"}. To use the GPU: ${n.fix}. Pass gpu: "off" to run on the CPU without this warning.`))}function __(n){let e=!1;return{accelerator:new Proxy(n,{get(r,o,s){const i=Reflect.get(r,o,s);return typeof i!="function"||o==="release"||o==="dispose"?i:(...a)=>(e=!0,i.apply(r,a))}}),used:()=>e}}function Lc(n,e,t){return n.gpu===null?{ran:"cpu",reason:n.reason,device:null}:e?{ran:"gpu",reason:null,device:n.gpu.device}:{ran:"cpu",reason:t,device:n.gpu.device}}const I_={breadthFirstSearch:Kf,sssp:Bf,bellmanFord:Wf,allPairsShortestPath:Gf,pageRank:Xh,personalizedPageRank:Qh,eigenvectorCentrality:uh,katzCentrality:Sh,hits:Ah,closenessCentrality:Jf,betweennessCentrality:qf,edgeBetweennessCentrality:dc,connectedComponents:th,weaklyConnectedComponents:nh,triangleCount:ag,labelPropagation:ph,labelPropagationSynchronous:mh};function ct(n,e){return n instanceof Promise?n.then(e):e(n)}const k_=new Set(["gpu","directed","weight","field","root","goal","target","source","sink","heuristic","personalization","seeds","left","right","clusters","pairs","edges","nonEdges","nodeMatch","edgeMatch","priority","candidates","sources","alive","startVector","initialRanks"]),S_=new Set(["breadthFirstSearch","directionOptimizedBfs","depthFirstSearch","hasCycle","topologicalSort","degreeCentrality","degrees","eigenvectorCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","stronglyConnectedComponents","condensation","kCoreDecomposition","triangleCount","isBipartite","isGraphIsomorphic","findAllIsomorphisms","hierarchicalClustering","teraHAC","syncClustering","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),P_=new Set(["hasCycle","topologicalSort","bidirectionalDijkstra","aStar","allPairsShortestPath","degrees","nodeClosenessCentrality","isGraphIsomorphic","findAllIsomorphisms","modularity","hierarchicalClustering","kruskalMST","primMST","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),gi={maxIterations:100,tolerance:1e-6},Mc={...gi,dampingFactor:.85},x_={pageRank:Mc,personalizedPageRank:Mc,deltaPageRank:Mc,eigenvectorCentrality:gi,hits:gi,katzCentrality:{...gi,alpha:.1,beta:1},labelPropagation:{maxIterations:100},labelPropagationSynchronous:{maxIterations:100},labelPropagationSemiSupervised:{maxIterations:100},allPairsShortestPath:{paths:!0},maxFlow:{algorithm:"edmonds-karp"},minSTCut:{algorithm:"ford-fulkerson"}},Ng=new Set(["topologicalSort","stronglyConnectedComponents","condensation","deltaPageRank"]);function ls(n,e){return n.cy.collection(e)}function Uc(n){if(n.s.weights?.some(e=>e<0)===!0)throw Object.assign(new Error(`${n.name}: a weight is negative; use graphtyBellmanFord`),{code:"E_BAD_WEIGHT"})}function Be(n,e,t){const r=ao(n.cs,e,`${n.name}: ${t}`);if(r===void 0)throw new Error(`${n.name}: the ${t} option is required`);return r}function bn(n,e,t=!1){const r=t?n.cs.edges:n.cs.nodes,s=(typeof e=="string"?r.filter(e):e)[0];if(s===void 0)return;if(!t){const a=n.s.ids.indexOf(s.id());return a===x?void 0:a}const i=n.cs.edges.toArray().indexOf(s);return i<0?void 0:i}function Et(n,e,t=!1){return r=>{const o=bn(n,r,t);return o===void 0?void 0:e[o]}}function us(n,e){return ls(n,Array.from(e,t=>n.cs.nodes[t]))}function Fc(n,e){return ls(n,Array.from(e,t=>n.cs.edges[t]))}function wi(n,e,t){const r=[];for(let o=0;o<e.length;o++)o>0&&r.push(n.cs.edges[t[o-1]]),r.push(n.cs.nodes[e[o]]);return ls(n,r)}function Qn(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);return{sources:e.map(r=>Be(n,r[0],t)),targets:e.map(r=>Be(n,r[1],t))}}function pi(n,e){if(e===void 0)return;const t=At(n.s.nodeCount);for(const r of Gt(n.cs,e))pn(t,r,!0);return t}function Zt(n,e,t,r=!1){return n.field!==void 0&&io(r?n.cs.edges:n.cs.nodes,e,n.field),{score:Et(n,e,r),...t}}function lt(n,e,t){const r=[];for(let s=0;s<e.length;s++){const i=e[s];if(i!==x){const a=r[i]??[];a.push(s),r[i]=a}}n.field!==void 0&&io(n.cs.nodes,e,n.field);const o=Array.from(r,s=>us(n,s??[]));return Object.assign(o,t,{cluster:s=>{const i=bn(n,s);return i===void 0||e[i]===x?void 0:e[i]}})}function Bc(n,e,t){const r=[];for(let s=0;s<e.visitedCount;s++){const i=e.order[s],a=e.parent[i];if(a!==x){const c=n.cs.nodes[a],l=n.cs.nodes[i],d=(n.s.directed?c.edgesTo(l):c.edgesWith(l)).intersection(n.cs.edges)[0];d!==void 0&&r.push(d)}r.push(n.cs.nodes[i])}const o=t!==void 0&&e.depth[t]!==x;return n.field!==void 0&&io(n.cs.nodes,Array.from(e.depth,s=>s===x?Number.NaN:s),n.field),{path:ls(n,r),found:ls(n,o?[n.cs.nodes[t]]:[]),depth:s=>{const i=bn(n,s);return i===void 0||e.depth[i]===x?void 0:e.depth[i]},parent:s=>{const i=bn(n,s);return i===void 0||e.parent[i]===x?void 0:n.cs.nodes[e.parent[i]]}}}function Tg(n,e){return n.field!==void 0&&io(n.cs.nodes,e.dist,n.field),{distanceTo:t=>{const r=bn(n,t);return r===void 0?1/0:e.dist[r]},pathTo:t=>{const r=bn(n,t);return r===void 0?n.cy.collection():wi(n,e.pathTo(r),e.pathEdges(r))}}}function zc(n,e,t,r){const o=[],s=[];for(let i=0;i<n.s.nodeCount;i++)(_e(e,i)?o:s).push(i);return n.field!==void 0&&io(n.cs.nodes,Array.from({length:n.s.nodeCount},(i,a)=>_e(e,a)?0:1),n.field),{value:r,cut:Fc(n,t),partitionFirst:us(n,o),partitionSecond:us(n,s)}}function Gc(n,e){return zc(n,e.side,e.cutEdges,e.cutValue)}function mi(n,e){return Array.from(e.scores,(t,r)=>({source:n.cs.nodes[e.sources[r]],target:n.cs.nodes[e.targets[r]],score:t}))}function Og(n,e,t){return r=>{const o=bn(n,r);return o===void 0?void 0:e.nodes[t[o]]}}function $g(n,e,t){const{nodeMatch:r,edgeMatch:o}=t;return{...n.rest,nodeMatch:r&&((s,i)=>r(n.cs.nodes[s],e.nodes[i])),edgeMatch:o&&((s,i)=>o(n.cs.edges[s],e.edges[i]))}}function Rg(n,e){const t=e.other;if(t===void 0)throw new Error(`${n.name}: the other option (the collection to compare with) is required`);let r=t;if(typeof t=="string"?r=n.cy.$(t):Array.isArray(t)&&(r=n.cy.collection(t)),typeof r?.nodes!="function")throw new TypeError(`${n.name}: the other option must be a Cytoscape collection, a selector or an array of elements`);return hi(r,{directed:n.s.directed})}function yi(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);if(typeof e=="function")return Float64Array.from(n.cs.nodes.toArray(),o=>e(o));const r=new Float64Array(n.s.nodeCount);for(const o of Gt(n.cs,e))r[o]=1;return r}function Dg(n,e){const t=yi(n,e,"personalization");if(!t.some(r=>r>0))throw new Error(`${n.name}: personalization ${typeof e=="function"?"gives no node a positive weight":"matches no node"}`);return t}function Lg(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);const r=new Uint32Array(n.s.nodeCount).fill(x);if(typeof e=="string"){const o=new Map;n.cs.nodes.forEach((s,i)=>{const a=s.data(e);a!==void 0&&(r[i]=o.get(a)??o.set(a,o.size).size-1)})}else e.forEach((o,s)=>{for(const i of Gt(n.cs,o))r[i]=s});if(r.every(o=>o===x))throw new Error(typeof e=="string"?`${n.name}: ${t} names the data field "${e}", which no node has`:`${n.name}: ${t} matches no node`);return r}function C_(n,e){const t=(r,o)=>{const s=bn(n,r),i=bn(n,o);return s===void 0||i===void 0?void 0:[s,i]};return{hasNegativeWeightCycle:e.hasNegativeCycle,distance:(r,o)=>{const s=t(r,o);return s===void 0?1/0:e.dist[s[0]*e.n+s[1]]},path:(r,o)=>{const{pathTo:s,pathEdges:i}=e;if(s===void 0||i===void 0)throw new Error("allPairsShortestPath: pass paths: true to walk shortest paths");const a=t(r,o);return a===void 0?n.cy.collection():wi(n,s(a[0],a[1]),i(a[0],a[1]))}}}function Mg(n,e){return Zt(n,e.scores,{rank:Et(n,e.scores),iterations:e.iterations,converged:e.converged})}function Ug(n,e){return lt(n,e.labels,{iterations:e.iterations,converged:e.converged})}function Fg(n){return n.topK!==void 0&&n.topK<=0?1/0:n.topK}function Bg(n,e){const t=new Uint32Array(n.s.nodeCount).fill(x);return e.matching.forEach((r,o)=>{r!==x&&(t[o]=r,t[r]=o)}),{size:e.size,mate:r=>{const o=bn(n,r);return o===void 0||t[o]===x?void 0:n.cs.nodes[t[o]]}}}function N_(n){let e=0;for(let t=1;t<n.length;t++)n[t]>n[e]&&(e=t);return e}const Wc={breadthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);return ct(n.call("breadthFirstSearch",n.s,Be(n,e.root,"root"),{...n.rest,target:t}),r=>Bc(n,r,t))},directionOptimizedBfs:(n,e)=>Bc(n,l3(n.s,Be(n,e.root,"root"),n.rest),void 0),depthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);if(t!==void 0&&e.order==="post")throw new Error(`${n.name}: goal stops only a pre-order walk; leave it out with order "post"`);return Bc(n,lh(n.s,Be(n,e.root,"root"),{...n.rest,target:t}),t)},hasCycle:(n,e={})=>b3(n.s),topologicalSort:(n,e={})=>{const t=E3(n.s);return t===null?null:us(n,t)},dijkstra:(n,e)=>(Uc(n),ct(n.call("sssp",n.s,Be(n,e.root,"root"),n.rest),t=>Tg(n,t))),bellmanFord:(n,e)=>ct(n.call("bellmanFord",n.s,Be(n,e.root,"root"),n.rest),t=>({...Tg(n,t),hasNegativeWeightCycle:t.hasNegativeCycle})),bidirectionalDijkstra:(n,e)=>{Uc(n);const t=_E(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),n.rest);return{found:t.path.length>0,distance:t.distance,path:wi(n,t.path,t.edges)}},aStar:(n,e)=>{const t=e.heuristic;Uc(n);const r=kE(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),t===void 0?()=>0:o=>t(n.cs.nodes[o]),n.rest);return{found:r.path.length>0,distance:r.distance,path:wi(n,r.path,r.edges)}},allPairsShortestPath:(n,e={})=>ct(n.call("allPairsShortestPath",n.s,n.rest),t=>C_(n,t)),degreeCentrality:(n,e={})=>{const t=f3(n.s,n.rest);return Zt(n,t,{degree:Et(n,t)})},degrees:(n,e={})=>{const t=oh(n.s);if(!n.s.directed){const r=Float64Array.from(t.inDegree,(o,s)=>o+t.outDegree[s]);return{indegree:Et(n,r),outdegree:Et(n,r)}}return{indegree:Et(n,t.inDegree),outdegree:Et(n,t.outDegree)}},pageRank:(n,e={})=>{const t=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("pageRank",n.s,{...n.rest,initialRanks:t,weighted:n.weighted}),r=>Mg(n,r))},personalizedPageRank:(n,e)=>{const t=Dg(n,e.personalization),r=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("personalizedPageRank",n.s,t,{...n.rest,initialRanks:r,weighted:n.weighted}),o=>Mg(n,o))},deltaPageRank:(n,e={})=>{const t=e.personalization===void 0?void 0:Dg(n,e.personalization),r=e.priority===!0&&e.maxIterations===void 0?{maxIterations:1/0}:{},o={...n.rest,...r,personalization:t,weighted:n.weighted},s=e.priority===!0?new p3(n.s).computeWithPriority(o):new w3(n.s).compute(o);if(s.some(i=>!Number.isFinite(i)))throw new RangeError(`${n.name}: the ranks overflowed (maxIterations ${String(n.rest.maxIterations)} is too high for this graph); lower maxIterations, or pass priority: true`);return Zt(n,s,{rank:Et(n,s)})},eigenvectorCentrality:(n,e={})=>{const t=e.startVector&&yi(n,e.startVector,"startVector");return ct(n.call("eigenvectorCentrality",n.s,{...n.rest,startVector:t}),r=>Zt(n,r.scores,{iterations:r.iterations,converged:r.converged}))},katzCentrality:(n,e={})=>ct(n.call("katzCentrality",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.scores,{iterations:t.iterations,converged:t.converged})),hits:(n,e={})=>ct(n.call("hits",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.authorities,{hub:Et(n,t.hubs),authority:Et(n,t.authorities),iterations:t.iterations,converged:t.converged})),closenessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("closenessCentrality",n.s,{...n.rest,sources:t,weighted:n.weighted}),r=>Zt(n,r.scores,{closeness:Et(n,r.scores)}))},nodeClosenessCentrality:(n,e)=>u3(n.s,Be(n,e.root,"root"),{...n.rest,weighted:n.weighted}),betweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("betweennessCentrality",n.s,{...n.rest,sources:t}),r=>{const o=n.s.nodeCount,s=e.endpoints===!0?o*(o-1):(o-1)*(o-2),i=n.s.directed?1:2,a=e.normalized===!0&&s>0?s:i,c=Float64Array.from(r.scores,u=>u*a),l=c.reduce((u,d)=>Math.max(u,d),0);return Zt(n,r.scores,{betweenness:Et(n,c),betweennessNormalized:Et(n,c.map(u=>l===0?0:u/l))})})},edgeBetweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("edgeBetweennessCentrality",n.s,{...n.rest,sources:t}),r=>Zt(n,r.scores,{},!0))},connectedComponents:(n,e={})=>ct(n.call("connectedComponents",n.s),t=>lt(n,t.labels,{})),weaklyConnectedComponents:(n,e={})=>ct(n.call("weaklyConnectedComponents",n.s),t=>lt(n,t.labels,{})),stronglyConnectedComponents:(n,e={})=>lt(n,Nc(n.s).labels,{}),condensation:(n,e={})=>{const t=PE(n.s);return lt(n,t.components.labels,{condensed:t.condensed})},kCoreDecomposition:(n,e={})=>{const t=kh(n.s),r=o=>us(n,Array.from(t.coreness.keys()).filter(s=>t.coreness[s]>=o));return Zt(n,t.coreness,{maxCore:t.maxCore,core:r})},triangleCount:(n,e={})=>ct(n.call("triangleCount",n.s),t=>Zt(n,t.perNode,{coefficient:Et(n,t.coefficient),total:t.total,transitivity:t.transitivity})),isBipartite:(n,e={})=>{const t=Yf(n.s,n.rest);if(t.sides===null){const s=n.cy.collection();return{bipartite:!1,partitionFirst:s,partitionSecond:s}}const{partitionFirst:r,partitionSecond:o}=zc(n,t.sides,[],0);return{bipartite:!0,partitionFirst:r,partitionSecond:o}},isGraphIsomorphic:(n,e)=>{const t=Rg(n,e),r=H3(n.s,t.snapshot,$g(n,t,e)),o=r.mapping;return{isomorphic:r.isomorphic,mapping:o===null?()=>{}:Og(n,t,o)}},findAllIsomorphisms:(n,e)=>{const t=Rg(n,e);return K3(n.s,t.snapshot,$g(n,t,e)).map(r=>Og(n,t,r))},modularity:(n,e)=>xc(n.s,Lg(n,e.clusters,"clusters"),n.rest),louvain:(n,e={})=>{const t=Gh(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},leiden:(n,e={})=>{const t=Ch(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},labelPropagation:(n,e={})=>ct(n.call("labelPropagation",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSynchronous:(n,e={})=>ct(n.call("labelPropagationSynchronous",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSemiSupervised:(n,e)=>{const t=$3(n.s,Lg(n,e.seeds,"seeds"),{...n.rest,weighted:n.weighted});return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},girvanNewman:(n,e={})=>{const t=yh(n.s,n.rest),r={...n,field:void 0},o=i=>lt(r,t.levels[i]??[],{}),s=N_(t.modularity);return lt(n,t.levels[s]??[],{modularity:t.modularity[s]??Number.NaN,levels:t.levels.length,level:o,modularities:Array.from(t.modularity)})},markovClustering:(n,e={})=>{const t=bE(n.s,n.rest);return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},spectralClustering:(n,e)=>{if(e.k===void 0)throw new Error(`${n.name}: the k option is required`);const t=LE(n.s,n.rest);return lt(n,t.labels,{converged:t.converged,eigenvalues:t.eigenvalues})},hierarchicalClustering:(n,e={})=>{const t=V3(n.s,n.rest),r={...n,field:void 0},o=i=>{const a=new Uint32Array(n.s.nodeCount).fill(x);return t.cut(i).forEach((c,l)=>{for(const u of c)a[u]=l}),lt(r,a,{})},s=i=>lt(r,t.cutAt(i).labels,{});return{merges:t.left.length,cut:o,cutAt:s}},teraHAC:(n,e={})=>{const t=XE(n.s,n.rest);return lt(n,t.labels,{merges:t.merges})},grsbm:(n,e={})=>lt(n,B3(n.s,{...n.rest,weighted:n.weighted}).labels,{}),syncClustering:(n,e)=>{if(e.numClusters===void 0)throw new Error(`${n.name}: the numClusters option is required`);const t=qE(n.s,n.rest);return lt(n,t.labels,{loss:t.loss,iterations:t.iterations,converged:t.converged})},kruskalMST:(n,e={})=>{const t=Kh(n.s);return Object.assign(n.cs.nodes.union(Fc(n,t.edges)),{totalWeight:t.totalWeight})},primMST:(n,e={})=>{const t=ao(n.cs,e.root,`${n.name}: root`),r=Yh(n.s,{...n.rest,start:t});return Object.assign(n.cs.nodes.union(Fc(n,r.edges)),{totalWeight:r.totalWeight})},maxFlow:(n,e)=>{const t=_c(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest);return{...zc(n,t.sourceSide,t.cutEdges,t.maxFlow),flow:Et(n,t.flow,!0)}},minSTCut:(n,e)=>Gc(n,hh(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest)),stoerWagner:(n,e={})=>Gc(n,qh(n.s)),kargerMinCut:(n,e={})=>Gc(n,Hh(n.s,n.rest)),maximumBipartiteMatching:(n,e={})=>Bg(n,jh(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),greedyBipartiteMatching:(n,e={})=>Bg(n,AE(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),commonNeighborsScore:(n,e)=>d3(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),adamicAdarScore:(n,e)=>sE(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),commonNeighborsPrediction:(n,e={})=>mi(n,Mh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),adamicAdarPrediction:(n,e={})=>mi(n,Fh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),commonNeighborsForPairs:(n,e)=>Array.from(rE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),adamicAdarForPairs:(n,e)=>Array.from(iE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),topCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,oE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},topAdamicAdarCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,aE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},evaluateCommonNeighbors:(n,e)=>Uh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),evaluateAdamicAdar:(n,e)=>Bh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),compareAdamicAdarWithCommonNeighbors:(n,e)=>{const t=Qn(n,e.edges,"edges"),r=Qn(n,e.nonEdges,"nonEdges"),o={directed:n.s.directed};return{adamicAdar:Bh(n.s,t,r,o),commonNeighbors:Uh(n.s,t,r,o)}}};function $n(n){return`graphty${n.charAt(0).toUpperCase()}${n.slice(1)}`}const T_=Object.keys(Wc).map($n),Vc=["breadthFirstSearch","dijkstra","bellmanFord","allPairsShortestPath","pageRank","personalizedPageRank","eigenvectorCentrality","katzCentrality","hits","closenessCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","triangleCount","labelPropagation","labelPropagationSynchronous"],O_=Vc.map(n=>`${$n(n)}Async`);function zg(n,e,t,r){const o=$n(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${o}: takes one options object; pass a weight function as { weight: fn }`);if(t.weight!==void 0&&S_.has(e))throw new Error(`${o}: this algorithm reads no edge weights; remove the weight option`);if(t.field!==void 0&&P_.has(e))throw new Error(`${o}: this algorithm has no per-element value to write; remove the field option`);const s=h_[o]??[];for(const[h,g]of Object.entries(t))if(g!==void 0&&!s.includes(h))throw new Error(`${o}: unknown option ${h}; the options are ${s.join(", ")}`);const i=t.directed??Ng.has(e),{mode:a}=t;if((a==="in"||a==="out")&&!i)throw new Error(`${o}: mode: "${a}" needs directed: true`);const c=hi(n,{directed:i,weight:t.weight}),l={...x_[e],...Object.fromEntries(Object.entries(t).filter(([h,g])=>!k_.has(h)&&g!==void 0))},u={name:o,cy:fi(n),cs:c,s:c.snapshot,field:t.field,weighted:t.weight!==void 0,rest:l,call:(h,...g)=>r[h](...g)},d=h=>{throw $_(h,e)};let f;try{f=Wc[e](u,t)}catch(h){d(h)}return{result:f instanceof Promise?f.catch(d):f,snapshot:c.snapshot}}function $_(n,e){if(!(n instanceof Error))return n;const t=$n(e),{code:r}=n;if(r==="E_NEEDS_UNDIRECTED"){const o=e==="connectedComponents"?", or call graphtyWeaklyConnectedComponents":"";n.message=`${t}: needs an undirected graph; leave out directed: true${o}`}else r==="E_NEEDS_DIRECTED"?n.message=`${t}: needs a directed graph; ${Ng.has(e)?"leave out directed: false":"pass directed: true"}`:n.message.startsWith(`${t}:`)||(n.message=`${t}: ${n.message}`);return n}function Gg(n,e,t={}){if($c($n(e),t?.gpu),t.gpu==="require"){const r=$n(e);throw new Error(Vc.includes(e)?`${r}: runs on the CPU; call ${r}Async for the GPU`:`${r}: has no GPU implementation and runs only on the CPU; leave out gpu: "require"`)}return zg(n,e,t,I_).result}async function Wg(n,e,t={}){$c(`${$n(e)}Async`,t?.gpu);const r=fi(n),o=await Cg(r,t.gpu);if(r.destroyed())throw cs();const s=o.gpu===null?null:__(o.gpu.accelerator);Dc(o,n.nodes().length);const{result:i,snapshot:a}=zg(n,e,t,f_(s?.accelerator??null)),c=bg(a);let l;try{l=await i}catch(d){throw r.destroyed()?cs():d}finally{c(),o.gpu!==null&&typeof t.weight=="function"&&o.gpu.accelerator.release(a)}const u=Lc(o,s?.used()??!1,"the options or the graph need the CPU implementation");return Object.assign(l,{backend:u})}function R_(n){for(const e of Object.keys(Wc)){const t=$n(e);n("collection",t,function(r){return Gg(this,e,r)}),n("core",t,function(r){return Gg(this.elements(),e,r)})}for(const e of Vc){const t=`${$n(e)}Async`;n("collection",t,function(r){return Wg(this,e,r)}),n("core",t,function(r){return Wg(this.elements(),e,r)})}}class D_ extends Error{constructor(e){super(`graphty: the core already has an element with id "${e}", so the new graph would merge into it; remove the existing elements (cy.elements().remove()) or add the graph to an empty core`),this.code="E_ID_TAKEN",this.name="IdTakenError",this.id=e}}function jc(n,e){if(n.destroyed())throw cs();for(const t of e)if(t.group==="nodes"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty())throw new D_(t.data.id);for(const t of e)t.group==="edges"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty()&&delete t.data.id;return n.add(e)}function L_(n){const e=new Set(n.elements("[graphty_import]").map(r=>String(r.data("graphty_import"))));let t=e.size+1;for(;e.has(String(t));)t++;return String(t)}function M_(n,e,t){let r=0;e.forEach((o,s)=>{const i=n[r];if(i?.id()!==o.data.id)return;r++;const a=t[s];a!=null&&i.style(a)})}function U_(n){n("core","graphtyGenerate",async function(t,r){const{generateElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyGenerate"),s=o(t,r);return{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyDataset",async function(t,r){const{datasetElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyDataset"),s=await o(t,r);return r?.signal?.throwIfAborted(),{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyImport",async function(t,r,o){const{importElements:s}=await as(vu("io.js"),"graphtyImport"),i=o?.styles!==void 0&&o.styles!==!1,a=await s(t,r,{...o,...i&&o.importId===void 0?{importId:L_(this)}:{}}),c=o?.applyStyles===!0&&a.stylesheet!==void 0,l=jc(this,a.elements);c&&a.bypass!==void 0&&M_(l,a.elements,a.bypass);const u=this.style();if(c&&a.stylesheet!==void 0&&u!==void 0){let d=u;for(const f of a.stylesheet)d=d.selector(f.selector).style(f.style);d.update()}return{elements:l,directed:a.directed,format:a.format,report:a.report,...a.stylesheet===void 0?{}:{stylesheet:a.stylesheet}}});const e=async(t,r,o)=>{const{exportElements:s}=await as(vu("io.js"),"graphtyExport");return s(t,r,o)};n("core","graphtyExport",function(t,r){return e(this.elements(),t,r)}),n("collection","graphtyExport",function(t,r){return e(this,t,r)})}function F_(n,e,t,r){const{positions:o,dim:s,n:i}=n,a=new Float32Array(3*i),c=[0,0,0];for(let l=0;l<i;l++)for(let u=0;u<3;u++)a[3*l+u]=u<s?o[s*l+u]*e+c[u]:c[u];return a}function B_(n,e,t){const r=new Float64Array(t),o=new Float64Array(t);for(let s=0;s<e*t;s++){const i=n[s];Number.isNaN(i)||(r[s%t]+=i,o[s%t]++)}for(let s=0;s<t;s++)r[s]=o[s]>0?r[s]/o[s]:0;return r}function z_(n,e,t,r){let o=0;for(let s=0;s<e;s++){let i=0;for(let a=0;a<t;a++){const c=n[t*s+a]-r[a];Number.isNaN(c)||(i+=c*c)}o=Math.max(o,Math.sqrt(i))}return o}function Jn(n,e,t=1,r){const o=Math.floor(n.length/e),s=B_(n,o,e),i=z_(n,o,e,s),a=i>0?t/i:0;for(let c=0;c<o*e;c++){const l=n[c],u=r?.[c%e]??0;Number.isNaN(l)||(n[c]=a===0?u:(l-s[c%e])*a+u)}return n}const qc=34359738337,G_=185852,W_=1;let Vg=class{constructor(e){this.seed=e===null||e===0||Number.isNaN(e)?Math.floor(Math.random()*1e6):e,this.state=this.seed%qc}next(){return this.state=(G_*this.state+W_)%qc,this.state/qc}};function V_(n){const e=[0,0,0];if(n===null)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function bi(n,e,t,r,o,s,i){const a=n.nodeCount;if(r!==2&&r!==3)throw new RangeError(`dim must be 2 or 3, got ${String(r)}`);if(e.length!==3*a)throw new RangeError(`positions has ${e.length} entries, expected ${3*a}`);if(!Number.isFinite(o)||o<=0)throw new RangeError(`scale must be a finite number > 0, got ${o}`);const c=V_(s),l=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];let d=0,f=0;for(let y=0;y<a;y++){let b=!0;for(let v=0;v<r;v++){const A=e[3*y+v];Number.isFinite(A)?(A<l[v]&&(l[v]=A),A>u[v]&&(u[v]=A)):b=!1}b?d++:f++}if(f===0)return;const h=i==="fr"?0:-1,g=1,w=[h,h,h],p=[g,g,g];if(d>0){for(let y=0;y<r;y++)if(Number.isFinite(l[y])&&Number.isFinite(u[y])&&(w[y]=(l[y]-c[y])/o,p[y]=(u[y]-c[y])/o,w[y]===p[y])){const b=(g-h)/2;w[y]-=b,p[y]+=b}}const m=new Vg(t);for(let y=0;y<a;y++){let b=!1;for(let v=0;v<r;v++)Number.isFinite(e[3*y+v])||(b=!0);if(b){for(let v=0;v<r;v++){const A=3*y+v;if(!Number.isFinite(e[A])){const E=m.next(),I=w[v]+E*(p[v]-w[v]);e[A]=I*o+c[v]}}r===2&&(e[3*y+2]=c[2])}}}const jg=new WeakMap;function j_(n){if(n!=null)return typeof n=="number"?n:typeof n=="string"?Number(n):Number.NaN}function co(n,e=null){if(vv(n)){if(!n.directed)return n;const r=jg.get(n);if(r!==void 0)return r;const o=n.toUndirected().snapshot;return jg.set(n,o),o}const t=new oi({directed:!1,weighted:"auto"});if(Array.isArray(n))t.addNodes(n);else{t.addNodes(n.nodes());for(const[r,o]of n.edges()){const s=e!==null&&n.getEdgeData!==void 0?n.getEdgeData(r,o,e):void 0;t.addEdge(r,o,j_(s))}}return t.freeze()}function ze(n,e,t){return Object.assign(n,{code:e,params:t})}function en(n,e){const t=e.dim??2;if(t!==2&&t!==3)throw ze(new Error(`dim must be 2 or 3, got ${String(t)}`),"E_BAD_OPTION",{option:"dim",value:t});const r=Array.from({length:t},(o,s)=>e.center?.[s]??0);return{n:n.nodeCount,dim:t,scale:e.scale??1,center:r}}function Wt(n,e,t){return{positions:Float32Array.from(n),dim:e,n:t}}function Rn(n,e,t){if(e===2)return n;const r=n.length/2,o=new Float64Array(3*r);for(let s=0;s<r;s++)o[3*s]=n[2*s],o[3*s+1]=n[2*s+1],o[3*s+2]=Number.isNaN(n[2*s])?Number.NaN:t[2];return o}function qg(n){const e=n??2;if(e!==2&&e!==3)throw ze(new RangeError(`dim must be 2 or 3, got ${String(e)}`),"E_BAD_OPTION",{option:"dim",value:e});return e}function q_(n,e,t){const r=n.nodeCount;if(e==null)return new Float32Array(3*r).fill(Number.NaN);if(e.length!==t*r)throw ze(new RangeError(`pos has ${e.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:e.length,expected:t*r});return F_({positions:e,dim:t,n:r},1)}function H_(n,e={}){const{scaling:t=1,a:r=1.1,maxIter:o=1e3}=e;if(r<=1)throw ze(new Error("The parameter a should be larger than 1"),"E_BAD_OPTION",{option:"a",value:r});const s=co(n),i=qg(e.dim),a=s.nodeCount,c=Float64Array.from(q_(s,e.pos,i));bi(s,c,e.seed??null,i,1,null,"fr");const l=new Float64Array(i*a);for(let b=0;b<a;b++)for(let v=0;v<i;v++)l[i*b+v]=c[3*b+v];const{rowPtr:u,colIdx:d}=s,f=t*Math.sqrt(a),h=.001,g=1e-6,w=new Float64Array(i*a),p=new Float64Array(i),m=new Int32Array(a);let y=g+1;for(let b=0;y>g&&b<o;b++){w.fill(0);for(let v=0;v<a;v++){for(let A=u[v];A<u[v+1];A++)m[d[A]]=v+1;for(let A=0;A<a;A++){if(v===A)continue;let E=0;for(let N=0;N<i;N++)p[N]=l[i*v+N]-l[i*A+N],E+=p[N]*p[N];const I=Math.sqrt(E)||.01,k=m[A]===v+1?r:1;for(let N=0;N<i;N++)w[i*v+N]+=f/I*p[N]-k*p[N]}}y=0;for(let v=0;v<a;v++){let A=0;for(let E=0;E<i;E++)l[i*v+E]+=w[i*v+E]*h,A+=w[i*v+E]*w[i*v+E];y+=Math.sqrt(A)}}return(e.scale!==void 0||e.center!==void 0)&&Jn(l,i,e.scale??1,e.center),{positions:Float32Array.from(l),dim:i,n:a}}function Hc(n,e,t,r,o,s,i="subsets"){if(r!=="vertical"&&r!=="horizontal")throw ze(new Error("align must be either vertical or horizontal"),"E_BAD_OPTION",{option:"align",value:r});const a=new Float64Array(2*n).fill(Number.NaN);if(e.forEach((c,l)=>{for(let u=0;u<c.length;u++){const d=c[u];if(!Number.isInteger(d)||d<0||d>=n)throw ze(new Error(`layer node index ${String(d)} is not a node of the graph`),"E_BAD_NODE",{option:i,index:d});[a[2*d],a[2*d+1]]=t(l,e.length,u,c.length)}}),r==="vertical")return Jn(a,2,o,s);Jn(a,2,o,[s[1],s[0]]);for(let c=0;c<n;c++)[a[2*c],a[2*c+1]]=[a[2*c+1],a[2*c]];return a}const Hg=(n,e,t,r)=>[n-(e-1)/2,t-(r-1)/2];function Kg(n,e,t){const r=n.nodes.get(e);if(r===null)throw ze(new Error(`${t} names node column "${e}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:t,column:e});if(r.dtype!=="u32"&&r.dtype!=="dict")throw ze(new Error(`${t} column "${e}" must be u32 or dict, not ${r.dtype}`),"E_COLUMN_TYPE",{option:t,column:e,dtype:r.dtype,expected:["u32","dict"]});const o=r.dtype==="u32"?r.data:r.codes,s=new Map;for(let i=0;i<n.nodeCount;i++)if(r.isSet(i)){const a=s.get(o[i]);a===void 0?s.set(o[i],[i]):a.push(i)}return[...s.keys()].sort((i,a)=>i-a).map(i=>s.get(i)??[])}function K_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{subsets:i="subset",align:a="vertical"}=e,c=typeof i=="string"?Kg(n,i,"subsets"):i.map(l=>ss(n,l));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Y_(n,e){const t=n.nodeCount;if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`start node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"start",index:e});const r=new Uint8Array(t);r[e]=1;let o=1;const s=[[e]];for(let i=s[0];;){const a=[];for(const c of i)for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];r[u]===0&&(r[u]=1,a.push(u))}if(a.length===0)break;o+=a.length,s.push(a),i=a}if(o<t)throw Object.assign(new Error("bfs_layout didn't include all nodes. Graph may be disconnected."),{code:"E_NOT_CONNECTED",params:{nodeCount:t,reached:o}});return s}function X_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{start:i=0,align:a="vertical"}=e,c=t===0?[]:Y_(co(n),xe(n,i));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Q_(n,e,t,r,o,s,i){const a=r;return Hc(n,[e,t],(c,l,u,d)=>[c*a-a/2,u/d-.5],o,s,i)}function J_(n,e){const t=typeof e=="string"||e instanceof Uint32Array?e:Df(n,e);if(typeof t!="string"){if(t.length<Math.ceil(n.nodeCount/32))throw ze(new Error(`top mask has ${t.length} words; ${n.nodeCount} nodes need ${Math.ceil(n.nodeCount/32)}`),"E_BAD_OPTION",{option:"top",length:t.length,expected:Math.ceil(n.nodeCount/32)});return o=>(t[o>>>5]>>>(o&31)&1)===1}const r=n.nodes.get(t);if(r===null)throw ze(new Error(`top names node column "${t}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:"top",column:t});if(r.dtype!=="bool")throw ze(new Error(`top column "${t}" must be bool, not ${r.dtype}`),"E_COLUMN_TYPE",{option:"top",column:t,dtype:r.dtype,expected:["bool"]});return o=>r.isSet(o)&&(r.data[o>>>5]>>>(o&31)&1)===1}function Yg(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{top:i,align:a="vertical",aspectRatio:c=1.3333333333333333}=e,l=i===void 0?f=>f%2===0:J_(n,i),u=[],d=[];for(let f=0;f<t;f++)(l(f)?u:d).push(f);return Wt(Rn(Q_(t,u,d,c,a,o,s),r,s),r,t)}const ds={zeros:function(n){return typeof n=="number"?new Array(n).fill(0):n.length===1?new Array(n[0]).fill(0):new Array(n[0]).fill(0).map(()=>this.zeros(n.slice(1)))},ones:function(n){return typeof n=="number"?new Array(n).fill(1):n.length===1?new Array(n[0]).fill(1):new Array(n[0]).fill(1).map(()=>this.ones(n.slice(1)))},linspace:function(n,e,t){if(t===1)return[n];const r=(e-n)/(t-1);return Array.from({length:t},(o,s)=>n+s*r)},array:function(n){return Array.isArray(n)?[...n]:[n]},repeat:function(n,e){const t=[];for(let r=0;r<e;r++)t.push(...ds.array(n));return t},mean:function(n,e=null){if(e===null){const t=Array.isArray(n[0])?n.flat(1/0):n;return t.reduce((o,s)=>o+s,0)/t.length}if(e===0){const t=[],r=n;for(let o=0;o<r[0].length;o++){let s=0;for(let i=0;i<r.length;i++)s+=r[i][o];t.push(s/r.length)}return t}return n.map(t=>ds.mean(t))},add:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n+e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t+e[r]):n.map(t=>t+e):e.map(t=>n+t)},subtract:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n-e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t-e[r]):n.map(t=>t-e):e.map(t=>n-t)},max:function(n){return Array.isArray(n)?Math.max(...n.flat(1/0)):n},min:function(n){return Array.isArray(n)?Math.min(...n.flat(1/0)):n},norm:function(n){return Math.sqrt(n.reduce((e,t)=>e+t*t,0))}};function Z_(n,e,t,r){const o=new Float64Array(n*e);if(n===1)o.set(r);else if(e===2){const s=ds.linspace(0,2*Math.PI,n+1);for(let i=0;i<n;i++)o[2*i]=yn(s[i])*t+r[0],o[2*i+1]=Jt(s[i])*t+r[1]}else{const s=(1+Math.sqrt(5))/2;for(let i=0;i<n;i++){const a=2*Math.PI*i/s,c=Of(1-2*(i+.5)/n);o[3*i]=Jt(c)*yn(a)*t+r[0],o[3*i+1]=Jt(c)*Jt(a)*t+r[1],o[3*i+2]=yn(c)*t+r[2]}}return o}function eI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Z_(t,r,o,s),r,t)}const ut=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1}),vi=.01,tI=1e-4,Xg=1e-8,xr=256,Qg=.9,nI=5,rI=1e4;function Jg(n,e,t){if(t.meta.components!==1)throw new RangeError(`node column "${e}" has ${t.meta.components} components; a node vector has one`);switch(t.dtype){case"f32":case"f64":{const r=n.nodes.gpuView(e);return r instanceof Float32Array?r:new Float32Array(r)}case"u32":case"i32":return new Float32Array(n.nodes.gpuView(e));case"u8":return new Float32Array(t.data);default:throw new TypeError(`node column "${e}" is ${t.dtype}, not numeric`)}}function oI(n,e,t){const r=e.nodeCount;if(n==null){const s=e.nodes.byRole("mass");if(s!==null)return Jg(e,s.meta.name,s);const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=t(a);return i}if(n instanceof Float32Array){if(n.length!==r)throw new RangeError(`the node vector has ${n.length} values, expected ${r}`);return n}if(typeof n=="string"){const s=e.nodes.get(n);if(s===null)throw new RangeError(`the option names node column "${n}", which the snapshot does not hold`);return Jg(e,n,s)}const o=new Float32Array(r);for(let s=0;s<r;s++){const i=n[e.ids.idOf(s)];o[s]=i===void 0?t(s):i}return o}function Zg(n,e){if(n===!0)return e.weights;if(n===!1||n===null||n===void 0)return null;const t=e.edges.get(n);if(t===null)throw new RangeError(`weight names edge column "${n}", which the snapshot does not hold`);if(t.meta.components!==1)throw new RangeError(`edge column "${n}" has ${t.meta.components} components; a weight column has one`);switch(t.dtype){case"f32":case"f64":case"u32":case"i32":{const r=Va(e,e.edges.gpuView(n));return r instanceof Float32Array?r:new Float32Array(r)}default:throw new TypeError(`edge column "${n}" is ${t.dtype}; a weight column is f32, f64, u32 or i32`)}}function Zn(n,e,t,r,o){if(e===void 0)return t;if(typeof e!="number"||!r(e))throw new RangeError(`ForceAtlas2Simulation: ${n} must be ${o}, got ${String(e)}`);return e}function Kc(n,e,t){if(e===void 0)return t;if(typeof e!="boolean")throw new TypeError(`ForceAtlas2Simulation: ${n} must be a boolean, got ${String(e)}`);return e}function sI(n){const e=[0,0,0];if(n===void 0)return e;if(n.length>3)throw new RangeError(`ForceAtlas2Simulation: center has ${n.length} components, at most 3 expected`);for(let t=0;t<n.length;t++){const r=n[t];if(typeof r!="number"||!Number.isFinite(r))throw new RangeError(`ForceAtlas2Simulation: center[${t}] is not finite`);e[t]=r}return e}function Ai(n){return Number.isInteger(n)&&n>=1}function iI(n){const e=n??{},t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`ForceAtlas2Simulation: dim must be 2 or 3, got ${String(t)}`);const r=e.compat??"paper";if(r!=="paper"&&r!=="networkx")throw new RangeError(`ForceAtlas2Simulation: compat must be "paper" or "networkx", got ${String(r)}`);return{maxIter:Zn("maxIter",e.maxIter,ut.maxIter,Ai,"an integer >= 1"),jitterTolerance:Zn("jitterTolerance",e.jitterTolerance,ut.jitterTolerance,o=>o>0,"> 0"),scalingRatio:Zn("scalingRatio",e.scalingRatio,ut.scalingRatio,o=>o>0,"> 0"),gravity:Zn("gravity",e.gravity,ut.gravity,o=>o>=0,">= 0"),strongGravity:Kc("strongGravity",e.strongGravity,ut.strongGravity),distributedAction:Kc("distributedAction",e.distributedAction,ut.distributedAction),linlog:Kc("linlog",e.linlog,ut.linlog),nodeMass:e.nodeMass??null,weight:e.weight??null,dim:t,scale:Zn("scale",e.scale,ut.scale,o=>Number.isFinite(o)&&o>0,"a finite number > 0"),center:sI(e.center),settleThreshold:Zn("settleThreshold",e.settleThreshold,ut.settleThreshold,o=>o>=0,">= 0"),settleWindow:Zn("settleWindow",e.settleWindow,ut.settleWindow,Ai,"an integer >= 1"),iterationsPerStep:Zn("iterationsPerStep",e.iterationsPerStep,ut.iterationsPerStep,Ai,"an integer >= 1"),compat:r,seed:e.seed??null}}function Yc(n){return{attraction:new Float64Array(3*n),force:new Float64Array(3*n),swing:new Float64Array(n),traction:new Float64Array(n),sumX:new Float64Array(n),sumY:new Float64Array(n),sumZ:new Float64Array(n),sumW:new Float64Array(n),disp:new Float64Array(n),free:new Float64Array(n)}}function ew(n){for(let e=xr/2;e>0;e=Math.floor(e/2))for(let t=0;t<e;t++)n[t]=n[t]+n[t+e];return n[0]}function er(n,e){const t=Math.ceil(e/xr),r=new Float64Array(t),o=new Float64Array(xr);for(let s=0;s<t;s++){for(let i=0;i<xr;i++){const a=s*xr+i;o[i]=a<e?n[a]:0}r[s]=ew(o)}return r}function tr(n){const e=new Float64Array(xr);for(let t=0;t<n.length;t++){const r=t%xr;e[r]=e[r]+n[t]}return ew(e)}function Dn(n,e,t){return Math.sqrt(n*n+e*e+t*t)}function tw(n){let e=n>>>0;return e=(e^e>>>16)>>>0,e=Math.imul(e,2146121005)>>>0,e=(e^e>>>15)>>>0,e=Math.imul(e,2221713035)>>>0,e=(e^e>>>16)>>>0,e}function aI(n,e){const t=Math.min(n,e),r=Math.max(n,e);return tw((Math.imul(t,2654435769)>>>0^r)>>>0)}function nw(n){return(n>>>8)*5960464477539063e-23}function rw(n,e,t){const r=aI(n,e),o=6.283185307179586*nw(r);let s;if(t===2)s=[yn(o),Jt(o),0];else{const i=2*nw(tw((r^1540483477)>>>0))-1,a=Math.sqrt(Math.max(0,1-i*i));s=[a*yn(o),a*Jt(o),i]}return n>e?[-s[0],-s[1],-s[2]]:s}function cI(n,e,t,r,o,s){const i=n,a=s,c=.05*Math.sqrt(i),l=Math.sqrt(c),u=10,d=Math.max(t,1e-30),f=Math.min(u,c*t/(i*i));let h=a*Math.max(l,f),g=o;e>2*d&&(g>.05&&(g=g*.5),h=Math.max(h,a));const w=e===0?1e30:h*g*t/e;return e>h*t?g>.05&&(g=g*.7):r<1e3&&(g=g*1.3),{speed:r+Math.min(w-r,.5*r),speedEfficiency:g}}function lI(n,e,t,r){for(let o=0;o<t;o++){if(n[o]===e[o])continue;const s=Math.min(r,o*32+32);for(let i=o*32;i<s;i++)if(_e(n,i)&&!_e(e,i))return!0}return!1}class uI{constructor(e){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.weights=null,this.mass=new Float64Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.fixed=null,this.scratch=Yc(0),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.settledCountValue=0,this.iterationsDoneValue=0,this.centroid=[0,0,0],this.pending=null,this.options=iI(e),this.dim=this.options.dim,this.swingMode=this.options.compat==="networkx"?1:0,this.gravityCenter=this.options.compat==="networkx"?1:0}get settled(){return this.state!=="loaded"?!1:this.n===0||this.iterationsDoneValue>=this.options.maxIter||this.settledCountValue>=this.options.settleWindow}get iterationsDone(){return this.iterationsDoneValue}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("ForceAtlas2Simulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new Error(`ForceAtlas2Simulation: positions.length ${t.length} !== 3 x ${r}`);const o=e.outDegree(),s=oI(this.options.nodeMass,e,p=>o[p]+1),i=Zg(this.options.weight,e),a=new Float64Array(r);for(let p=0;p<r;p++)if(a[p]=s[p],!(a[p]>0))throw new Error(`ForceAtlas2Simulation: mass[${p}] must be positive`);const c=i===null?null:Float64Array.from(i);r!==this.n&&(this.fixed=null),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.mass=a,this.weights=c,this.owner=t;const{scale:l,center:u,seed:d}=this.options;bi(e,t,d,this.dim,l,u,"fa2");const[f,h,g]=u,w=new Float64Array(3*r);for(let p=0;p<r;p++)w[3*p]=(t[3*p]-f)/l,w[3*p+1]=(t[3*p+1]-h)/l,w[3*p+2]=this.dim===2?0:(t[3*p+2]-g)/l;this.positions=w,this.oldForce=new Float64Array(3*r),this.scratch=Yc(r),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.pending=null,this.writeInitialStatistics(),this.state="loaded",this.reheat()}step(e=this.options.iterationsPerStep){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed");if(this.state==="created")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)");if(!Ai(e))throw new RangeError(`ForceAtlas2Simulation: iterations must be an integer >= 1, got ${String(e)}`);if(this.settled)return;let t=0;for(;t<e&&!this.settled;)this.iterate(),this.iterationsDoneValue+=1,t+=1;this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`ForceAtlas2Simulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);const o=this.fixed,s=o!==null&&lI(o,e,r,t),i=new Uint32Array(r);i.set(e.subarray(0,r)),this.fixed=i,s&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s,owner:i}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`ForceAtlas2Simulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("ForceAtlas2Simulation: setPosition: coordinates must be finite");i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o;const{scale:a}=this.options,[c,l,u]=this.options.center;this.positions[3*e]=(i[3*e]-c)/a,this.positions[3*e+1]=(i[3*e+1]-l)/a,this.positions[3*e+2]=this.dim===2?0:(i[3*e+2]-u)/a,this.reheat()}reheat(){this.assertNotDisposed(),this.iterationsDoneValue=0,this.settledCountValue=0,this.swingMode===1&&(this.swingValue=1,this.tractionValue=1)}dispose(){this.state="disposed",this.owner=new Float32Array(0),this.scratch=Yc(0),this.pending=null,this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.mass=new Float64Array(0),this.weights=null,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null,this.n=0}assertNotDisposed(){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)")}isFixed(e){return this.fixed!==null&&_e(this.fixed,e)}writeBack(){const{n:e,owner:t,positions:r}=this,{scale:o}=this.options,[s,i,a]=this.options.center;for(let c=0;c<e;c++)this.isFixed(c)||(t[3*c]=r[3*c]*o+s,t[3*c+1]=r[3*c+1]*o+i,t[3*c+2]=this.dim===2?a:r[3*c+2]*o+a)}writeInitialStatistics(){const{n:e,positions:t}=this,r=[0,0,0];for(let o=0;o<e;o++)for(let s=0;s<3;s++)r[s]+=t[3*o+s];e===0?this.centroid=[0,0,0]:this.centroid=[r[0]/e,r[1]/e,r[2]/e],this.settledCountValue=0}foldTotals(e){return{sum:[tr(e.sumX),tr(e.sumY),tr(e.sumZ)],sumSq:tr(e.sumW),disp:tr(e.disp),free:tr(e.free)}}fold(e){const t=this.foldTotals(e),r=this.n,o=Math.sqrt(Math.max(t.sumSq,0)/r),s=t.free===0?0:t.disp/t.free;this.centroid=[t.sum[0]/r,t.sum[1]/r,t.sum[2]/r],this.settledCountValue=s<=this.options.settleThreshold*o?this.settledCountValue+1:0}iterate(){const{n:e,scratch:t}=this;this.pending!==null&&this.fold(this.pending);const{positions:r,mass:o,rowPtr:s,colIdx:i,weights:a,oldForce:c}=this,{scalingRatio:l,gravity:u,linlog:d,distributedAction:f,strongGravity:h}=this.options,{attraction:g,force:w,swing:p,traction:m,sumX:y,sumY:b,sumZ:v,sumW:A,disp:E,free:I}=t;for(let R=0;R<e;R++){let D=0,U=0,B=0;const V=r[3*R],W=r[3*R+1],q=r[3*R+2];for(let K=s[R];K<s[R+1];K++){const X=i[K];if(X===R)continue;const H=a===null?1:a[K],Y=r[3*X]-V,ee=r[3*X+1]-W,Z=r[3*X+2]-q;let J=H;if(d){const ce=Math.max(Dn(Y,ee,Z),vi);J=H*Ge(1+ce)/ce}D=D+Y*J,U=U+ee*J,B=B+Z*J}f&&(D=D/o[R],U=U/o[R],B=B/o[R]),g[3*R]=D,g[3*R+1]=U,g[3*R+2]=B}p.fill(0),m.fill(0);const k=this.centroid[0],N=this.centroid[1],C=this.centroid[2];for(let R=0;R<e;R++){const D=r[3*R],U=r[3*R+1],B=r[3*R+2],V=o[R];let W=0,q=0,K=0;for(let he=0;he<e;he++){if(he===R)continue;const ge=o[he],me=D-r[3*he],De=U-r[3*he+1],Ne=B-r[3*he+2];let He=me*me+De*De+Ne*Ne;if(He<Xg){const Ft=rw(R,he,this.dim),Nt=l*V*ge/vi;W=W+Ft[0]*Nt,q=q+Ft[1]*Nt,K=K+Ft[2]*Nt;continue}He=Math.max(He,tI);const mt=l*V*ge/He;W=W+me*mt,q=q+De*mt,K=K+Ne*mt}let X=0,H=0,Y=0;const ee=this.gravityCenter===0?D-k:D,Z=this.gravityCenter===0?U-N:U,J=this.gravityCenter===0?B-C:B,ce=-u*V;if(h)X=ce*ee,H=ce*Z,Y=ce*J;else{const he=Dn(ee,Z,J);he>vi&&(X=ce*ee/he,H=ce*Z/he,Y=ce*J/he)}W=W+X,q=q+H,K=K+Y;const de=g[3*R]+W,ne=g[3*R+1]+q,ve=g[3*R+2]+K;w[3*R]=de,w[3*R+1]=ne,w[3*R+2]=ve;const ue=c[3*R],we=c[3*R+1],Xe=c[3*R+2];this.swingMode===1?(p[R]=V*Dn(D-de,U-ne,B-ve),m[R]=.5*V*Dn(D+de,U+ne,B+ve)):this.isFixed(R)||(p[R]=V*Dn(de-ue,ne-we,ve-Xe),m[R]=.5*V*Dn(de+ue,ne+we,ve+Xe))}const O=tr(er(p,e)),T=tr(er(m,e));let $=O,L=T;this.swingMode===1&&($=this.swingValue+O,L=this.tractionValue+T);const F=cI(e,$,L,this.speedValue,this.speedEfficiencyValue,this.options.jitterTolerance);this.speedValue=F.speed,this.speedEfficiencyValue=F.speedEfficiency,this.swingValue=$,this.tractionValue=L;const M=this.speedValue;E.fill(0),I.fill(0);for(let R=0;R<e;R++){const D=w[3*R],U=w[3*R+1],B=w[3*R+2],V=o[R];let W=V*Dn(D,U,B);this.swingMode===0&&(W=V*Dn(D-c[3*R],U-c[3*R+1],B-c[3*R+2]));const q=M/(1+Math.sqrt(M*W)),K=this.isFixed(R),X=K?0:D*q,H=K?0:U*q;let Y=K?0:B*q;this.dim===2&&(Y=0);const ee=r[3*R]+X,Z=r[3*R+1]+H,J=r[3*R+2]+Y;r[3*R]=ee,r[3*R+1]=Z,r[3*R+2]=J,this.swingMode===0&&(c[3*R]=D,c[3*R+1]=U,c[3*R+2]=B);const ce=ee-k,de=Z-N,ne=J-C;y[R]=ee,b[R]=Z,v[R]=J,A[R]=ce*ce+de*de+ne*ne,K||(E[R]=Dn(X,H,Y),I[R]=1)}this.pending={sumX:er(y,e),sumY:er(b,e),sumZ:er(v,e),sumW:er(A,e),disp:er(E,e),free:er(I,e)}}}const fs=.1,dI=50,fI=.1,hI=.7;function gI(n){const e=[0,0,0];if(n===void 0)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function Ei(n,e,t,r,o){if(!Number.isFinite(e)||e<t||e>r||o&&!Number.isInteger(e))throw new RangeError(`FruchtermanReingoldSimulation: ${n} must be ${o?"an integer":"a finite number"} in [${t}, ${r}], got ${e}`);return e}class wI{constructor(e={}){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.fixed=null,this.k=0,this.dt=0,this.t=fs,this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0,this.pendingEnergy=null,this.iterationsDoneValue=0,this.settledCountValue=0,this.settledValue=!1,this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;const t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`FruchtermanReingoldSimulation: dim must be 2 or 3, got ${String(t)}`);this.dim=t;const r=e.scale??ut.scale;if(!Number.isFinite(r)||r<=0)throw new RangeError(`FruchtermanReingoldSimulation: scale must be a finite number > 0, got ${r}`);this.scale=r,this.center=gI(e.center),this.seed=e.seed??null;const o=e.k??null;if(o===null||Number.isNaN(o)||o===0)this.kOption=null;else{if(!Number.isFinite(o)||o<0)throw new RangeError(`FruchtermanReingoldSimulation: k must be null, 0 or a finite number > 0, got ${o}`);this.kOption=o}const s=e.cooling??"linear";if(s!=="linear"&&s!=="adaptive")throw new RangeError(`FruchtermanReingoldSimulation: cooling must be "linear" or "adaptive", got ${String(s)}`);this.adaptive=s==="adaptive",this.iterations=Ei("iterations",e.iterations??(this.adaptive?rI:dI),0,Number.MAX_SAFE_INTEGER,!0),this.settleThreshold=Ei("settleThreshold",e.settleThreshold??ut.settleThreshold,0,Number.POSITIVE_INFINITY,!1),this.settleWindow=Ei("settleWindow",e.settleWindow??ut.settleWindow,1,Number.MAX_SAFE_INTEGER,!0),this.iterationsPerStep=Ei("iterationsPerStep",e.iterationsPerStep??ut.iterationsPerStep,1,Number.MAX_SAFE_INTEGER,!0),this.fixedOption=e.fixed??null}get settled(){return this.settledValue}get iterationsDone(){return this.iterationsDoneValue}get settledCount(){return this.settledCountValue}get meanDisplacement(){return this.meanDisplacementValue}get rmsRadius(){return this.rmsRadiusValue}get temperature(){return this.t}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("FruchtermanReingoldSimulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new RangeError(`FruchtermanReingoldSimulation: positions has ${t.length} entries, expected ${3*r}`);const o=this.resolveFixed(e,r);r!==this.n&&(this.positions=new Float64Array(3*r),this.displacement=new Float64Array(3*r)),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.owner=t,this.fixed=o,bi(e,t,this.seed,this.dim,this.scale,this.center,"fr");const s=this.positions,[i,a,c]=this.center,{scale:l}=this;for(let u=0;u<r;u++)s[3*u]=(t[3*u]-i)/l,s[3*u+1]=(t[3*u+1]-a)/l,s[3*u+2]=this.dim===2?0:(t[3*u+2]-c)/l;this.k=this.kOption??1/Math.sqrt(r),this.dt=fs/(this.iterations+1),this.t=fs,this.resetAdaptive(),this.pendingEnergy=null,this.writeInitialStatistics(),this.iterationsDoneValue=0,this.settledCountValue=0,this.state="loaded",this.settledValue=r===0||this.computeSettled()}step(e=this.iterationsPerStep){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded");if(!Number.isInteger(e)||e<1)throw new RangeError(`FruchtermanReingoldSimulation: step(${e}): an integer >= 1 is required`);if(this.settledValue)return;let t=0;for(;t<e&&!this.settledValue;)this.iterate(),t++,this.iterationsDoneValue++,this.settledValue=this.computeSettled();this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`FruchtermanReingoldSimulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);let o=!1;const s=this.fixed;if(s!==null)for(let i=0;i<t&&!o;i++)_e(s,i)&&!_e(e,i)&&(o=!0);this.fixed=new Uint32Array(e.subarray(0,r)),o&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`FruchtermanReingoldSimulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("FruchtermanReingoldSimulation: setPosition: coordinates must be finite");const{owner:i,positions:a,scale:c}=this,[l,u,d]=this.center;i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o,a[3*e]=(t-l)/c,a[3*e+1]=(r-u)/c,a[3*e+2]=this.dim===2?0:(o-d)/c,this.reheat()}reheat(){this.assertNotDisposed(),this.settledCountValue=0,this.adaptive?(this.iterationsDoneValue=0,this.t=fs,this.resetAdaptive()):(this.iterationsDoneValue=Math.floor(hI*this.iterations),this.t=fs-this.dt*this.iterationsDoneValue),this.state==="loaded"&&(this.settledValue=this.n===0||this.computeSettled())}dispose(){this.state="disposed",this.n=0,this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.owner=new Float32Array(0),this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null}iterate(){this.adaptive&&this.pendingEnergy!==null&&this.updateAdaptive(this.pendingEnergy);const{n:e,k:t,t:r,positions:o,displacement:s,rowPtr:i,colIdx:a,fixed:c}=this;s.fill(0);for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=b+1;I<e;I++){const k=v-o[3*I],N=A-o[3*I+1],C=E-o[3*I+2],O=k*k+N*N+C*C;let T,$,L;if(O<Xg){const F=rw(b,I,this.dim),M=t*t/vi;T=F[0]*M,$=F[1]*M,L=F[2]*M}else{const F=Math.sqrt(O),M=t*t/F;T=k/F*M,$=N/F*M,L=C/F*M}s[3*b]+=T,s[3*b+1]+=$,s[3*b+2]+=L,s[3*I]-=T,s[3*I+1]-=$,s[3*I+2]-=L}}for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=i[b];I<i[b+1];I++){const k=a[I],N=v-o[3*k],C=A-o[3*k+1],O=E-o[3*k+2],T=Math.sqrt(N*N+C*C+O*O)||fI,$=T*T/t;s[3*b]-=N/T*$,s[3*b+1]-=C/T*$,s[3*b+2]-=O/T*$}}const[l,u,d]=this.centroid;let f=0,h=0,g=0,w=0,p=0,m=0,y=0;for(let b=0;b<e;b++){if(c===null||!_e(c,b)){const C=s[3*b],O=s[3*b+1],T=s[3*b+2],$=C*C+O*O+T*T,L=Math.sqrt($);y+=$;const F=Math.min(L,r);L!==0&&(o[3*b]+=C/L*F,o[3*b+1]+=O/L*F,o[3*b+2]+=T/L*F),p+=F,m++}const v=o[3*b],A=o[3*b+1],E=o[3*b+2];f+=v,h+=A,g+=E;const I=v-l,k=A-u,N=E-d;w+=I*I+k*k+N*N}this.adaptive?this.pendingEnergy=y:this.t-=this.dt,this.centroid=[f/e,h/e,g/e],this.rmsRadiusValue=Math.sqrt(Math.max(w,0)/e),this.meanDisplacementValue=m===0?0:p/m,this.settledCountValue=this.meanDisplacementValue<=this.settleThreshold*this.rmsRadiusValue?this.settledCountValue+1:0}resetAdaptive(){this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0}updateAdaptive(e){e<this.previousEnergy?(this.progress++,this.progress>=nI&&(this.progress=0,this.t/=Qg)):(this.progress=0,this.t*=Qg),this.previousEnergy=e}writeBack(){const{n:e,owner:t,positions:r,scale:o,fixed:s}=this,[i,a,c]=this.center;for(let l=0;l<e;l++)s!==null&&_e(s,l)||(t[3*l]=r[3*l]*o+i,t[3*l+1]=r[3*l+1]*o+a,t[3*l+2]=r[3*l+2]*o+c)}writeInitialStatistics(){const{n:e,positions:t}=this;if(e===0){this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;return}let r=0,o=0,s=0;for(let a=0;a<e;a++)r+=t[3*a],o+=t[3*a+1],s+=t[3*a+2];r/=e,o/=e,s/=e;let i=0;for(let a=0;a<e;a++){const c=t[3*a]-r,l=t[3*a+1]-o,u=t[3*a+2]-s;i+=c*c+l*l+u*u}this.centroid=[r,o,s],this.rmsRadiusValue=Math.sqrt(i/e),this.meanDisplacementValue=0}computeSettled(){return this.iterationsDoneValue>=this.iterations||this.settledCountValue>=this.settleWindow}resolveFixed(e,t){const r=Math.ceil(t/32),o=this.fixedOption;if(typeof o=="string"){const i=e.nodes.get(o);if(i===null)throw new RangeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which the snapshot does not hold`);if(i.dtype!=="bool")throw new TypeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which is ${i.dtype}, not bool`);return new Uint32Array(i.data.subarray(0,r))}if(o!==null){if(o.length<r)throw new RangeError(`FruchtermanReingoldSimulation: the fixed mask has ${o.length} words, ${r} needed for ${t} nodes`);return new Uint32Array(o.subarray(0,r))}const s=e.nodes.byRole("fixed");return s!==null&&s.dtype==="bool"?new Uint32Array(s.data.subarray(0,r)):t===this.n?this.fixed:null}assertNotDisposed(){if(this.state==="disposed")throw new Error("FruchtermanReingoldSimulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded")}}function pI(n,e,t,r){if(e!==null&&(!Number.isInteger(e)||e<1))throw ze(new Error("columns must be a positive integer"),"E_BAD_OPTION",{option:"columns",value:e});const o=new Float64Array(2*n);if(n===0)return o;const s=Math.min(e??Math.ceil(Math.sqrt(n)),n),i=Math.ceil(n/s),a=Math.max(s-1,i-1),c=a===0?0:2*t/a;for(let l=0;l<n;l++)o[2*l]=r[0]+(l%s-(s-1)/2)*c,o[2*l+1]=r[1]+(Math.floor(l/s)-(i-1)/2)*c;return o}function mI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(pI(t,e.columns??null,o,s),r,s),r,t)}function yI(n,e,t,r){if(e.length===0)return n.map(l=>-l);const o=n.slice(),s=new Array(e.length).fill(0),i=[];for(let l=0;l<e.length;l++){const u=e[l],d=t[l];i.push(1/d.reduce((f,h,g)=>f+h*u[g],0))}for(let l=e.length-1;l>=0;l--){const u=e[l];s[l]=i[l]*u.reduce((d,f,h)=>d+f*o[h],0);for(let d=0;d<o.length;d++)o[d]-=s[l]*t[l][d]}let a=1;if(e.length>0&&t.length>0){const l=t[t.length-1];a=e[e.length-1].reduce((d,f,h)=>d+f*l[h],0)/l.reduce((d,f)=>d+f*f,0)}const c=o.map(l=>a*l);for(let l=0;l<e.length;l++){const u=e[l],d=t[l],f=i[l]*d.reduce((h,g,w)=>h+g*c[w],0);for(let h=0;h<c.length;h++)c[h]+=u[h]*(s[l]-f)}return c.map(l=>-l)}function bI(n,e,t,r,o,s){const c=r.reduce((d,f,h)=>d+f*e[h],0);if(c>=0)return 0;let l=s;const u=20;for(let d=0;d<u;d++){const f=n.map((g,w)=>g+l*e[w]);if(o(f)<=t+1e-4*l*c)return l;l*=.5}return 0}function vI(n,e,t){const r=e.length,o=.001,s=n.map(h=>h.map(g=>g===0?0:1/g)),i=e.flat(),a=500,c=1e-5,l=10,u=[],d=[];for(let h=0;h<a;h++){const[g,w]=Xc(i,s,o,t),p=yI(w,u,d),m=bI(i,p,g,w,I=>Xc(I,s,o,t)[0],1);if(m===0){if(u.length===0)break;u.length=0,d.length=0;continue}const y=[...i];for(let I=0;I<i.length;I++)i[I]+=m*p[I];const[,b]=Xc(i,s,o,t),v=i.map((I,k)=>I-y[k]),A=b.map((I,k)=>I-w[k]);if(v.reduce((I,k,N)=>I+k*A[N],0)>1e-10&&(u.push(v),d.push(A)),u.length>l&&(u.shift(),d.shift()),Math.sqrt(b.reduce((I,k)=>I+k*k,0))<c)break}const f=[];for(let h=0;h<r;h++)f.push(i.slice(h*t,(h+1)*t));return f}function AI(n,e,t){const r=t.length;for(let o=0;o<r;o++)for(let s=o+1;s<r;s++){const i=e[o].map((u,d)=>u-e[s][d]),a=Math.sqrt(i.reduce((u,d)=>u+d*d,0)),c=t[o][s],l=a*c-1;n+=l*l}return n}function EI(n,e,t,r){const o=t.length;for(let s=0;s<o;s++)for(let i=s+1;i<o;i++){const a=e[s].map((f,h)=>f-e[i][h]),c=Math.sqrt(a.reduce((f,h)=>f+h*h,0))||1e-10,l=a.map(f=>f/c),u=t[s][i],d=c*u-1;for(let f=0;f<r;f++){const h=2*u*d*l[f];n[s*r+f]+=h,n[i*r+f]-=h}}}function Xc(n,e,t,r){const o=e.length,s=[];for(let l=0;l<o;l++)s.push(n.slice(l*r,(l+1)*r));let i=0;const a=new Array(r).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)a[u]+=s[l][u];i+=.5*t*a.reduce((l,u)=>l+u*u,0),i=AI(i,s,e);const c=new Array(n.length).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)c[l*r+u]+=t*a[u];return EI(c,s,e,r),[i,c]}const _I=1e6,II=42,kI=24;function ow(n,e){const t=kI*n*n,r=e===null?`kamadaKawai: ${n} nodes need about ${t} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`kamadaKawai: ${n} nodes exceeds maxNodes ${e}; it would allocate about ${t} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(new RangeError(r),{code:"E_TOO_LARGE",params:{nodeCount:n,maxNodes:e,bytes:t}})}function SI(n,e){let t=null;return e===!0?t=n.edges.byRole("weight"):typeof e=="string"&&(t=n.edges.get(e)),t?.dtype==="f64"&&t.meta.components===1?Va(n,t.data):Zg(e,n)}function PI(n,e){const t=n.nodeCount;let r;if(e.dist!==null&&e.dist!==void 0){if(e.dist.length!==t*t)throw ze(new RangeError(`kamadaKawai: dist has ${e.dist.length} values, expected ${t*t} (n * n)`),"E_BAD_OPTION",{option:"dist",length:e.dist.length,expected:t*t});if(t>=2&&!e.dist.some((o,s)=>Number.isFinite(o)&&s%(t+1)!==0))throw ze(new RangeError("kamadaKawai: dist has no finite distance between two different nodes; was it computed from a graph without edges?"),"E_BAD_OPTION",{option:"dist"});r=e.dist}else{const o=SI(n,e.weight??!0);let s;try{s=new Float64Array(t*t).fill(Number.POSITIVE_INFINITY)}catch(c){throw c instanceof RangeError?ow(t,null):c}const{rowPtr:i,colIdx:a}=n;for(let c=0;c<t;c++){s[c*t+c]=0;for(let l=i[c];l<i[c+1];l++){const u=o===null?1:o[l];if(!(u>=0))throw ze(new RangeError(`kamadaKawai: weights are distances and must be >= 0, got ${u}`),"E_BAD_WEIGHT",{weight:u});const d=c*t+a[l];u<s[d]&&(s[d]=u)}}for(let c=0;c<t;c++)for(let l=0;l<t;l++){const u=s[l*t+c];if(u!==Number.POSITIVE_INFINITY)for(let d=0;d<t;d++){const f=u+s[c*t+d];f<s[l*t+d]&&(s[l*t+d]=f)}}r=s}return Array.from({length:t},(o,s)=>Array.from({length:t},(i,a)=>{const c=r[s*t+a];return s===a?0:Number.isFinite(c)?c:_I}))}function xI(n,e,t){const r=n.nodeCount,{pos:o}=e;if(o!=null){if(o.length!==t*r)throw ze(new RangeError(`kamadaKawai: pos has ${o.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:o.length,expected:t*r});return Array.from({length:r},(i,a)=>Array.from(o.subarray(t*a,t*a+t),c=>Number.isNaN(c)?0:c))}if(t===2){const i=ds.linspace(0,2*Math.PI,r+1);return Array.from({length:r},(a,c)=>[yn(i[c]),Jt(i[c])])}const s=new Float64Array(3*r).fill(Number.NaN);return bi(n,s,e.seed===void 0?II:e.seed,3,1,null,"fr"),Array.from({length:r},(i,a)=>Array.from(s.subarray(3*a,3*a+3)))}function CI(n,e={}){const t=co(n),r=qg(e.dim),o=t.nodeCount;if(e.maxNodes!==void 0&&(o>e.maxNodes||Number.isNaN(e.maxNodes)))throw ow(o,e.maxNodes);if(o<=1){const a=new Float32Array(r*o);return o===1&&a.set(Array.from({length:r},(c,l)=>e.center?.[l]??0)),{positions:a,dim:r,n:o}}const s=vI(PI(t,e),xI(t,e,r),r),i=Float64Array.from(s.flat());return Jn(i,r,e.scale??1,e.center),{positions:Float32Array.from(i),dim:r,n:o}}class NI{constructor(e){this.n=e,this.cw=Array.from({length:e},()=>new Map),this.ccw=Array.from({length:e},()=>new Map),this.first=new Int32Array(e).fill(-1)}has(e,t){return this.cw[e].has(t)}addCw(e,t,r){if(r<0){this.cw[e].set(t,t),this.ccw[e].set(t,t),this.first[e]=t;return}const o=this.cw[e].get(r);if(o===void 0)throw new Error("Cannot add edge. Reference neighbor does not exist");this.cw[e].set(r,t),this.cw[e].set(t,o),this.ccw[e].set(o,t),this.ccw[e].set(t,r)}addCcw(e,t,r){if(r<0){this.addCw(e,t,-1);return}this.addCw(e,t,this.ccw[e].get(r)??-1),r===this.first[e]&&(this.first[e]=t)}addFirst(e,t){this.addCcw(e,t,this.first[e])}nextFace(e,t){return[t,this.ccw[t].get(e)??-1]}neighboursCw(e){const t=this.first[e];if(t<0)return[];const r=[t];for(let o=this.cw[e].get(t)??t;o!==t;o=this.cw[e].get(o)??t)r.push(o);return r}}const _i=(n=-1,e=-1)=>({low:n,high:e}),Ln=n=>n.low<0&&n.high<0;class TI{constructor(e){this.adj=e,this.lowpt=new Map,this.lowpt2=new Map,this.nesting=new Map,this.oriented=new Set,this.ordered=[],this.ref=new Map,this.side=new Map,this.stack=[],this.stackBottom=new Map,this.lowptEdge=new Map,this.leftRef=new Map,this.rightRef=new Map,this.roots=[],this.n=e.length,this.height=new Int32Array(this.n).fill(-1),this.parentEdge=new Float64Array(this.n).fill(-1),this.out=Array.from({length:this.n},()=>[])}key(e,t){return e*this.n+t}target(e){return e%this.n}low(e){return this.lowpt.get(e)??0}run(){const{n:e}=this,t=this.adj.reduce((s,i)=>s+i.length,0)/2;if(e>2&&t>3*e-6)return null;for(let s=0;s<e;s++)this.height[s]<0&&(this.height[s]=0,this.roots.push(s),this.orient(s));const r=s=>[...this.out[s]].sort((i,a)=>(this.nesting.get(this.key(s,i))??0)-(this.nesting.get(this.key(s,a))??0));this.ordered=Array.from({length:e},(s,i)=>r(i));for(const s of this.roots)if(!this.test(s))return null;for(const s of this.oriented)this.nesting.set(s,this.sign(s)*(this.nesting.get(s)??0));const o=new NI(e);for(let s=0;s<e;s++){this.ordered[s]=r(s);let i=-1;for(const a of this.ordered[s])o.addCw(s,a,i),i=a}for(const s of this.roots)this.embed(s,o);return o}orient(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];for(;r[s]<this.adj[s].length;){const a=this.adj[s][r[s]],c=this.key(s,a),l=this.key(a,s);if(!o.has(c)){if(this.oriented.has(c)||this.oriented.has(l)){r[s]++;continue}if(this.oriented.add(c),this.out[s].push(a),this.lowpt.set(c,this.height[s]),this.lowpt2.set(c,this.height[s]),this.height[a]<0){this.parentEdge[a]=c,this.height[a]=this.height[s]+1,t.push(s,a),o.add(c);break}this.lowpt.set(c,this.height[a])}if(this.nesting.set(c,2*this.low(c)+((this.lowpt2.get(c)??0)<this.height[s]?1:0)),i>=0){const u=this.low(i),d=this.lowpt2.get(i)??0,f=this.low(c),h=this.lowpt2.get(c)??0;f<u?(this.lowpt2.set(i,Math.min(u,h)),this.lowpt.set(i,f)):f>u?this.lowpt2.set(i,Math.min(d,f)):this.lowpt2.set(i,Math.min(d,h))}r[s]++}}}conflicting(e,t){return!Ln(e)&&this.low(e.high)>this.low(t)}lowest(e){return Ln(e.left)?this.low(e.right.low):Ln(e.right)?this.low(e.left.low):Math.min(this.low(e.left.low),this.low(e.right.low))}top(){return this.stack.length===0?null:this.stack[this.stack.length-1]}test(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];let a=!1;const c=this.ordered[s];for(;r[s]<c.length;){const l=c[r[s]],u=this.key(s,l);if(!o.has(u)){if(this.stackBottom.set(u,this.top()),u===this.parentEdge[l]){t.push(s,l),o.add(u),a=!0;break}this.lowptEdge.set(u,u),this.stack.push({left:_i(),right:_i(u,u)})}if(this.low(u)<this.height[s]){if(l===c[0])this.lowptEdge.set(i,this.lowptEdge.get(u)??-1);else if(!this.addConstraints(u,i))return!1}r[s]++}!a&&i>=0&&this.removeBackEdges(i)}return!0}addConstraints(e,t){const r={left:_i(),right:_i()};for(;;){const o=this.stack.pop();if(Ln(o.left)||([o.left,o.right]=[o.right,o.left]),!Ln(o.left))return!1;if(this.low(o.right.low)>this.low(t)?(Ln(r.right)?r.right={...o.right}:this.ref.set(r.right.low,o.right.high),r.right.low=o.right.low):this.ref.set(o.right.low,this.lowptEdge.get(t)??-1),this.top()===(this.stackBottom.get(e)??null))break}for(let o=this.top();o!==null&&(this.conflicting(o.left,e)||this.conflicting(o.right,e));o=this.top()){const s=this.stack.pop();if(this.conflicting(s.right,e)&&([s.left,s.right]=[s.right,s.left]),this.conflicting(s.right,e))return!1;this.ref.set(r.right.low,s.right.high),s.right.low>=0&&(r.right.low=s.right.low),Ln(r.left)?r.left={...s.left}:this.ref.set(r.left.low,s.left.high),r.left.low=s.left.low}return Ln(r.left)&&Ln(r.right)||this.stack.push(r),!0}removeBackEdges(e){const t=Math.floor(e/this.n),r=o=>this.ref.get(o)??-1;for(;this.stack.length>0&&this.lowest(this.top())===this.height[t];){const o=this.stack.pop();o.left.low>=0&&this.side.set(o.left.low,-1)}if(this.stack.length>0){const o=this.stack.pop();for(;o.left.high>=0&&this.target(o.left.high)===t;)o.left.high=r(o.left.high);for(o.left.high<0&&o.left.low>=0&&(this.ref.set(o.left.low,o.right.low),this.side.set(o.left.low,-1),o.left.low=-1);o.right.high>=0&&this.target(o.right.high)===t;)o.right.high=r(o.right.high);o.right.high<0&&o.right.low>=0&&(this.ref.set(o.right.low,o.left.low),this.side.set(o.right.low,-1),o.right.low=-1),this.stack.push(o)}if(this.low(e)<this.height[t]){const o=this.top(),s=o.left.high,i=o.right.high;this.ref.set(e,s>=0&&(i<0||this.low(s)>this.low(i))?s:i)}}sign(e){const t=[e],r=new Map;for(;t.length>0;){const o=t.pop()??0,s=this.ref.get(o)??-1;if(s>=0)t.push(o,s),r.set(o,s),this.ref.set(o,-1);else{const i=r.get(o)??-1;this.side.set(o,(this.side.get(o)??1)*(i>=0?this.side.get(i)??1:1))}}return this.side.get(e)??1}embed(e,t){const r=[e],o=new Int32Array(this.n);for(;r.length>0;){const s=r.pop()??0,i=this.ordered[s];for(;o[s]<i.length;){const a=i[o[s]++],c=this.key(s,a);if(c===this.parentEdge[a]){t.addFirst(a,s),this.leftRef.set(s,a),this.rightRef.set(s,a),r.push(s,a);break}(this.side.get(c)??1)===1?t.addCw(a,s,this.rightRef.get(a)??-1):(t.addCcw(a,s,this.leftRef.get(a)??-1),this.leftRef.set(a,s))}}}}function OI(n,e,t,r){const{n:o}=n;if(r.has(e*o+t))return[];r.add(e*o+t);let s=e,i=t;const a=[e],c=new Set(a);let[,l]=n.nextFace(s,i);for(;i!==e||l!==t;)c.has(i)?(n.addCw(s,l,i),n.addCcw(l,s,i),r.add(i*o+l),r.add(l*o+s),i=s):(c.add(i),a.push(i)),s=i,[i,l]=n.nextFace(i,l),r.add(s*o+i);return a}function $I(n,e,t){let[,r]=n.nextFace(e,t),[,o]=n.nextFace(t,r);if(!(e===t||e===r))for(;e!==o;)n.has(e,r)?[e,t,r]=[t,r,o]:(n.addCw(e,r,t),n.addCcw(r,e,t),[t,r]=[r,o]),[,o]=n.nextFace(t,r)}function RI(n){const{n:e}=n,t=new Uint8Array(e),r=[];for(let a=0;a<e;a++)if(t[a]!==1){r.push(a),t[a]=1;for(const c=[a];c.length>0;)for(const l of n.neighboursCw(c.pop()??0))t[l]===0&&(t[l]=1,c.push(l))}for(let a=0;a+1<r.length;a++)n.addFirst(r[a],r[a+1]),n.addFirst(r[a+1],r[a]);let o=[];const s=[],i=new Set;for(let a=0;a<e;a++){const c=n.first[a];if(c<0)continue;let l=c;do{const u=OI(n,a,l,i);u.length>0&&(s.push(u),u.length>o.length&&(o=u)),l=n.cw[a].get(l)??c}while(l!==c)}for(const a of s)a!==o&&$I(n,a[0],a[1]);return o}class DI{constructor(e,t){this.embedding=e,this.ccwNbr=new Map,this.cwNbr=new Map;const{n:r}=e;this.v1=t[0],this.v2=t[1],this.chords=new Int32Array(r),this.marked=new Uint8Array(r),this.ready=new Set(t);let o=this.v2;for(let s=2;s<t.length;s++)this.ccwNbr.set(o,t[s]),o=t[s];this.ccwNbr.set(o,this.v1),o=this.v1;for(let s=t.length-1;s>0;s--)this.cwNbr.set(o,t[s]),o=t[s];for(const s of t)this.countChords(s,null)}run(){const{n:e}=this.embedding,t=new Array(e);t[0]=[this.v1,[]],t[1]=[this.v2,[]],this.ready.delete(this.v1),this.ready.delete(this.v2);for(let r=e-1;r>1;r--){const o=this.ready.values().next().value;this.ready.delete(o),this.marked[o]=1;const[s,i]=this.contourEnds(o),a=this.replaceContour(o,s,i);a.length===2?(this.releaseChord(s),this.releaseChord(i)):this.addInner(new Set(a.slice(1,-1))),t[r]=[o,a]}return t}isOuterNbr(e,t){return this.ccwNbr.get(e)===t||this.cwNbr.get(e)===t}isOnOuter(e){return this.marked[e]===0&&(this.ccwNbr.has(e)||e===this.v1)}countChords(e,t){for(const r of this.embedding.neighboursCw(e))this.isOnOuter(r)&&!this.isOuterNbr(e,r)&&(this.chords[e]++,this.ready.delete(e),t!==null&&!t.has(r)&&(this.chords[r]++,this.ready.delete(r)))}contourEnds(e){let t=-1,r=-1;for(const o of this.embedding.neighboursCw(e))if(this.isOnOuter(o)&&(o===this.v1?t=this.v1:o===this.v2?r=this.v2:this.cwNbr.get(o)===e?t=o:r=o),t>=0&&r>=0)break;return[t,r]}replaceContour(e,t,r){const o=[t];for(let s=t;s!==r;){const i=this.embedding.ccw[e].get(s)??r;o.push(i),this.cwNbr.set(s,i),this.ccwNbr.set(i,s),s=i}return o}releaseChord(e){--this.chords[e]===0&&this.ready.add(e)}addInner(e){for(const t of e)this.ready.add(t),this.countChords(t,e)}}function LI(n,e){return new DI(n,e).run()}function MI(n){const{n:e}=n,t=new Float64Array(2*e);if(e<4){const d=[0,0,2,0,1,1];return t.set(d.slice(0,2*e)),t}const r=LI(n,RI(n)),o=new Int32Array(e).fill(-1),s=new Int32Array(e).fill(-1),i=new Float64Array(e),a=new Float64Array(e),[c,l,u]=[r[0][0],r[1][0],r[2][0]];s[c]=u,i[l]=1,i[u]=1,a[u]=1,s[u]=l;for(let d=3;d<e;d++){const[f,h]=r[d],g=h[0],w=h[1],p=h[h.length-1],m=h[h.length-2],y=h.length>2;i[w]+=1,i[p]+=1;let b=0;for(let v=1;v<h.length;v++)b+=i[h[v]];i[f]=Math.floor((-a[g]+b+a[p])/2),a[f]=Math.floor((a[g]+b+a[p])/2),i[p]=b-i[f],y&&(i[w]-=i[f]),s[g]=f,s[f]=p,y?(o[f]=w,s[m]=-1):o[f]=-1}t[2*c+1]=a[c];for(const d=[c];d.length>0;){const f=d.pop()??0;for(const h of[o[f],s[f]])h>=0&&(t[2*h]=t[2*f]+i[h],t[2*h+1]=a[h],d.push(h))}return t}function UI(n){const e=[];for(let t=0;t<n.nodeCount;t++){const r=[];for(let o=n.rowPtr[t];o<n.rowPtr[t+1];o++){const s=n.colIdx[o];s!==t&&s!==r[r.length-1]&&r.push(s)}e.push(r)}return e}function FI(n,e,t){const r=new TI(UI(n)).run();if(r===null)throw Object.assign(new Error("G is not planar."),{code:"E_NOT_PLANAR",params:{nodeCount:n.nodeCount,edgeCount:n.edgeCount}});return Jn(MI(r),2,e,t)}function BI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(FI(co(n),o,s),r,s),r,t)}function sw(n,e,t,r,o=0){const s=new Float64Array(2*n).fill(Number.NaN);if(e.length===0)return s;const i=o==="networkx"?Math.PI/e.length:o;if(!Number.isFinite(i))throw ze(new TypeError(`rotate must be a finite number of radians or "networkx", not ${String(o)}`),"E_BAD_OPTION",{option:"rotate",value:o});const a=t/e.length;let c=a;return e[0].length===1&&(s[2*e[0][0]]=r[0],s[2*e[0][0]+1]=r[1]),e.forEach((l,u)=>{if(l.length===0||u===0&&l.length===1)return;const d=ds.linspace(0,2*Math.PI,l.length+1),f=(u+1)*i;for(let h=0;h<l.length;h++)s[2*l[h]]=yn(d[h]+f)*c+r[0],s[2*l[h]+1]=Jt(d[h]+f)*c+r[1];c+=a}),s}function zI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{nlist:i}=e,a=typeof i=="string"?Kg(n,i,"nlist"):i?.map(c=>ss(n,c))??[Array.from({length:t},(c,l)=>l)];for(const c of a)for(let l=0;l<c.length;l++)if(!Number.isInteger(c[l])||c[l]<0||c[l]>=t)throw ze(new Error(`shell node index ${String(c[l])} is not a node of the graph`),"E_BAD_NODE",{option:"nlist",index:c[l]});return Wt(Rn(sw(t,a,o,s,e.rotate),r,s),r,t)}function GI(n,e){const t=new Map;for(let r=n.rowPtr[e];r<n.rowPtr[e+1];r++)t.has(n.colIdx[r])||t.set(n.colIdx[r],n.arcToEdge[r]);return[...t.keys()].sort((r,o)=>(t.get(r)??0)-(t.get(o)??0))}function WI(n,e){const t=n.nodeCount,r=new Int32Array(t).fill(-1);if(t===0)return{rings:[],parent:r};if(e===null){let a=0,c=-1;for(let l=0;l<t;l++){let u=0;for(let d=n.rowPtr[l];d<n.rowPtr[l+1];d++)(d===n.rowPtr[l]||n.colIdx[d]!==n.colIdx[d-1])&&u++;u>c&&(a=l,c=u)}e=a}else if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`root node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"root",index:e});const o=new Uint8Array(t);o[e]=1;const s=[[e]];for(let a=s[0];a.length>0;){const c=[];for(const l of a)for(const u of GI(n,l))o[u]===0&&(o[u]=1,r[u]=l,c.push(u));c.length>0&&s.push(c),a=c}const i=[];for(let a=0;a<t;a++)o[a]===0&&i.push(a);return i.length>0&&s.push(i),{rings:s,parent:r}}function VI(n,e,t,r){const o=new Float64Array(n);for(let s=r-1;s>=0;s--)for(const i of e[s])o[i]||=1,s>0&&(o[t[i]]+=o[i]);return o}function jI(n,e,t,r,o){const s=new Float64Array(2*n);if(n===0)return s;const i=e.length>1?r/(e.length-1):0,a=e.at(-1)??[],c=e.length>1&&t[a[0]]===-1?e.length-1:e.length,l=VI(n,e,t,c),u=new Float64Array(n),d=new Float64Array(n),f=new Float64Array(n);d[e[0][0]]=2*Math.PI,c>1&&e[1].length===1&&(u[e[0][0]]=Math.PI/4-Math.PI);const h=(g,w,p)=>{s[2*g]=yn(p)*w+o[0],s[2*g+1]=Jt(p)*w+o[1]};h(e[0][0],0,0);for(let g=1;g<c;g++){const w=2*Of(g/(g+1));for(const p of e[g]){const m=t[p],y=d[m]*l[p]/l[m],b=u[m]+f[m]+y/2;f[m]+=y,h(p,g*i,b),d[p]=Math.min(y,w),u[p]=b-d[p]/2}}return c<e.length&&a.forEach((g,w)=>{h(g,r,2*Math.PI*w/a.length)}),s}function qI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=e.root??null,{arrangement:a="rings",rotate:c}=e;if(a!=="rings"&&a!=="sectors")throw ze(new Error(`arrangement must be "rings" or "sectors", not ${String(a)}`),"E_BAD_OPTION",{option:"arrangement",value:a});if(a==="sectors"&&c!==void 0&&c!==0)throw ze(new Error('rotate turns each ring separately, which only arrangement: "rings" allows'),"E_BAD_OPTION",{option:"rotate",value:c});const{rings:l,parent:u}=WI(co(n),i===null?null:xe(n,i));if(a==="sectors")return Wt(Rn(jI(t,l,u,o,s),r,s),r,t);const d=l.length>1?l.length/(l.length-1):1;return Wt(Rn(sw(t,l,o*d,s,c),r,s),r,t)}class iw{constructor(e){this.seed=e??Math.floor(Math.random()*1e6),this.m=34359738337,this.a=185852,this.c=1,this._state=this.seed%this.m}_next(){return this._state=(this.a*this._state+this.c)%this.m,this._state/this.m}rand(e=null){if(e===null)return this._next();if(typeof e=="number"){const r=[];for(let o=0;o<e;o++)r.push(this._next());return r}if(e.length===1){const r=[];for(let o=0;o<e[0];o++)r.push(this._next());return r}const t=[];for(let r=0;r<e[0];r++)t.push(this.rand(e.slice(1)));return t}}function HI(n,e,t,r,o){const s=new iw(o??void 0),i=new Float64Array(n*e);for(let a=0;a<n*e;a++)i[a]=s.rand()*t+r[a%e];return i}function KI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(HI(t,r,o,s,e.seed??null),r,t)}const YI=1e-9,XI=5e3;function QI(n,e,t,r,o){const s=n.nodeCount,i=new Float64Array(s*e);if(s<=2){for(let w=0;w<s;w++){const p=w===0?-t:t;for(let m=0;m<e;m++)i[e*w+m]=s===1?r[m]:r[m]+p}return i}const{rowPtr:a,colIdx:c}=n,l=(w,p)=>c[p]!==w&&(p===a[w]||c[p]!==c[p-1]),u=new Float64Array(s);for(let w=0;w<s;w++)for(let p=a[w];p<a[w+1];p++)u[w]+=l(w,p)?1:0;const d=w=>{const p=new Float64Array(s);for(let m=0;m<s;m++){let y=u[m]*w[m];for(let b=a[m];b<a[m+1];b++)l(m,b)&&(y-=w[c[b]]);p[m]=y}return p},f=YI*2*Math.max(1,...u),h=new iw(o??void 0),g=[new Float64Array(s).fill(1/Math.sqrt(s))];for(let w=0;w<e;w++){const p=Float64Array.from({length:s},()=>h.rand()-.5),m=aw(p,g)?JI(d,p,g,f):p.fill(0);g.push(m);for(let y=0;y<s;y++)i[e*y+w]=m[y]}Jn(i,e,t);for(let w=0;w<s*e;w++)i[w]+=r[w%e];return i}function JI(n,e,t,r){let o=n(e),s=null;for(let i=0;i<XI;i++){const a=Qc(e,o),c=o.map((p,m)=>p-a*e[m]);if(Jc(c)<r)break;const l=[e];for(const p of s===null?[c]:[c,s])aw(p,[...t,...l])&&l.push(p);const u=[o,...l.slice(1).map(n)],d=l.map(p=>u.map(m=>Qc(p,m))),f=ZI(d),h=new Float64Array(e.length),g=new Float64Array(e.length),w=new Float64Array(e.length);l.forEach((p,m)=>{for(let y=0;y<e.length;y++)h[y]+=f[m]*p[y],g[y]+=f[m]*u[m][y],m>0&&(w[y]+=f[m]*p[y])}),e.set(h),o=g,s=w}return e}function ZI(n){const e=n.length,t=n.map((o,s)=>n.map((i,a)=>s===a?1:0));for(let o=0;o<50;o++)for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)ek(n,t,s,i);let r=0;for(let o=1;o<e;o++)n[o][o]<n[r][r]&&(r=o);return t.map(o=>o[r])}function ek(n,e,t,r){if(Math.abs(n[t][r])<1e-300)return;const o=(n[r][r]-n[t][t])/(2*n[t][r]),s=Math.sign(o||1)/(Math.abs(o)+Math.sqrt(o*o+1)),i=1/Math.sqrt(s*s+1),a=s*i;for(const c of[n,e])for(const l of c)[l[t],l[r]]=[i*l[t]-a*l[r],a*l[t]+i*l[r]];[n[t],n[r]]=[n[t].map((c,l)=>i*c-a*n[r][l]),n[t].map((c,l)=>a*c+i*n[r][l])]}function aw(n,e){const t=Jc(n);for(let o=0;o<2;o++)for(const s of e){const i=Qc(n,s);for(let a=0;a<n.length;a++)n[a]-=i*s[a]}const r=Jc(n);if(r<=1e-8*t)return!1;for(let o=0;o<n.length;o++)n[o]/=r;return!0}function Qc(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function Jc(n){let e=0;for(const t of n)e+=t*t;return Math.sqrt(e)}function tk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(QI(co(n),r,o,s,e.seed??null),r,t)}function nk(n,e,t,r,o){const s=new Float64Array(2*n);if(o){let c=r;c+=1/(.5*c);for(let l=0;l<n;l++){const u=.5*c;c+=1/u,s[2*l]=yn(c)*u,s[2*l+1]=Jt(c)*u}}else for(let i=0;i<n;i++)s[2*i]=yn(r*i)*i,s[2*i+1]=Jt(r*i)*i;return Jn(s,2,e,t)}function rk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=nk(t,o,s,e.resolution??.35,e.equidistant??!1);return Wt(Rn(i,r,s),r,t)}function ok(n,e,t){switch(n){case"forceatlas2":return t?.forceAtlas2!==void 0?t.forceAtlas2(e):new uI(e);case"fruchtermanReingold":case"spring":return t?.fruchtermanReingold!==void 0?t.fruchtermanReingold(e):new wI(e);case"spring-electrical":if(t?.springElectrical===void 0)throw new Error('createSimulation: "spring-electrical" has no CPU simulation; inject an accelerator that implements springElectrical');return t.springElectrical(e);default:{const r=n;throw new Error(`createSimulation: unknown simulation type ${String(r)}`)}}}const sk={animate:!1,animationDuration:500,fit:!0,padding:30,randomize:!0,refresh:1};function ik(n,e){const t=new Map;return n.nodes.forEach((o,s)=>{const i=o.data(e);if(typeof i=="number"||typeof i=="string"){const a=t.get(i);a===void 0?t.set(i,[s]):a.push(s)}}),[...t.keys()].sort((o,s)=>typeof o=="number"&&typeof s=="number"?o-s:String(o).localeCompare(String(s))).map(o=>t.get(o)??[])}const cw={random:(n,e)=>KI(n,e),circular:(n,e)=>eI(n,e),spiral:(n,e)=>rk(n,e),grid:(n,e)=>mI(n,e),spectral:(n,e)=>tk(n,e),planar:(n,e)=>BI(n,e),arf:(n,e)=>H_(n,e),"kamada-kawai":(n,e)=>CI(n,e),shell:(n,e,t)=>{const r=e.nlist;return zI(n,{...e,nlist:r?.map(o=>Gt(t,o))})},multipartite:(n,e,t)=>{const r=e.subsets??"subset",o=typeof r=="string"?ik(t,r):r.map(s=>Gt(t,s));return K_(n,{...e,subsets:o})},bipartite:(n,e,t)=>{if(e.top===void 0)return Yg(n,e);const r=At(n.nodeCount);for(const o of Gt(t,e.top))pn(r,o,!0);return Yg(n,{...e,top:r})},bfs:(n,{root:e,...t},r)=>X_(n,{...t,start:ao(r,e,"graphty layout: root")}),radial:(n,e,t)=>qI(n,{...e,root:ao(t,e.root,"graphty layout: root")})},ak={forceatlas2:{maxIter:100},fruchtermanReingold:{iterations:50}},lw={forceatlas2:"forceatlas2","fruchterman-reingold":"fruchtermanReingold","spring-electrical":"spring-electrical"},ck=[...Object.keys(cw),...Object.keys(lw)];function uw(n,e){if(n===void 0){const t=r=>Number.isFinite(r)?r:1;return{x1:0,y1:0,w:t(e.width()),h:t(e.height())}}return"w"in n?n:{x1:n.x1,y1:n.y1,w:n.x2-n.x1,h:n.y2-n.y1}}function Zc(n){return{radius:Math.max(Math.min(n.w,n.h)/2,1),center:[n.x1+n.w/2,n.y1+n.h/2,0]}}function dw(n,e,t,r){const o=new Float64Array(2*t);for(let a=0;a<t;a++)o[2*a]=n[e*a],o[2*a+1]=n[e*a+1];const{radius:s,center:i}=Zc(r);return Jn(o,2,s,i)}function lk(n,e,t,r){let o=0,s=0,i=0;for(let f=0;f<t;f++)_e(e,f)&&(o+=n[3*f],s+=n[3*f+1],i++);o/=i,s/=i;const a=o>=r.x1&&o<=r.x1+r.w&&s>=r.y1&&s<=r.y1+r.h,c=(f,h,g,w)=>h===0?1/0:((h>0?w:g)-f)/h;let l=1/0,u=0;for(let f=0;f<t;f++)if(!_e(e,f)){const h=n[3*f]-o,g=n[3*f+1]-s;l=Math.min(l,c(o,h,r.x1,r.x1+r.w),c(s,g,r.y1,r.y1+r.h)),u=Math.max(u,Math.hypot(h,g))}a?Number.isFinite(l)||(l=1):l=u>0?Zc(r).radius/u:1;const d=new Float64Array(2*t);for(let f=0;f<t;f++){const h=_e(e,f)?1:l;d[2*f]=o+h*(n[3*f]-o),d[2*f+1]=s+h*(n[3*f+1]-s)}return d}function uk(n,e){const t={};for(const r of["nodeMass","nodeSize"]){const o=e[r];if(Array.isArray(o)||ArrayBuffer.isView(o)&&!(o instanceof Float32Array))t[r]=Float32Array.from(o);else if(typeof o=="string"){const s={};n.nodes.forEach(i=>{const a=i.data(o);typeof a=="number"&&Number.isFinite(a)&&(s[i.id()]=a)}),t[r]=s}}return t}function fw(n){return(e,t)=>Number.isNaN(n[2*t])?e.position():{x:n[2*t],y:n[2*t+1]}}function hw(n,e,t){const r=fw(t);e.layoutPositions(n,n.options,r)}function gw(n){return{...n,dim:n.dim??2,scale:1,center:void 0,seed:n.seed??null,weight:n.weight!==void 0}}function ww(n){return hi(n.eles.not(":parent"),{weight:n.weight})}function pw(n,e){if((e?n.animate!==!0&&!!n.animate:!!n.animate)&&!n.cy.styleEnabled())throw new Error(`${n.name}: animate needs a core that renders; create a headless core with styleEnabled: true, or pass animate: false`)}function dk(n,e){const t=n.options;pw(t,!1);const r=ww(t),o=e(r.snapshot,gw(t),r);hw(n,r.nodes,dw(o.positions,o.dim,o.n,uw(t.boundingBox,t.cy)))}function mw(n,e){for(;!n.settled&&!e.stopped&&!e.options.cy.destroyed();){const t=n.step(50);if(t instanceof Promise)return t.then(()=>mw(n,e))}}function fk(n,e){const t=n.options;if(pw(t,!0),$c(t.name,t.gpu),n.stopped=!1,t.accelerator!==void 0){n.backend=t.accelerator===null?{ran:"cpu",reason:"accelerator: null was passed",device:null}:{ran:"gpu",reason:null,device:t.accelerator.kind},tl(n,e,t.accelerator);return}const r=t.gpu==="require"?null:xg(t.gpu);if(r!==null){n.backend=Lc(r,!1,""),Dc(r,t.eles.nodes().length),tl(n,e,null);return}n.looping=!0,Cg(t.cy,t.gpu).then(o=>{if(n.looping=!1,n.backend=Lc(o,o.gpu!==null,""),Dc(o,t.eles.nodes().length),n.stopped||t.cy.destroyed()){n.emit({type:"layoutstop",layout:n});return}tl(n,e,o.gpu?.accelerator??null)}).catch(o=>{n.looping=!1,t.cy.destroyed()||n.emit("layouterror",[o]),n.emit({type:"layoutstop",layout:n})})}const el=new WeakMap;function yw(n,e){let t=0,r=0;for(let o=0;o<e;o++)t+=n[3*o],r+=n[3*o+1];return e===0?[0,0,0]:[t/e,r/e,0]}function tl(n,e,t){const r=n.options;if(t===null&&e==="spring-electrical"){const O=n.backend?.reason??"none was available";n.backend=void 0;const T=new Error(`graphty-spring-electrical has no CPU simulation and runs only on the GPU; no GPU ran because ${O}`);bw(n,T);return}const o=ww(r),s=o.snapshot,i=s.nodeCount,a=uw(r.boundingBox,r.cy),{radius:c,center:l}=Zc(a),u=r.dim??2,d=new Float32Array(3*i),f=At(i),h=new Vg(r.seed??null);let g=!1;o.nodes.forEach((O,T)=>{const $=O.locked();g||=$,pn(f,T,$);const L=O.position(),F=$||r.randomize===!1;d[3*T]=F?L.x:a.x1+h.next()*a.w,d[3*T+1]=F?L.y:a.y1+h.next()*a.h,d[3*T+2]=F||u===2?0:(h.next()*2-1)*c});const w=r.randomize===!1&&!g?el.get(r.cy)?.get(e):void 0,p=w??c,m=ok(e,{...ak[e],...gw(r),...uk(o,r),scale:p,center:w===void 0?l:yw(d,i),iterationsPerStep:1},t);m.load(s,d),g&&m.setFixed(f);const y=bg(s),b=()=>{if(m.dispose(),y(),!g){const[O,T]=yw(d,i);let $=0;for(let L=0;L<i;L++)$=Math.max($,Math.hypot(d[3*L]-O,d[3*L+1]-T));if($>0){const L=el.get(r.cy)??new Map;L.set(e,p*c/$),el.set(r.cy,L)}}},v=()=>g?lk(d,f,i,a):dw(d,3,i,a),A=O=>{n.looping=!1,b(),r.cy.destroyed()||n.emit("layouterror",[O]),n.emit({type:"layoutstop",layout:n})};if(r.animate!==!0){const O=()=>{n.looping=!1,b(),r.cy.destroyed()?n.emit({type:"layoutstop",layout:n}):hw(n,o.nodes,v())},T=mw(m,n);T===void 0?O():(n.looping=!0,T.then(O,A));return}n.looping=!0,n.emit({type:"layoutstart",layout:n});let E=!0;const I=typeof requestAnimationFrame=="function"?requestAnimationFrame:O=>setTimeout(O,16),k=()=>{n.looping=!1,b(),r.stop!==void 0&&n.one("layoutstop",r.stop),n.emit({type:"layoutstop",layout:n})},N=()=>{if(r.cy.destroyed()){k();return}o.nodes.positions(fw(v())),r.fit!==!1&&r.cy.fit(r.eles,r.padding),E&&(E=!1,r.ready!==void 0&&n.one("layoutready",r.ready),n.emit({type:"layoutready",layout:n})),m.settled||n.stopped?k():I(C)},C=()=>{if(n.stopped||r.cy.destroyed()){N();return}let O;try{O=m.step(r.refresh??1)}catch(T){A(T);return}O instanceof Promise?O.then(N,A):N()};C()}function bw(n,e){n.looping=!0,Promise.resolve().then(()=>{n.looping=!1,n.emit("layouterror",[e]),n.emit({type:"layoutstop",layout:n})})}const vw=new WeakMap;function hk(){return this.options.cy.destroyed()?bw(this,cs()):vw.get(this)?.(this),this}function gk(){return this.looping?this.stopped=!0:this.emit({type:"layoutstop",layout:this}),this}function Aw(n,e){function t(o){this.options={...sk,...o},this.stopped=!1,this.looping=!1,vw.set(this,n)}const r={run:hk};return e&&(r.stop=gk),Object.assign(t.prototype,r),t}function wk(n){for(const[e,t]of Object.entries(cw))n("layout",`graphty-${e}`,Aw(r=>{dk(r,t)},!1));for(const[e,t]of Object.entries(lw))n("layout",`graphty-${e}`,Aw(r=>{fk(r,t)},!0))}const Ew=Symbol.for("@graphty/cytoscape-extensions");function pk(n){const e=n;e[Ew]!==!0&&(e[Ew]=!0,wk(n),R_(n),U_(n))}const _w=Object.assign(pk,{ALGORITHM_NAMES:T_,ASYNC_ALGORITHM_NAMES:O_,configureWebGpu:b_,GPU_SIZE_FLOOR:Ag,LAYOUT_NAMES:ck,toSnapshot:hi,writeData:io}),{cytoscape:Iw}=globalThis;typeof Iw=="function"&&Iw.use(_w);const nl=256,lo=65535,rl=lo*nl,Ve=4294967295,Ii=256,uo=64,ki=256,Vt=256,kw=32768,mk=3,yk=256,Sw=16*1024*1024,bk=4,vk=4*1024,Ak=64*1024*1024,Pw=16*1024*1024,xw=2,Rt=256,fo=32,jt=256,Cw=64,Cr=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),nr=Object.freeze({repulsion:"auto",exactMaxNodes:kw,nearMax:64,deterministic:!0,gridMax2D:512,gridMax3D:128,extentFactor:6,compat:"paper"}),Ek=.01,_k=1e-4,Ik=1e-8,Nw=128,ol=1,Tw=2,Si=.1,kk=.7,Sk=.9,Pk=5,xk=1e4,Ck=Object.freeze({k:null,iterations:50,fixed:null,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2,cooling:"linear"}),Nk=300,sl=Object.freeze({springLength:10,springCoefficient:.8,gravity:-12,dragCoefficient:.9,timeStep:.5,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),Ow=Object.freeze({springElectrical:.003,fruchtermanReingold:.002}),Tk=2e3,Ok=2**128-2**104,$w=8,Rw=4,Dw=1024,Lw=1e-6,Mw=1.01,$k=24,$e=32,Rk=4096,Dk=2,Lk=24,Mk=32,ho=2139095040,Uk=.25,Fk=256,Bk=2,zk=100,Gk=256,Pi=64,il=32,Wk=4096,Uw=8,Nr=4,Vk=2147483648,jk=32,al=128,cl=65e3,Fw=2,qk=32,Hk=Object.freeze({});class S extends Error{constructor(e,t,r){super(t),this.name="WebGpuGraphError",this.code=e,this.details=r===void 0?Hk:Object.freeze({...r})}}function go(n){if(typeof n!="object"||n===null)return!1;const e=n;return e.name==="WebGpuGraphError"&&typeof e.code=="string"}function xi(n,e){return go(n)&&n.code===e}const Bw=Object.freeze(["maxBufferSize","maxStorageBufferBindingSize","maxStorageBuffersPerShaderStage","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX"]),Kk=["maxTextureDimension1D","maxTextureDimension2D","maxTextureDimension3D","maxTextureArrayLayers","maxBindGroups","maxBindGroupsPlusVertexBuffers","maxBindingsPerBindGroup","maxDynamicUniformBuffersPerPipelineLayout","maxDynamicStorageBuffersPerPipelineLayout","maxSampledTexturesPerShaderStage","maxSamplersPerShaderStage","maxStorageBuffersPerShaderStage","maxStorageBuffersInVertexStage","maxStorageBuffersInFragmentStage","maxStorageTexturesPerShaderStage","maxStorageTexturesInVertexStage","maxStorageTexturesInFragmentStage","maxUniformBuffersPerShaderStage","maxUniformBufferBindingSize","maxStorageBufferBindingSize","minUniformBufferOffsetAlignment","minStorageBufferOffsetAlignment","maxVertexBuffers","maxBufferSize","maxVertexAttributes","maxVertexBufferArrayStride","maxInterStageShaderVariables","maxColorAttachments","maxColorAttachmentBytesPerSample","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeWorkgroupsPerDimension","maxImmediateSize"],zw=new WeakSet;function Gw(n){return n instanceof Error?n.message:String(n)}function Ww(n){return n.architecture==="software"||n.architecture==="swiftshader"||n.architecture==="warp"||n.isFallbackAdapter===!0}function wo(n){const{info:e}=n,t=n.limits,r={};for(const o of Kk){const s=t[o];typeof s=="number"&&(r[o]=s)}return Object.freeze({vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description,software:Ww(e),subgroupMinSize:e.subgroupMinSize??0,subgroupMaxSize:e.subgroupMaxSize??0,features:Object.freeze(Array.from(n.features).sort()),limits:Object.freeze(r)})}async function Vw(n,e){let t;try{t=await n.requestAdapter({powerPreference:e})}catch(r){const o=`requestAdapter() threw: ${Gw(r)}`;throw new S("E_NO_ADAPTER",o,{reason:o})}if(t===null){const r="requestAdapter() returned null: no usable WebGPU adapter";throw new S("E_NO_ADAPTER",r,{reason:r})}return t}function Yk(n,e){const t={};if(e==="default")return t;if(e==="raise"){for(const r of Bw)t[r]=n.limits[r];return t}for(const r of Bw){const o=e[r];if(o===void 0)continue;const s=n.limits[r];if(o>s)throw new S("E_NO_DEVICE",`requested ${r} = ${o} exceeds the adapter's ${s}`,{reason:"limit",adapter:wo(n),limit:r,requested:o,available:s});t[r]=o}return t}function Xk(n,e,t){const r=[];for(const o of e){if(!n.features.has(o))throw new S("E_NO_DEVICE",`required feature "${o}" is not supported by the adapter`,{reason:"feature",adapter:wo(n),requested:o});r.includes(o)||r.push(o)}for(const o of t)n.features.has(o)&&!r.includes(o)&&r.push(o);return r}function jw(n,e){return new S("E_NO_DEVICE",`the adapter already created a device (an adapter is consumed by one requestDevice, spec 2.2 step 1): ${e}`,{reason:"consumed",adapter:wo(n)})}async function Qk(n,e){if(zw.has(n))throw jw(n,"recorded by this package");let t;try{t=await n.requestDevice(e)}catch(r){const o=Gw(r);throw/consumed|already been used/i.test(o)?jw(n,o):new S("E_NO_DEVICE",`requestDevice() rejected: ${o}`,{reason:"requestDevice",adapter:wo(n)})}return zw.add(n),t}function Jk(n,e,t,r){const o=new Set(n.features),s=o.has("subgroups");return{limits:n.limits,features:o,wgslFeatures:new Set(r),subgroupMinSize:s?e.subgroupMinSize??0:0,subgroupMaxSize:s?e.subgroupMaxSize??0:0,software:Ww(e),runtime:t,vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description}}function qw(n,e){const t=new Set(n.features),r=t.has("subgroups");return{limits:n.limits,features:t,wgslFeatures:e?.wgslFeatures??new Set,subgroupMinSize:r?e?.subgroupMinSize??0:0,subgroupMaxSize:r?e?.subgroupMaxSize??0:0,software:e?.software??!1,runtime:e?.runtime??"unknown",vendor:e?.vendor??"",architecture:e?.architecture??"",device:e?.device??"",description:e?.description??""}}function ll(n){const e=Math.min(nl,n.limits.maxComputeInvocationsPerWorkgroup);let t=1;for(;t*2<=e;)t*=2;return t}function ul(n){const e=n.limits.maxComputeWorkgroupsPerDimension;if(e!==lo)throw new S("E_NO_DEVICE",`maxComputeWorkgroupsPerDimension is ${e}; the dispatch planner and the WGSL prelude bake ${lo}`,{reason:"maxComputeWorkgroupsPerDimension",adapter:null,requested:lo,available:e});const t=ll(n);if(t<64)throw new S("E_NO_DEVICE",`the device allows a workgroup of ${t} invocations; the kernels need a power of two >= 64`,{reason:"limit",adapter:null,limit:"maxComputeInvocationsPerWorkgroup",requested:64,available:t})}function Zk(n,e){return n.messages.map(t=>{if(t.lineNum===0)return`${t.type} ${t.message}`;const r=t.lineNum-e;return r>=1?`${t.type} ${r}:${t.linePos} ${t.message}`:`${t.type} prelude:${t.lineNum}:${t.linePos} ${t.message}`})}class eS{constructor(e,t){this.live=new Map,this.residentBytes=0,this.pending=[],this.failure=null,this.serial=0,this.device=e,this.threshold=t??Sw}createBuffer(e){this.serial+=1;const t=e.label===void 0||e.label===""?`buffer-${this.serial}`:e.label,{size:r}=e,o=r>=this.threshold;o&&this.device.pushErrorScope("out-of-memory");const s=this.device.createBuffer({...e,label:t});if(this.live.set(s,r),this.residentBytes+=r,o){const i=this.device.popErrorScope().then(a=>{a!==null&&(this.live.has(s)&&(this.live.delete(s),this.residentBytes-=r),this.failure===null&&(this.failure=new S("E_OUT_OF_MEMORY",`out of memory creating "${t}" (${r} bytes, ${this.residentBytes} resident): ${a.message}`,{requested:r,resident:this.residentBytes,label:t})))},()=>{});this.pending.push(i)}return s}destroy(e){const t=this.live.get(e);t!==void 0&&(this.live.delete(e),this.residentBytes-=t),e.destroy()}async check(){for(;this.pending.length>0;){const e=this.pending.splice(0);await Promise.all(e)}if(this.failure!==null)throw this.failure}reset(){this.failure=null}get resident(){return this.residentBytes}get liveBuffers(){return this.live.size}}class tS{constructor(){this.queue=[]}set(e){this.queue.push(e)}take(){if(this.queue.length===0)return null;const e=this.queue.splice(0);let t=null;for(let r=e.length-1;r>=0;r-=1){const o=e[r];t=t===null?o:new S(o.code,o.message,{...o.details,next:t})}return t}get pending(){return this.queue.length>0}}function nS(n,e){const{message:t}=n;return n.constructor.name==="GPUOutOfMemoryError"?new S("E_OUT_OF_MEMORY",`uncaptured out-of-memory error on "${e}": ${t}`,{requested:0,resident:0,label:e}):new S("E_VALIDATION",`uncaptured validation error on "${e}": ${t}`,{label:e,message:t})}function rS(n,e,t){let r=!0;const o=n.label??"",s=i=>{if(!r)return;const a=nS(i.error,o);t!==null?t(a):e.set(a)};return n.addEventListener("uncapturederror",s),()=>{r=!1,typeof n.removeEventListener=="function"&&n.removeEventListener("uncapturederror",s)}}function oS(n,e){let t=!1;return n.lost.then(r=>(t||(t=!0,e(r)),r))}function Hw(n){return new S("E_DEVICE_LOST",`device lost (${n.reason}): ${n.message}`,{reason:n.reason,message:n.message})}const dl=16,sS=32,Kw=new WeakMap;let Yw=1;function iS(n){let e=Kw.get(n);return e===void 0&&(e=Yw,Yw+=1,Kw.set(n,e)),e}function aS(n,e){return n.offset<e.offset+e.size&&e.offset<n.offset+n.size}class cS{constructor(e,t,r,o,s){this.cache=new Map,this.device=e,this.spec=t,this.pipeline=o,this.layouts=s,this.workgroupSize=r.overrides.WG,this.entryPoint=r.entryPoint;const i=s.map(()=>[]);for(const a of t.bindings)i[a.group].push(a);for(const a of i)a.sort((c,l)=>c.binding-l.binding);this.groups=i,this.dynamicCounts=i.map(a=>a.filter(c=>c.kind==="uniform").length)}bind(e){const{id:t}=this.spec,r=new Map(this.spec.bindings.map(d=>[d.name,d]));for(const d of Object.keys(e))if(!r.has(d))throw new S("E_INVALID_ARGUMENT",`${t}: no binding named "${d}"`,{argument:"bindings",value:d,expected:[...r.keys()].join(", ")});const o=[];for(const d of this.spec.bindings){const f=e[d.name];if(f===void 0)throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" is missing`,{argument:"bindings",value:d.name,expected:"a Binding for every declared name"});if(!(Number.isInteger(f.size)&&f.size>0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has size ${f.size}`,{argument:d.name,value:f.size,expected:"size > 0 (a zero-length buffer is never bound)"});if(!(Number.isInteger(f.offset)&&f.offset>=0&&f.offset%ki===0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has offset ${f.offset}`,{argument:d.name,value:f.offset,expected:`a multiple of ${ki} (spec 2.6: the offset alignment the package always honours)`});o.push({decl:d,binding:f})}for(let d=0;d<o.length;d++)for(let f=d+1;f<o.length;f++){const h=o[d],g=o[f];if(!(h.binding.buffer!==g.binding.buffer||!(h.decl.kind==="storage"||g.decl.kind==="storage"))){if(h.decl.kind!==g.decl.kind)throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind one buffer with different access modes (writable usage next to another usage)`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"one access mode per buffer when a slot is read_write",reason:"usage"});if(aS(h.binding,g.binding))throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind intersecting ranges of one read_write buffer`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"disjoint ranges",reason:"range"})}}const s=o.map(({binding:d})=>`${iS(d.buffer)}:${d.offset}:${d.size}`).join("|"),i=this.cache.get(s);if(i!==void 0)return this.cache.delete(s),this.cache.set(s,i),i;const a=new Map(o.map(({decl:d,binding:f})=>[d.name,f])),c=this.layouts.map((d,f)=>this.device.createBindGroup({label:`${t}/${f}`,layout:d,entries:this.groups[f].map(h=>{const g=a.get(h.name);return{binding:h.binding,resource:{buffer:g.buffer,offset:g.offset,size:g.size}}})})),l=[];this.dynamicCounts.forEach((d,f)=>{d>0&&l.push(f)});const u=Object.freeze({kernel:this,bindGroups:Object.freeze(c),dynamicGroups:Object.freeze(l)});return this.cache.set(s,u),this.cache.size>sS&&this.cache.delete(this.cache.keys().next().value),u}dispatch(e,t,r,o){this.check(t,o),r.x!==0&&(this.setUp(e,t,o),e.dispatchWorkgroups(r.x,r.y,r.z))}dispatchIndirect(e,t,r,o,s){if(this.check(t,s),!Number.isInteger(o)||o<0||(o+1)*dl>r.size)throw new S("E_INVALID_ARGUMENT",`${this.spec.id}: args slot ${o} is outside the binding`,{argument:"slot",value:o,expected:`0 <= slot < ${Math.floor(r.size/dl)}`});this.setUp(e,t,s),e.dispatchWorkgroupsIndirect(r.buffer,r.offset+dl*o)}check(e,t){const{id:r}=this.spec;if(e.kernel!==this)throw new S("E_INVALID_ARGUMENT",`${r}: the bound kernel belongs to "${e.kernel.spec.id}"`,{argument:"bound",value:e.kernel.spec.id,expected:r});if(t!==void 0&&t.length!==e.dynamicGroups.length)throw new S("E_INVALID_ARGUMENT",`${r}: ${t.length} dynamic offsets for ${e.dynamicGroups.length} dynamic groups`,{argument:"dynamicOffsets",value:t.length,expected:e.dynamicGroups.length})}setUp(e,t,r){e.setPipeline(this.pipeline);let o=0;t.bindGroups.forEach((s,i)=>{const a=this.dynamicCounts[i];if(a>0){const c=r?.[o]??0;o+=1;const l=[];for(let u=0;u<a;u++)l.push(c);e.setBindGroup(i,s,l)}else e.setBindGroup(i,s)})}invalidate(){this.cache.clear()}}const Se=Object.freeze({MAP_READ:1,MAP_WRITE:2,COPY_SRC:4,COPY_DST:8,INDEX:16,VERTEX:32,UNIFORM:64,STORAGE:128,INDIRECT:256,QUERY_RESOLVE:512}),Xw=Object.freeze({READ:1,WRITE:2}),Qw=Object.freeze({VERTEX:1,FRAGMENT:2,COMPUTE:4});function Tr(n){if(!Number.isFinite(n))throw new S("E_INVALID_ARGUMENT",`wgslF32Literal: ${n} is not a finite number`,{argument:"value",value:n,expected:"a finite number"});const e=String(n);return/[.e]/.test(e)?e:`${e}.0`}const Jw=`// ---- prelude: constants, standard overrides, helpers (every module receives this text first)
1
+ var graphtyCytoscape=(function(){"use strict";var bu=typeof document<"u"&&document.currentScript&&document.currentScript.src;function vu(n){return bu?import(new URL("cdn/"+n,bu).href):Promise.reject(new Error("graphty: the script-tag bundle loads the file formats from dist/cdn/ next to itself, but it was not loaded by a <script src> tag, so it cannot tell where that is. Load it with <script src>, or use the ES module build: <script type='module'> importing https://cdn.jsdelivr.net/npm/@graphty/cytoscape-extensions/dist/cdn/cytoscape-extensions.js"))}const x=4294967295,Te=4294967294,Mr=1,Au=Symbol.for("@graphty/graph-format/snapshot"),ft=256,Eu=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,zn=1,_u=0,la="graphty-snapshot",ua=[71,83,78,80],da=16909060,C0=Object.freeze({});class P extends Error{constructor(e,t,r){super(t),this.name="GraphFormatError",this.code=e,this.details=r===void 0?C0:Object.freeze({...r})}}const Ur=new WeakMap;function it(n){Ur.set(n,(Ur.get(n)??0)+1)}function Gn(n){Ur.set(n,Math.max(Ur.get(n)??0,1)+1)}function N0(n){return Ur.get(n)??0}function Fr(n){return(Ur.get(n)??0)>1}const T0=32;let Iu=null,ku=null;function Su(){return Iu??=new TextDecoder("utf-8",{ignoreBOM:!0}),Iu}function O0(){return ku??=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),ku}function $0(n){let e=0;const t=n.length;for(let r=0;r<t;r++){const o=n.charCodeAt(r);if(o<128)e+=1;else if(o<2048)e+=2;else if(o>=55296&&o<=56319&&r+1<t){const s=n.charCodeAt(r+1);s>=56320&&s<=57343?(e+=4,r++):e+=3}else e+=3}return e}function R0(n,e,t){let r=t;const o=n.length;for(let s=0;s<o;s++){let i=n.charCodeAt(s);if(i<128){e[r++]=i;continue}if(i<2048){e[r++]=192|i>>6,e[r++]=128|i&63;continue}if(i>=55296&&i<=57343){const a=D0(n,s,i);if(a>=0){s++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63;continue}i=65533}e[r++]=224|i>>12,e[r++]=128|i>>6&63,e[r++]=128|i&63}return r}function D0(n,e,t){if(t>56319||e+1>=n.length)return-1;const r=n.charCodeAt(e+1);return r<56320||r>57343?-1:65536+(t-55296<<10)+(r-56320)}const L0=13;function Ro(n){return n.length<L0?n:` ${n}`.slice(1)}function Pu(n){const e=n.length;for(let t=0;t<e;t++){const r=n.charCodeAt(t);if(r<55296||r>57343)continue;if(r>56319||t+1>=e)return!0;const o=n.charCodeAt(t+1);if(o<56320||o>57343)return!0;t++}return!1}function xu(n,e,t){const r=t-e;if(r===0)return"";if(r<=T0){let o="",s=e;for(;s<t;s++){const i=n[s];if(i>=128)break;o+=String.fromCharCode(i)}if(s===t)return o}return Su().decode(n.subarray(e,t))}function M0(n,e,t){for(let r=e;r<t;r++)if(n[r]>=128)return!1;return!0}function fa(n,e,t,r){const o=new Array(r-t);if(r<=t)return o;const s=e[t],i=e[r];if(M0(n,s,i)){const a=Su().decode(n.subarray(s,i));for(let c=t;c<r;c++)o[c-t]=a.substring(e[c]-s,e[c+1]-s);return o}for(let a=t;a<r;a++)o[a-t]=xu(n,e[a],e[a+1]);return o}function U0(n,e,t){let r=!0;for(let o=e;o<t;o++)if(n[o]>=128){r=!1;break}if(r)return!0;try{return O0().decode(n.subarray(e,t)),!0}catch{return!1}}function Do(n,e){const t=new Uint32Array(e+1);let r=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(r+=$0(a)),t[i+1]=r}const o=new Uint8Array(r);let s=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(s=R0(a,o,s))}return{offsets:t,utf8:o}}function ha(n,e,t,r){if(n.length!==t+1)throw new P("E_BAD_SERIALIZATION",`${r}: expected ${t+1} offsets, found ${n.length}`,{ref:r,reason:"offsets length",expected:t+1,found:n.length});let o=n[0];for(let s=1;s<=t;s++){const i=n[s];if(i<o)throw new P("E_BAD_SERIALIZATION",`${r}: offsets decrease at row ${s-1}`,{ref:r,reason:"offsets not monotonic",row:s-1});o=i}if(o>e.length)throw new P("E_BAD_SERIALIZATION",`${r}: offsets end at ${o} but the byte store has ${e.length} bytes`,{ref:r,reason:"offsets exceed utf8",end:o,byteLength:e.length})}class Wn{constructor(e,t,r){this.length=e,this.source=t,this.cache=null,this.encodedArrays=r}static fromStrings(e,t=e.length){return new Wn(t,e,null)}static fromEncoded(e,t){return new Wn(Math.max(0,e.length-1),null,{offsets:e,utf8:t})}get encoded(){return this.encodedArrays!==null}get decoded(){return this.source!==null}get detached(){return this.source===null&&this.length>0&&this.encodedArrays!==null&&this.encodedArrays.offsets.length===0}get offsets(){return this.ensureEncoded().offsets}get utf8(){return this.ensureEncoded().utf8}at(e){if(!(e>=0&&e<this.length)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`row ${e} out of range (length ${this.length})`,{index:e,size:this.length});if(this.source!==null)return this.source[e];this.cache??=new Array(this.length);const t=this.cache[e];if(t!==void 0)return t;const{offsets:r,utf8:o}=this.ensureEncoded(),s=xu(o,r[e],r[e+1]);return this.cache[e]=s,s}slice(e=0,t=this.length){const[r,o]=Cu(e,t,this.length),{source:s}=this;if(s!==null){const c=new Array(o-r);for(let l=r;l<o;l++)c[l-r]=s[l];return c}const{offsets:i,utf8:a}=this.ensureEncoded();return fa(a,i,r,o)}decodeAll(){return this.slice(0,this.length)}materialiseDecoded(){this.source===null&&(this.source=this.decodeAll(),this.cache=null)}byteLength(){const e=this.encodedArrays;return e===null?0:e.offsets.byteLength+e.utf8.byteLength}firstMalformedRow(){const e=this.encodedArrays;if(this.source!==null||e===null)return-1;const{offsets:t,utf8:r}=e;for(let o=0;o<this.length;o++)if(!U0(r,t[o],t[o+1]))return o;return-1}ensureEncoded(){let e=this.encodedArrays;return e===null&&(e=Do(this.source,this.length),this.encodedArrays=e,it(e.offsets.buffer),it(e.utf8.buffer)),e}}function Cu(n,e,t){let r=Math.trunc(n),o=Math.trunc(e);return Number.isNaN(r)&&(r=0),Number.isNaN(o)&&(o=0),r=r<0?Math.max(t+r,0):Math.min(r,t),o=o<0?Math.max(t+o,0):Math.min(o,t),[r,Math.max(r,o)]}function F0(){try{const n=new ArrayBuffer(0,{maxByteLength:64});return!n.resizable||typeof n.resize!="function"?!1:(n.resize(64),n.byteLength===64&&n.maxByteLength===64)}catch{return!1}}const ga=F0(),wa=16,B0=64,Nu=1024*1024,z0=16,G0=256*1024*1024;function Lo(n,e){const t=n%e;return t===0?n:n+e-t}function Mo(n){return Lo(n,4)}function W0(n){return Math.ceil(n/4)}function hr(n,e=ft){return Lo(n,e)}function V0(n,e=ft){const t=[],r=[];let o=0,s=0;for(const i of n){if(i===0){t.push(null),r.push(null);continue}const a=hr(o,e);s+=a-o,t.push(a),o=a+i,r.push(o)}return{offsets:t,ends:r,byteLength:o,padding:s}}function j0(n){return n.byteOffset%4===0&&n.byteLength%4===0}function pa(n){const{buffer:e}=n;return e instanceof ArrayBuffer&&!e.resizable}function Ds(n){return n.byteOffset%4===0&&n.byteOffset+Mo(n.byteLength)<=n.buffer.byteLength}function q0(n){if(!Ds(n))throw new P("E_COLUMN_ALIGNMENT",`u8 array at byteOffset ${n.byteOffset} with byteLength ${n.byteLength} has no zero-copy padded u32 view`,{byteOffset:n.byteOffset,byteLength:n.byteLength,bufferByteLength:n.buffer.byteLength});return new Uint32Array(n.buffer,n.byteOffset,W0(n.byteLength))}function H0(n){const e=new Uint8Array(new ArrayBuffer(Mo(n.byteLength)),0,n.byteLength);return e.set(n),e}function K0(n){throw new P("E_UNSUPPORTED",`unsupported dtype ${String(n)}`,{dtype:n})}function Y0(n,e){return Lo(Math.max(e,n*2,wa),wa)}function Tu(n,e){return Lo(n*e,B0)}function Ou(n,e=ga,t=Nu){if(!e)return new ArrayBuffer(n);const r=Math.max(n,t);try{return new ArrayBuffer(n,{maxByteLength:r})}catch(o){if(o instanceof RangeError&&r>n)return new ArrayBuffer(n,{maxByteLength:n});throw o}}function $u(n,e,t,r=ga){if(t<=n.length)return n;const o=e.BYTES_PER_ELEMENT,s=Tu(Y0(n.length,t),o),i=s/o,{buffer:a}=n;if(a.resizable&&n.byteOffset===0&&s<=a.maxByteLength)return a.resize(s),new e(a,0,i);const c=Math.max(a.maxByteLength*2,Math.min(a.maxByteLength*z0,G0),Nu),l=new e(Ou(s,r,c),0,i);return l.set(n),l}const ma=4294967295;function Fe(n){return Math.ceil(n/32)}function Ru(n){const e=n%32;return e===0?ma:ma>>>32-e}function ya(n,e){const t=Fe(e);t>0&&t<=n.length&&e%32!==0&&(n[t-1]&=Ru(e)),t<n.length&&n.fill(0,t)}function In(n,e=!1){const t=new Uint32Array(Fe(n));return e&&(t.fill(ma),ya(t,n)),t}function Le(n,e){return(n[e>>>5]>>>(e&31)&1)===1}function Ht(n,e){n[e>>>5]|=1<<(e&31)}function Kt(n,e){n[e>>>5]&=~(1<<(e&31))}function ba(n,e,t){t?Ht(n,e):Kt(n,e)}function Du(n){let e=n-(n>>>1&1431655765);return e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,Math.imul(e,16843009)>>>24}function gr(n,e){const t=Math.floor(e/32);let r=0;for(let o=0;o<t;o++)r+=Du(n[o]);return e%32!==0&&(r+=Du(n[t]&Ru(e))),r}function X0(n,e){const t=new Uint32Array(gr(n,e));let r=0;for(let o=0;o<e;o++)(n[o>>>5]>>>(o&31)&1)===1&&(t[r++]=o);return t}function Lu(n,e,t){const r=Math.max(0,t-e),o=In(r);if(r===0)return o;const s=e>>>5,i=e&31;if(i===0)o.set(n.subarray(s,s+o.length));else{const a=32-i;for(let c=0;c<o.length;c++){const l=s+c,u=l<n.length?n[l]>>>i:0,d=l+1<n.length?n[l+1]<<a:0;o[c]=u|d}}return ya(o,r),o}function wr(n,e){if(Pu(n))throw new P("E_COLUMN_TYPE","string value contains a lone surrogate",{...e,reason:"lone surrogate"})}function Q0(n){const e=new Map;for(let t=0;t<n.length;t++){const r=n[t];e.has(r)||e.set(r,t)}return e}class J0{constructor(e){if(this.values=[],this.codes=new Map,e!==void 0)for(const t of e)this.intern(t)}get size(){return this.values.length}intern(e){const t=this.codes.get(e);if(t!==void 0)return t;wr(e);const r=this.values.length,o=Ro(e);return this.values.push(o),this.codes.set(o,r),r}codeOf(e){const t=this.codes.get(e);return t===void 0?x:t}has(e){return this.codes.has(e)}}const Z0=["bool","i32","f64","string","json"],ey=/^-?(0|[1-9]\d*)$/,ty=/^[+-]?((0|[1-9]\d*)(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/,Mu=-2147483648,Uu=2147483647;function pr(n){return Z0.indexOf(n)}function Fu(n,e){return n===null?e:e===null?n:pr(e)>pr(n)?e:n}function ny(n){if(n==="true"||n==="false")return"bool";if(ey.test(n)){const e=Number(n);return e>=Mu&&e<=Uu?"i32":Number.isFinite(e)?"f64":"string"}return ty.test(n)&&Number.isFinite(Number(n))?"f64":"string"}function Ls(n){if(n==null)return null;switch(typeof n){case"boolean":return"bool";case"number":return Number.isInteger(n)&&n>=Mu&&n<=Uu?"i32":"f64";case"string":return"string";case"object":return"json";default:throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a column`,{reason:"unsupported value type",found:typeof n})}}function Br(n,e){switch(e){case"bool":if(typeof n=="boolean")return n;break;case"i32":case"f64":if(typeof n=="number")return n;if(typeof n=="boolean")return n?1:0;break;case"string":if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);break;case"json":return n;default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a ${e} column`,{dtype:e,found:typeof n})}function Bu(n){let e=null;for(const t of n)if(e=Fu(e,Ls(t)),e==="json")break;return e}class zu{constructor(){this.current=null}get dtype(){return this.current}observeValue(e){return this.apply(Ls(e))}observeText(e){return this.apply(ny(e))}widenTo(e){return this.apply(e)}apply(e){const t=Fu(this.current,e);return t===this.current?!1:(this.current=t,!0)}}const Gu=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),ry=new Set(["f32","f64","i32","u32","u8"]),Wu=16,Vu=256,oy=-2147483648,sy=2147483647,iy=4294967295,ay=255,cy=new TextDecoder,Ms=new WeakMap;function mr(n){return new Uint8Array(new ArrayBuffer(Mo(n)),0,n)}function ly(n){switch(n){case"f32":case"i32":case"u32":case"dict":return"direct";case"u8":case"bool":return"packed";case"f64":return"convert";case"string":case"list":case"json":return"none";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function uy(n){return n!=="list"&&Gu.has(n)}function kn(n){if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function cn(n,e,t=0){if(!(n===null||typeof n=="boolean"||typeof n=="number")){if(typeof n=="string"){wr(n,{field:e});return}if(t>Vu)throw new P("E_COLUMN_TYPE",`${e} is nested deeper than ${Vu} levels`,{field:e,reason:"nesting"});if(Array.isArray(n)){for(const r of n)cn(r,e,t+1);return}if(kn(n)){for(const r of Object.keys(n))cn(n[r],e,t+1);return}throw new P("E_COLUMN_TYPE",`${e} is not a JSON value`,{field:e,found:n===void 0?"undefined":typeof n})}}function Vn(n){if(Array.isArray(n))return n.map(e=>Vn(e));if(kn(n)){const e={};for(const t of Object.keys(n))t==="__proto__"?Object.defineProperty(e,t,{value:Vn(n[t]),enumerable:!0,writable:!0,configurable:!0}):e[t]=Vn(n[t]);return e}return n}function yr(n,e){switch(n){case"f32":case"f64":return!0;case"i32":return Number.isInteger(e)&&e>=oy&&e<=sy;case"u32":return Number.isInteger(e)&&e>=0&&e<=iy;case"u8":return Number.isInteger(e)&&e>=0&&e<=ay;default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function ju(n,e,t){if(typeof t=="number")return yr(n,t)?t:null;if(e>1&&Array.isArray(t)&&t.length===e){const r=t[0];if(typeof r!="number"||!yr(n,r))return null;for(let o=1;o<e;o++)if(!Object.is(t[o],r))return null;return r}return null}function Qe(n,e,t){return new P("E_COLUMN_TYPE",e,{...t,field:n})}function dy(n){if(n===void 0)return null;if(!kn(n))throw Qe("origin","origin must be a plain object");const e=t=>{const r=n[t];if(r==null)return null;if(typeof r!="string")throw Qe("origin",`origin.${t} must be a string or null`,{found:typeof r});return r};return{format:e("format"),id:e("id"),title:e("title"),type:e("type"),namespace:e("namespace")}}function qu(n,e,t){if(e===void 0)return 1;if(!Number.isInteger(e)||e<1||e>Wu)throw Qe(n,`${n} must be an integer in 1..${Wu}, found ${e}`,{found:e});if(e>1&&!ry.has(t))throw Qe(n,`${n} > 1 is only allowed for f32 / f64 / i32 / u32 / u8, not ${t}`,{found:e,dtype:t});return e}function fy(n,e,t,r,o,s){switch(n){case"f32":case"f64":case"i32":case"u32":case"u8":{if(t!==void 0){if(typeof t!="number")throw Qe("fill",`fill of a ${n} column must be a number`,{found:typeof t});return t}return s!==null?x:ju(n,e,r)??0}case"bool":{if(t!==void 0){if(typeof t!="boolean")throw Qe("fill","fill of a bool column must be a boolean",{found:typeof t});return t}return typeof r=="boolean"?r:!1}case"dict":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a dict column must be a string",{found:typeof t});return t}return typeof r=="string"&&(o===null||o.includes(r))?r:o!==null&&o.length>0&&typeof o[0]=="string"?o[0]:""}case"string":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a string column must be a string",{found:typeof t});return t}return""}case"list":case"json":{if(t!==void 0&&t!=="")throw Qe("fill",`a ${n} column takes no fill value`,{found:t});return""}default:{const i=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}function ht(n,e,t){const{dtype:r}=t;if(r===void 0||!Gu.has(r))throw Qe("dtype",`column "${n}" has no valid dtype`,{name:n,found:r});const o=qu("components",t.components,r);let s=null,i=null;if(r==="list"){const{itemDtype:h}=t;if(h===void 0||!uy(h))throw Qe("itemDtype",`list column "${n}" needs a scalar itemDtype`,{name:n,found:h});s=h,i=qu("itemComponents",t.itemComponents,h)}else if(t.itemDtype!==void 0||t.itemComponents!==void 0)throw Qe("itemDtype",`itemDtype / itemComponents are only allowed on list columns, not ${r}`,{name:n,dtype:r});const a=t.refersTo??null;if(a!==null){if(a!=="node"&&a!=="edge")throw Qe("refersTo",'refersTo must be "node" or "edge"',{found:a});if(!(r==="u32"&&o===1||r==="list"&&s==="u32"&&i===1))throw Qe("refersTo",`refersTo requires a u32 column or a list of u32, not ${r}`,{name:n,dtype:r})}const c=t.default;c!==void 0&&cn(c,"default");let l=null;if(t.options!==void 0){if(!Array.isArray(t.options))throw Qe("options","options must be an array");if(cn(t.options,"options"),r==="dict"){for(const h of t.options)if(typeof h!="string")throw Qe("options","options of a dict column must be strings",{found:typeof h})}l=Object.freeze(Vn([...t.options]))}const u=t.extra??{};if(!kn(u))throw Qe("extra","extra must be a plain object");cn(u,"extra");const d=t.role??null;if(d!==null&&typeof d!="string")throw Qe("role","role must be a string",{found:typeof d});const f=fy(r,o,t.fill,c,l,a);return Object.freeze({name:n,domain:e,dtype:r,components:o,itemDtype:s,itemComponents:i,nullable:t.nullable??!0,mutable:t.mutable??!1,role:d,refersTo:a,unique:t.unique??!1,default:Vn(c),fill:f,options:l,origin:dy(t.origin),dynamic:t.dynamic??!1,extra:Object.freeze(Vn({...u}))})}function Sn(n){return{name:n.name,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype??void 0,itemComponents:n.itemComponents??void 0,nullable:n.nullable,mutable:n.mutable,role:n.role??void 0,refersTo:n.refersTo??void 0,unique:n.unique,default:n.default,fill:n.fill,options:n.options??void 0,origin:n.origin??void 0,dynamic:n.dynamic,extra:n.extra}}class br{constructor(e,t,r,o,s){this.versionValue=0,this.defaultCache=null,this.dtype=e,this.meta=t,this.length=r,this.gpu=ly(e),this.validityWords=o,this.nullCountValue=s,this.defaultValue=Vn(t.default)}get validity(){return this.validityWords}get nullCount(){return this.nullCountValue}get version(){return this.versionValue}get paddedByteLength(){return this.byteLength}get validityByteLength(){return this.validityWords===null?0:this.validityWords.byteLength}get detached(){if(this.length===0)return!1;const e=this.validityWords;return e!==null&&e.length===0||this.storageDetached()}isSet(e){if(!(e>=0&&e<this.length))return!1;const t=this.validityWords;if(t===null)return!0;if(t.length===0)throw this.detachedError();return Le(t,e)}value(e){if(this.assertAttached(),!(Number.isInteger(e)&&e>=0&&e<this.length))throw new P("E_INDEX_RANGE",`row ${e} is out of range for a column of ${this.length} rows`,{row:e,length:this.length,column:this.meta.name});const t=this.validityWords;if(t!==null&&!Le(t,e)){const{defaultValue:r}=this;return r===void 0?void 0:Vn(r)}return this.readValue(e)}materializeDefault(){if(this.assertAttached(),this.meta.default===void 0)throw new P("E_NO_DEFAULT",`column "${this.meta.name}" declares no default`,{column:this.meta.name});return this.nullCountValue===0||this.fillIsDefault()?this.self():(this.defaultCache??=this.withDefaults(),this.defaultCache)}paddedU32View(){throw new P("E_GPU_INELIGIBLE",`a ${this.dtype} column has no u32 view`,{column:this.meta.name,dtype:this.dtype})}markDirty(){this.assertMutable("markDirty"),this.assertAttached(),this.versionValue++,this.defaultCache=null,Ms.delete(this);const e=this.validityWords;e!==null&&(this.nullCountValue=this.length-gr(e,this.length))}mutableValidity(){return this.assertMutable("mutableValidity"),this.validityWords}setAll(){this.assertMutable("setAll"),this.validityWords=null,this.nullCountValue=0,this.versionValue++,this.defaultCache=null}assertAttached(){if(this.detached)throw this.detachedError()}detachedError(){return new P("E_DETACHED",`column "${this.meta.name}" was transferred away`,{column:this.meta.name})}assertMutable(e){if(!this.meta.mutable)throw new P("E_COLUMN_IMMUTABLE",`${e}() on immutable column "${this.meta.name}"`,{column:this.meta.name,operation:e})}checkRange(e,t){if(this.assertAttached(),!(Number.isInteger(e)&&Number.isInteger(t)&&e>=0&&e<=t&&t<=this.length))throw new P("E_INDEX_RANGE",`row range [${e}, ${t}) is invalid for ${this.length} rows`,{start:e,end:t,length:this.length,column:this.meta.name})}sliceValidity(e,t){const r=this.validityWords;if(r===null)return{validity:null,nullCount:0};const o=t-e,s=e%32===0?zr(r.subarray(e>>>5,(e>>>5)+Fe(o))):Lu(r,e,t);return{validity:s,nullCount:o-gr(s,o)}}cloneValidity(){return this.assertAttached(),this.validityWords===null?null:this.validityWords.slice()}}function zr(n){return Gn(n.buffer),n}class Uo extends br{constructor(e,t,r,o,s,i){super(e,t,r,s,i),this.data=o}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}storageDetached(){return this.data.length===0&&this.length*this.meta.components>0}slice(e,t){this.checkRange(e,t);const{components:r}=this.meta,o=this.sliceData(e*r,t*r),{validity:s,nullCount:i}=this.sliceValidity(e,t);return this.wrap(this.meta,t-e,o,s,i)}clone(){return this.assertAttached(),this.wrap(this.meta,this.length,this.copyData(),this.cloneValidity(),this.nullCountValue)}readValue(e){const{components:t}=this.meta;return t===1?this.data[e]:this.data.subarray(e*t,(e+1)*t)}fillIsDefault(){const{fill:e,default:t,components:r}=this.meta;return typeof e!="number"?!1:ju(this.dtype,r,t)===e}withDefaults(){const{components:e,default:t}=this.meta,r=this.copyData(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||Hu(this.dtype,r,s*e,e,t,this.meta.name,s);return this.wrap(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}sliceData(e,t){return zr(this.data.subarray(e,t))}copyData(){return this.data.slice()}}function Hu(n,e,t,r,o,s,i){if(typeof o=="number"){Ku(n,o,s,i),r===1?e[t]=o:e.fill(o,t,t+r);return}if(r===1||!Yu(o,r))throw new P("E_COLUMN_TYPE",`row ${i} of ${n} column "${s}" is not ${r} number(s)`,{column:s,row:i,components:r,found:typeof o});for(let a=0;a<r;a++)Ku(n,o[a],s,i);for(let a=0;a<r;a++)e[t+a]=o[a]}function Ku(n,e,t,r){if(!yr(n,e))throw new P("E_COLUMN_TYPE",`row ${r} of ${n} column "${t}": ${e} is not representable`,{column:t,row:r,value:e})}function Yu(n,e){if(typeof n!="object"||n===null)return!1;const t=n;if(t.length!==e)return!1;for(let r=0;r<e;r++)if(typeof t[r]!="number")return!1;return!0}class va extends Uo{constructor(e,t,r,o,s){super("f32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new va(e,t,r,o,s)}}class Aa extends Uo{constructor(e,t,r,o,s){super("f64",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Aa(e,t,r,o,s)}}class Ea extends Uo{constructor(e,t,r,o,s){super("i32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Ea(e,t,r,o,s)}}class _a extends Uo{constructor(e,t,r,o,s){super("u32",e,t,r,o,s)}paddedU32View(){return this.data}self(){return this}wrap(e,t,r,o,s){return new _a(e,t,r,o,s)}}class Ia extends Uo{constructor(e,t,r,o,s){super("u8",e,t,r,o,s)}get paddedByteLength(){return Mo(this.data.byteLength)+this.validityByteLength}paddedU32View(){return q0(this.data)}self(){return this}wrap(e,t,r,o,s){return new Ia(e,t,r,o,s)}sliceData(e,t){if(e%4===0)return zr(this.data.subarray(e,t));const r=mr(t-e);return r.set(this.data.subarray(e,t)),r}copyData(){const e=mr(this.data.length);return e.set(this.data),e}}class Fo extends br{constructor(e,t,r,o,s){super("bool",e,t,o,s),this.data=r}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}paddedU32View(){return this.assertAttached(),this.data}slice(e,t){this.checkRange(e,t);const r=t-e,o=e%32===0?zr(this.data.subarray(e>>>5,(e>>>5)+Fe(r))):Lu(this.data,e,t),{validity:s,nullCount:i}=this.sliceValidity(e,t);return new Fo(this.meta,r,o,s,i)}clone(){return this.assertAttached(),new Fo(this.meta,this.length,this.data.slice(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.data.length===0}self(){return this}readValue(e){return Le(this.data,e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="boolean")throw new P("E_COLUMN_TYPE",`default of bool column "${t}" is not a boolean`,{column:t,field:"default"});const r=this.data.slice(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(e?Ht(r,s):Kt(r,s));return new Fo(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}}class Bo extends br{constructor(e,t,r,o,s,i){super("dict",e,t,s,i),this.codeMap=null,this.codes=r,this.dictionary=o}get byteLength(){return this.codes.byteLength+this.validityByteLength}codeOf(e){this.codeMap??=Q0(this.dictionary);const t=this.codeMap.get(e);return t===void 0?x:t}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.codes}paddedU32View(){return this.assertAttached(),this.codes}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Bo(this.meta,t-e,zr(this.codes.subarray(e,t)),this.dictionary,r,o)}storageDetached(){return this.codes.length===0}clone(){return this.assertAttached(),new Bo(this.meta,this.length,this.codes.slice(),[...this.dictionary],this.cloneValidity(),this.nullCountValue)}self(){return this}readValue(e){return this.dictionary[this.codes[e]]}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of dict column "${t}" is not a string`,{column:t,field:"default"});let r=this.dictionary,o=this.codeOf(e);o===x&&(o=r.length,r=[...r,e]);const s=this.codes.slice(),i=this.validityWords;if(i!==null)for(let a=0;a<this.length;a++)Le(i,a)||(s[a]=o);return new Bo(this.meta,this.length,s,r,this.cloneValidity(),this.nullCountValue)}}function hy(n){const e=Do(n,n.length),t=mr(e.utf8.length);return t.set(e.utf8),{offsets:e.offsets,utf8:t}}class ln extends br{constructor(e,t,r,o,s,i,a){super("string",e,t,i,a),this.offsetsStore=r,this.utf8Store=o,this.strings=s}get offsets(){return this.store(),this.offsetsStore}get utf8(){return this.store(),this.utf8Store}get byteLength(){return this.store(),this.offsetsStore.byteLength+this.utf8Store.byteLength+this.validityByteLength}valueAt(e){const t=this.strings?.[e];if(t!==void 0)return t;this.assertAttached(),this.store();const r=this.offsetsStore,o=this.utf8Store,s=cy.decode(o.subarray(r[e],r[e+1]));return this.strings??=new Array(this.length),this.strings[e]=s,s}decodeAll(){const e=new Array(this.length);for(let t=0;t<this.length;t++)e[t]=this.valueAt(t);return e}slice(e,t){this.checkRange(e,t);const r=t-e,{validity:o,nullCount:s}=this.sliceValidity(e,t),i=this.strings===null?null:this.strings.slice(e,t);if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,r,null,null,i,o,s);const a=this.offsetsStore[e],c=new Uint32Array(r+1);for(let u=0;u<=r;u++)c[u]=this.offsetsStore[e+u]-a;const l=zr(this.utf8Store.subarray(a,this.offsetsStore[t]));return new ln(this.meta,r,c,l,i,o,s)}clone(){this.assertAttached();const e=this.strings===null?null:[...this.strings];if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,this.length,null,null,e,this.cloneValidity(),this.nullCountValue);const t=mr(this.utf8Store.length);return t.set(this.utf8Store),new ln(this.meta,this.length,this.offsetsStore.slice(),t,e,this.cloneValidity(),this.nullCountValue)}hasStore(){return this.offsetsStore!==null}decodedCache(){return this.strings}self(){return this}storageDetached(){return this.offsetsStore!==null&&this.offsetsStore.length===0}readValue(e){return this.valueAt(e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of string column "${t}" is not a string`,{column:t,field:"default"});const r=this.decodeAll(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(r[s]=e);return new ln(this.meta,this.length,null,null,r,this.cloneValidity(),this.nullCountValue)}store(){if(this.offsetsStore!==null&&this.utf8Store!==null){this.assertAttached();return}const e=this.strings??[],t=new Array(this.length);for(let o=0;o<this.length;o++)t[o]=e[o]??"";const r=hy(t);this.offsetsStore=r.offsets,this.utf8Store=r.utf8,it(r.offsets.buffer),it(r.utf8.buffer)}}class zo extends br{constructor(e,t,r,o,s,i){super("list",e,t,s,i),this.offsets=r,this.child=o}get byteLength(){return this.offsets.byteLength+this.child.byteLength+this.validityByteLength}sliceOf(e){this.assertAttached();const t=this.offsets[e],r=this.offsets[e+1],o=new Array(r-t);for(let s=t;s<r;s++)o[s-t]=this.child.value(s);return o}slice(e,t){this.checkRange(e,t);const r=t-e,o=this.offsets[e],s=new Uint32Array(r+1);for(let c=0;c<=r;c++)s[c]=this.offsets[e+c]-o;const{validity:i,nullCount:a}=this.sliceValidity(e,t);return new zo(this.meta,r,s,this.child.slice(o,this.offsets[t]),i,a)}clone(){return this.assertAttached(),new zo(this.meta,this.length,this.offsets.slice(),this.child.clone(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.offsets.length===0||ka(this.child)}self(){return this}readValue(e){return this.sliceOf(e)}fillIsDefault(){return!1}withDefaults(){const{default:e,name:t}=this.meta;if(!Array.isArray(e))throw new P("E_COLUMN_TYPE",`default of list column "${t}" is not an array`,{column:t,field:"default"});const r=new Array(this.length),o=this.validityWords;for(let i=0;i<this.length;i++)r[i]=o!==null&&!Le(o,i)?e:this.sliceOf(i);const s=Qu(this.meta,r);return new zo(this.meta,this.length,s.offsets,s.child,this.cloneValidity(),this.nullCountValue)}}class Go extends br{constructor(e,t,r,o,s){super("json",e,t,o,s),this.values=r}get byteLength(){return this.validityByteLength}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Go(this.meta,t-e,this.values.slice(e,t),r,o)}clone(){return this.assertAttached(),new Go(this.meta,this.length,[...this.values],this.cloneValidity(),this.nullCountValue)}storageDetached(){return!1}self(){return this}readValue(e){return this.values[e]}fillIsDefault(){return!1}withDefaults(){const{default:e}=this.meta,t=[...this.values],r=this.validityWords;if(r!==null)for(let o=0;o<this.length;o++)Le(r,o)||(t[o]=e);return new Go(this.meta,this.length,t,this.cloneValidity(),this.nullCountValue)}}function gy(n){return n instanceof br}function ka(n){return n.detached}function un(n,e,t,r){return new P("E_COLUMN_LENGTH",`column "${n.name}": ${e} has length ${r}, expected ${t}`,{column:n.name,what:e,expected:t,found:r})}function dn(n,e){return new P("E_COLUMN_TYPE",`column "${n.name}": ${e}`,{column:n.name})}function Tt(n){const{meta:e,length:t}=n;if(!(Number.isInteger(t)&&t>=0))throw new P("E_COLUMN_LENGTH",`column "${e.name}": invalid row count ${t}`,{column:e.name,found:t});const{validity:r}=n;let o=null;if(r!==null){if(!e.nullable)throw dn(e,"a non-nullable column cannot carry a validity bitmap");if(!(r instanceof Uint32Array))throw dn(e,"validity must be a Uint32Array");if(r.length!==Fe(t))throw un(e,"validity",Fe(t),r.length);o=r}const s=o===null?0:t-gr(o,t),{dtype:i}=e;switch(i){case"f32":return new va(e,t,Wo(n,Float32Array),o,s);case"f64":return new Aa(e,t,Wo(n,Float64Array),o,s);case"i32":return new Ea(e,t,Wo(n,Int32Array),o,s);case"u32":return new _a(e,t,Wo(n,Uint32Array),o,s);case"u8":{const a=Wo(n,Uint8Array);if(!Ds(a))throw new P("E_COLUMN_ALIGNMENT",`column "${e.name}": no padded u32 view over the u8 data`,{column:e.name,byteOffset:a.byteOffset,byteLength:a.byteLength});return new Ia(e,t,a,o,s)}case"bool":{if(!(n.data instanceof Uint32Array))throw dn(e,"bool data must be packed Uint32Array words");if(n.data.length!==Fe(t))throw un(e,"data",Fe(t),n.data.length);return new Fo(e,t,n.data,o,s)}case"dict":{if(!(n.data instanceof Uint32Array))throw dn(e,"dict codes must be a Uint32Array");if(n.data.length!==t)throw un(e,"codes",t,n.data.length);if(n.dictionary===null)throw dn(e,"dict column needs a dictionary");return new Bo(e,t,n.data,n.dictionary,o,s)}case"string":{if(n.offsets===null||n.utf8===null){const{strings:a}=n;if(a?.length!==t)throw un(e,"strings",t,a===null?-1:a.length);for(let c=0;c<t;c++)if(typeof a[c]!="string")throw dn(e,`row ${c} is not a decoded string and no Utf8 store is present`);return new ln(e,t,null,null,a,o,s)}if(n.offsets.length!==t+1)throw un(e,"offsets",t+1,n.offsets.length);if(n.offsets[t]!==n.utf8.length)throw un(e,"utf8",n.offsets[t],n.utf8.length);return new ln(e,t,n.offsets,n.utf8,n.strings,o,s)}case"list":{if(n.offsets?.length!==t+1)throw un(e,"offsets",t+1,n.offsets===null?-1:n.offsets.length);const{child:a}=n;if(a===null||a.dtype==="list")throw dn(e,"list column needs a non-list child column");if(a.validity!==null||a.meta.nullable)throw dn(e,"list child must be non-nullable");if(a.dtype!==e.itemDtype||a.meta.components!==e.itemComponents)throw dn(e,`list child is ${a.dtype} x${a.meta.components}, declared ${String(e.itemDtype)} x${String(e.itemComponents)}`);if(n.offsets[t]!==a.length)throw un(e,"child",n.offsets[t],a.length);return new zo(e,t,n.offsets,a,o,s)}case"json":{if(n.values?.length!==t)throw un(e,"values",t,n.values===null?-1:n.values.length);return new Go(e,t,n.values,o,s)}default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}function Wo(n,e){const{meta:t,length:r}=n;if(!(n.data instanceof e))throw dn(t,`${t.dtype} data must be a ${e.name}`);const o=r*t.components;if(n.data.length!==o)throw un(t,"data",o,n.data.length);return n.data}function Us(n){const e={meta:n.meta,length:n.length,data:null,validity:n.validity,nullCount:n.nullCount,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null},{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return e.data=n.data,e;case"dict":return e.data=n.codes,e.dictionary=n.dictionary,e;case"string":return n instanceof ln?(e.strings=n.decodedCache(),n.hasStore()&&(e.offsets=n.offsets,e.utf8=n.utf8),e):(e.offsets=n.offsets,e.utf8=n.utf8,e);case"list":return e.offsets=n.offsets,e.child=n.child,e;case"json":return e.values=n.values,e;default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function Sa(n){const e=new Set,t=r=>{r!==null&&e.add(r.buffer)};switch(t(n.validity),n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":t(n.data);break;case"dict":t(n.codes);break;case"string":(!(n instanceof ln)||n.hasStore())&&(t(n.offsets),t(n.utf8));break;case"list":t(n.offsets);for(const r of Sa(n.child))e.add(r);break;case"json":break;default:{const r=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${r.dtype}`,{})}}return[...e]}function Xu(n,e){const t=n.meta;if(e.dtype!==t.dtype||e.components!==t.components||e.itemDtype!==t.itemDtype||e.itemComponents!==t.itemComponents)throw new P("E_COLUMN_TYPE",`column "${t.name}" is ${t.dtype} x${t.components}; a patch cannot change its dtype`,{column:t.name,field:"dtype"});if(e.fill!==t.fill)throw new P("E_COLUMN_TYPE",`the fill of existing column "${t.name}" cannot change`,{column:t.name,field:"fill"});const r=Us(n);if(!e.nullable&&n.validity!==null){if(n.nullCount>0)throw new P("E_COLUMN_TYPE",`column "${t.name}" has ${n.nullCount} unset rows and cannot become non-nullable`,{column:t.name,field:"nullable",nullCount:n.nullCount});r.validity=null}return r.meta=e,Tt(r)}function wy(n){Ms.delete(n)}function py(n){const{dtype:e}=n;switch(e){case"f32":case"i32":case"u32":case"bool":return n.data;case"u8":return n.paddedU32View();case"dict":return n.codes;case"f64":{let t=Ms.get(n);return t===void 0&&(t=new Float32Array(n.data),Ms.set(n,t)),t}case"string":case"list":case"json":throw new P("E_GPU_INELIGIBLE",`a ${e} column cannot be bound by the GPU`,{column:n.meta.name,dtype:e});default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function my(n,e,t){const r=typeof e=="string"?e:"",o=n.codeOf(r);return o===x?0:o}function Pa(n){const e=new J0(n.options===null?void 0:n.options);return typeof n.fill=="string"&&n.fill!==""&&e.intern(n.fill),e}function Gr(n,e,t){return{meta:n,length:e,data:null,validity:t,nullCount:t===null?0:e,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null}}function yy(n){if(n.itemDtype===null||n.itemComponents===null)throw new P("E_COLUMN_TYPE",`column "${n.name}" is not a list`,{column:n.name,field:"itemDtype"});return ht(`${n.name}.item`,n.domain,{dtype:n.itemDtype,components:n.itemComponents,nullable:!1,refersTo:n.refersTo??void 0})}function by(n,e){return n===void 0||n===null&&e!=="json"}function Qu(n,e){const t=new Uint32Array(e.length+1),r=[];for(let s=0;s<e.length;s++){for(const i of e[s])r.push(i);t[s+1]=r.length}const o=Vo(yy(n),r);return{offsets:t,child:o}}function Vo(n,e){const{length:t}=e,{dtype:r,components:o,fill:s,name:i}=n;let a=null,c=0;for(let d=0;d<t;d++)if(by(e[d],r)){if(!n.nullable)throw new P("E_COLUMN_TYPE",`row ${d} of non-nullable column "${i}" is unset`,{column:i,row:d});a??=In(t,!0),Kt(a,d),c++}const l=Gr(n,t,a);l.nullCount=c;const u=d=>a===null||Le(a,d);switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const d=Ju(r,t*o);s!==0&&d.fill(s);for(let f=0;f<t;f++){if(!u(f))continue;const h=e[f],g=typeof h=="boolean"?Number(h):h;Hu(r,d,f*o,o,g,i,f)}l.data=d;break}case"bool":{const d=In(t,s===!0);for(let f=0;f<t;f++){if(!u(f))continue;Br(e[f],"bool")===!0?Ht(d,f):Kt(d,f)}l.data=d;break}case"dict":{const d=Pa(n),f=new Uint32Array(t);a!==null&&f.fill(my(d,s));for(let h=0;h<t;h++){if(!u(h))continue;const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of dict column "${i}" is not a string`,{column:i,row:h});f[h]=d.intern(g)}l.data=f,l.dictionary=d.values;break}case"string":{const d=typeof s=="string"?s:"",f=new Array(t);for(let h=0;h<t;h++){if(!u(h)){f[h]=d;continue}const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of string column "${i}" is not a string`,{column:i,row:h});wr(g,{column:i,row:h}),f[h]=g}l.strings=f;break}case"list":{const d=new Array(t);for(let h=0;h<t;h++){if(!u(h)){d[h]=[];continue}const g=e[h];if(!Array.isArray(g))throw new P("E_COLUMN_TYPE",`row ${h} of list column "${i}" is not an array`,{column:i,row:h});d[h]=g}const f=Qu(n,d);l.offsets=f.offsets,l.child=f.child;break}case"json":{const d=new Array(t);for(let f=0;f<t;f++){if(!u(f)){d[f]=void 0;continue}cn(e[f],`row ${f}`),d[f]=e[f]}l.values=d;break}default:{const d=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${d}`,{dtype:d})}}return Tt(l)}function Ju(n,e){switch(n){case"f32":return new Float32Array(e);case"f64":return new Float64Array(e);case"i32":return new Int32Array(e);case"u32":return new Uint32Array(e);case"u8":return mr(e);default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function vy(n){let e=!1,t=!1;for(const r of n)r!=null&&(Array.isArray(r)?e=!0:t=!0);return e&&!t?{dtype:"list",itemDtype:Bu(Ay(n))??"json"}:{dtype:Bu(n)??"json",itemDtype:void 0}}function Ay(n){const e=[];for(const t of n)if(Array.isArray(t))for(const r of t)e.push(r);return e}function xa(n,e,t,r,o){if(r.length!==e)throw new P("E_COLUMN_LENGTH",`column "${t}": ${r.length} values for ${e} rows`,{column:t,expected:e,found:r.length});let s={nullable:!0,...o};if(s.dtype===void 0){const a=vy(r);s={...s,dtype:a.dtype},a.dtype==="list"&&s.itemDtype===void 0&&(s={...s,itemDtype:a.itemDtype})}const i=ht(t,n,s);return Vo(i,r)}function Zu(n){return n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":n instanceof Int32Array?"i32":n instanceof Uint32Array?"u32":"u8"}function Ey(n,e,t,r,o,s="copy"){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=ht(t,n,{nullable:!1,...o,dtype:a}),u=Gr(l,e,null),d=_y(t,a,e,l.components);if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});if(!pa(r)){const h=r.buffer instanceof ArrayBuffer?"resizable ArrayBuffer":"SharedArrayBuffer";throw new P("E_UNSUPPORTED",`column "${t}": a view over a ${h} cannot be adopted`,{column:t,reason:h})}let f=r;if(r instanceof Uint8Array&&!Ds(r)){if(s==="strict")throw new P("E_COLUMN_ALIGNMENT",`column "${t}": no zero-copy padded u32 view over the u8 array`,{column:t,byteOffset:r.byteOffset,byteLength:r.byteLength,bufferByteLength:r.buffer.byteLength});const h=mr(r.length);h.set(r),f=h}return u.data=f,a==="dict"&&(u.dictionary=Iy(l,r,e)),Tt(u)}function _y(n,e,t,r){switch(e){case"bool":return Fe(t);case"dict":return t;case"f32":case"f64":case"i32":case"u32":case"u8":return t*r;default:{const o=e;throw new P("E_COLUMN_TYPE",`column "${n}": a ${o} column cannot adopt a typed array`,{column:n,field:"dtype"})}}}function Iy(n,e,t){const{name:r}=n,o=Pa(n);for(let s=0;s<t;s++){const i=e[s];if(i>=o.size)throw new P("E_COLUMN_TYPE",`column "${r}": code ${i} at row ${s} is outside the ${o.size} declared options`,{column:r,row:s,code:i})}return o.values}function zt(n,e,t){if(e!==void 0){if(typeof e!="string"||!t.includes(e))throw new P("E_UNSUPPORTED",`option ${n} has an unsupported value ${ky(e)}`,{field:n,found:e,reason:"unsupported option"});return e}}function ky(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):`a ${typeof n}`}const Fs=["first","last","sum","min","max"],Sy=[...Fs,"mean","count","drop"];function Pn(n){if(typeof n=="number")return String(n);if(typeof n=="string"){const e=n.length>40?`${n.slice(0,37)}...`:n;return JSON.stringify(e)}return n===null?"null":typeof n=="bigint"?`${String(n)}n`:`a value of type ${typeof n}`}function jn(n){if(typeof n=="number"){if(!Number.isFinite(n))throw new P("E_INVALID_ID",`invalid node id ${String(n)}: not a finite number`,{id:n,reason:"non-finite"});return n===0?0:n}if(typeof n=="string"){if(Pu(n))throw new P("E_INVALID_ID",`invalid node id ${Pn(n)}: lone surrogate`,{id:n,reason:"lone surrogate"});return n}throw new P("E_INVALID_ID",`invalid node id: ${Pn(n)} is not a string or a number`,{reason:"unsupported type",type:typeof n})}const Bs=new WeakMap;function Py(n){const e=Bs.get(n);if(e===void 0)throw new P("E_UNSUPPORTED","not a NodeIdMap of this package",{reason:"foreign id map"});return e}function fn(n,e,t={}){return{kind:n,size:e,offset:0,denseValues:null,denseInverse:null,decoded:null,numbers:null,tags:null,strings:null,map:null,stringIndex:null,...t}}function ed(n){return n.size===0?!1:n.denseValues!==null&&n.denseValues.length===0||n.decoded===null&&n.numbers!==null&&n.numbers.length===0||n.decoded===null&&n.tags!==null&&n.tags.length===0||n.decoded===null&&n.strings?.detached===!0}function xy(n){const e=Bs.get(n);return e!==void 0&&ed(e)}function jo(n){return n===0?0:n}function Ca(n,e,t){return new P("E_DUPLICATE_ID",`duplicate node id ${Pn(n)} at indices ${e} and ${t}`,{id:n,indices:[e,t]})}function Wr(n,e){return new P("E_INVALID_SNAPSHOT",`id map violates invariant I11: ${n}`,{invariant:"I11",reason:n,...e})}function hn(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function td(n,e,t){const r=new Uint32Array(e+1).fill(x);for(let o=0;o<n.length;o++){const s=n[o];if(r[s]!==x)throw t(s,r[s],o);r[s]=o}return r}function qo(n,e,t){const r=new Map;for(let o=0;o<e;o++){const s=n[o],i=r.get(s);if(i!==void 0)throw t(s,i,o);r.set(s,o)}return r}function Cy(n,e){let t=!0,r=!0,o=!0,s=-1,i=0,a=!0;if(e>0){const c=n[0];typeof c=="number"&&Number.isSafeInteger(c)?i=c:a=!1}for(let c=0;c<e;c++){const l=n[c];typeof l=="number"?(r=!1,a&&l!==c+i&&(a=!1),o&&(Number.isInteger(l)&&l>=0&&l<Te?l>s&&(s=l):o=!1)):(t=!1,a=!1,o=!1)}return t||(s=-1),{allNumbers:t,allStrings:r,identity:a,offset:i,allDenseIntegers:o,maxId:s}}function Ny(n,e){return e===0||n.identity?"identity":n.allDenseIntegers&&n.maxId+1<=2*e?"dense":n.allNumbers?"numeric":n.allStrings?"string":"mixed"}function Ty(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++){const o=n[r];t[r]=typeof o=="number"?o:x}return t}class Yt{constructor(e){this.kind=e.kind,this.size=e.size,this.offset=e.kind==="identity"?e.offset:0,this.storage=e,Bs.set(this,e),Object.freeze(this)}idOf(e){if(!(e>=0&&e<this.size)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`node index ${e} out of range (size ${this.size})`,{index:e,size:this.size});return this.idAt(e)}indexOf(e){const{storage:t}=this;switch(t.kind){case"identity":{if(typeof e!="number")return x;const r=e-t.offset;return!Number.isInteger(r)||r<0||r>=t.size?x:r===0?0:r}case"dense":{const r=t.denseInverse;return typeof e!="number"||!Number.isInteger(e)||e<0||e>=r.length?x:r[e]}case"numeric":case"string":case"mixed":{const r=this.reverseMap().get(e);return r===void 0||r>=t.size?x:r}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}has(e){return this.indexOf(e)!==x}requireIndex(e){const t=this.indexOf(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return t}indicesOf(e,t="invalid"){zt("onMissing",t,["invalid","throw"]);const r=t==="throw"?i=>this.requireIndex(i):i=>this.indexOf(i);if(Array.isArray(e)){const i=e,a=new Uint32Array(i.length);for(let c=0;c<i.length;c++)a[c]=r(i[c]);return a}let o=new Uint32Array(16),s=0;for(const i of e){if(s===o.length){const a=new Uint32Array(o.length*2);a.set(o),o=a}o[s++]=r(i)}return o.slice(0,s)}idsSlice(e=0,t=this.size){const[r,o]=Cu(e,t,this.size),{storage:s}=this;switch(this.assertAttached(),s.kind){case"identity":{const i=new Array(o-r);for(let a=r;a<o;a++)i[a-r]=a+s.offset;return i}case"dense":return Array.from(s.denseValues.subarray(r,o));case"numeric":return s.decoded!==null?s.decoded.slice(r,o):Array.from(s.numbers.subarray(r,o),jo);case"string":return s.strings.slice(r,o);case"mixed":{if(s.decoded!==null)return s.decoded.slice(r,o);const i=s.tags,a=s.numbers,c=s.strings,l=new Array(o-r);for(let u=r;u<o;u++)l[u-r]=i[u]===0?jo(a[u]):c.at(u);return l}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(s.kind)}`,{kind:s.kind})}}toArray(){return this.idsSlice(0,this.size)}*[Symbol.iterator](){for(let e=0;e<this.size;e++)yield this.idAt(e)}toMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(this.idAt(r),e[r]);return t}toStringMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(String(this.idAt(r)),e[r]);return t}toRecord(e){const t=Object.create(null);for(let r=0;r<this.size;r++)t[String(this.idAt(r))]=e[r];return t}*entries(e){for(let t=0;t<this.size;t++)yield[this.idAt(t),e[t]]}stringIndex(){const{storage:e}=this;if(e.stringIndex===null){const t=new Map;for(let r=0;r<e.size;r++){const o=this.idAt(r),s=String(o);(typeof o=="string"||!t.has(s))&&t.set(s,r)}e.stringIndex=t}return e.stringIndex}byteLength(){const{storage:e}=this;let t=0;return e.denseValues!==null&&(t+=e.denseValues.byteLength),e.denseInverse!==null&&(t+=e.denseInverse.byteLength),e.numbers!==null&&(t+=e.numbers.byteLength),e.tags!==null&&(t+=e.tags.byteLength),e.strings!==null&&(t+=e.strings.byteLength()),t}idAt(e){const{storage:t}=this;switch(this.assertAttached(),t.kind){case"identity":return e+t.offset;case"dense":return t.denseValues[e];case"numeric":return t.decoded!==null?t.decoded[e]:jo(t.numbers[e]);case"string":return t.strings.at(e);case"mixed":return t.decoded!==null?t.decoded[e]:t.tags[e]===0?jo(t.numbers[e]):t.strings.at(e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}assertAttached(){if(ed(this.storage))throw new P("E_DETACHED","the id map's storage was transferred away",{kind:this.storage.kind})}reverseMap(){const{storage:e}=this;if(e.map===null){this.assertAttached(),e.decoded===null&&e.strings!==null&&e.strings.materialiseDecoded();const t=new Map;for(let r=0;r<e.size;r++)t.set(this.idAt(r),r);e.map=t}return e.map}}function nd(n,e=0){if(!Number.isInteger(n)||n<0||n>Te)throw new P("E_TOO_LARGE",`node count ${n} is not an integer in [0, MAX_COUNT]`,{count:n,max:Te});if(!Number.isSafeInteger(e))throw new P("E_INVALID_ID",`identity offset ${e} is not a safe integer`,{offset:e,reason:"non-integer offset"});return new Yt(fn("identity",n,{offset:e}))}function rd(n,e=n.length,t={}){if(!Number.isInteger(e)||e<0||e>Te)throw new P("E_TOO_LARGE",`node count ${e} is not an integer in [0, MAX_COUNT]`,{count:e,max:Te});const r=t.map!==void 0||t.validate===!1;let o=n;if(!r){const a=new Array(e);for(let c=0;c<e;c++)a[c]=jn(n[c]);o=a}const s=Cy(o,e),i=Ny(s,e);switch(i){case"identity":return new Yt(fn("identity",e,{offset:e===0?0:s.offset}));case"dense":{const a=Ty(o,e),c=td(a,s.maxId,Ca);return new Yt(fn("dense",e,{denseValues:a,denseInverse:c}))}case"numeric":case"mixed":{const a=t.map??(r?null:qo(o,e,Ca));return new Yt(fn(i,e,{decoded:o,map:a}))}case"string":{const a=t.map??(r?null:qo(o,e,Ca)),c=Wn.fromStrings(o,e);return new Yt(fn("string",e,{strings:c,map:a}))}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(i)}`,{kind:i})}}function Oy(n){const e=Bs.get(n),t=new Set;if(e===void 0)return[];for(const r of[e.denseValues,e.denseInverse,e.numbers,e.tags])r!==null&&t.add(r.buffer);return e.strings?.encoded&&(t.add(e.strings.offsets.buffer),t.add(e.strings.utf8.buffer)),[...t]}function $y(n,e="structure"){const{kind:t,size:r}=n;if(e!=="none"&&(!Number.isInteger(r)||r<0||r>Te))throw hn("ids.size",`size ${r} is not an integer in [0, MAX_COUNT]`,{found:r});switch(t){case"identity":return Ry(n,e);case"dense":return Dy(n,e);case"numeric":return Ly(n,e);case"string":return My(n,e);case"mixed":return By(n,e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Na(n,e,t){return Wr(`duplicate id ${Pn(n)}`,{id:n,indices:[e,t]})}function zs(n,e,t,r){if(t!==r)throw hn(n,`expected ${r} ${e}, found ${t}`,{expected:r,found:t})}function od(n){const e=n.firstMalformedRow();if(e!==-1)throw Wr(`malformed UTF-8 in id at index ${e}`,{index:e})}function Ry(n,e){const{offset:t,size:r}=n;if(!Number.isSafeInteger(t)||r>0&&!Number.isSafeInteger(t+r-1)){const o=`offset ${t} with ${r} ids leaves the safe-integer range`;throw e==="full"?Wr(o,{found:t,size:r}):hn("ids.offset",o,{found:t,size:r})}return new Yt(fn("identity",r,{offset:jo(t)}))}function Dy(n,e){const{values:t,size:r}=n;if(!(t instanceof Uint32Array))throw hn("ids.values","a dense id map needs u32 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=-1;for(let i=0;i<t.length;i++)t[i]>o&&(o=t[i]);if(o>=Te)throw hn("ids.values",`dense id ${o} is not below MAX_COUNT`,{found:o});if(o+1>2*Math.max(r,t.length))throw hn("ids.values",`dense bound violated: max id ${o} with ${r} nodes`,{maxId:o,size:r});const s=td(t,o,(i,a,c)=>Wr(`duplicate id ${i}`,{id:i,indices:[a,c]}));return new Yt(fn("dense",r,{denseValues:t,denseInverse:s}))}function Ly(n,e){const{values:t,size:r}=n;if(!(t instanceof Float64Array))throw hn("ids.values","a numeric id map needs f64 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=null;if(e==="full"){for(let s=0;s<r;s++)if(!Number.isFinite(t[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:t[s]});o=qo(t,r,Na)}return new Yt(fn("numeric",r,{numbers:t,map:o}))}function My(n,e){const{offsets:t,utf8:r,size:o}=n;if(t===null||r===null)throw hn("ids.offsets","a string id map needs offsets and utf8");e!=="none"&&ha(t,r,o,"ids.offsets");const s=Wn.fromEncoded(t,r);let i=null;return e==="full"&&(od(s),i=qo(s.decodeAll(),o,Na)),new Yt(fn("string",o,{strings:s,map:i}))}function Uy(n,e,t,r,o){zs("ids.tags","tags",n.length,o),zs("ids.numbers","numbers",e.length,o);for(let s=0;s<o;s++)if(n[s]>1)throw hn("ids.tags",`tag ${n[s]} at index ${s} is not 0 or 1`,{index:s,found:n[s]});ha(t,r,o,"ids.offsets")}function Fy(n,e,t,r){const o=new Array(r);for(let s=0;s<r;s++)if(n[s]===0){if(!Number.isFinite(e[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:e[s]});o[s]=e[s]}else o[s]=t.at(s);return o}function By(n,e){const{tags:t,numbers:r,offsets:o,utf8:s,size:i}=n;if(t===null||r===null||o===null||s===null)throw hn("ids.tags","a mixed id map needs tags, numbers, offsets and utf8");e!=="none"&&Uy(t,r,o,s,i);const a=Wn.fromEncoded(o,s);let c=null;return e==="full"&&(od(a),c=qo(Fy(t,r,a,i),i,Na)),new Yt(fn("mixed",i,{tags:t,numbers:r,strings:a,map:c}))}function zy(n){const e=Py(n),{kind:t,size:r}=e;switch(t){case"identity":return{kind:t,size:r,offset:e.offset,values:null,tags:null,numbers:null,offsets:null,utf8:null};case"dense":return{kind:t,size:r,offset:0,values:e.denseValues,tags:null,numbers:null,offsets:null,utf8:null};case"numeric":{if(e.numbers===null){const o=e.decoded,s=new Float64Array(r);for(let i=0;i<r;i++){const a=o[i];if(typeof a!="number")throw new P("E_INVALID_ID",`numeric id map holds a ${typeof a} at index ${i}`,{index:i,found:typeof a});s[i]=a}e.numbers=s,it(s.buffer)}return{kind:t,size:r,offset:0,values:e.numbers,tags:null,numbers:null,offsets:null,utf8:null}}case"string":{const o=e.strings;return{kind:t,size:r,offset:0,values:null,tags:null,numbers:null,offsets:o.offsets,utf8:o.utf8}}case"mixed":{if(e.tags===null||e.numbers===null||e.strings===null){const o=e.decoded,s=new Uint8Array(r),i=new Float64Array(r);for(let l=0;l<r;l++){const u=o[l];typeof u=="number"?i[l]=u:s[l]=1}const{offsets:a,utf8:c}=Do(o,r);e.tags=s,e.numbers=i,e.strings=Wn.fromEncoded(a,c);for(const l of[s.buffer,i.buffer,a.buffer,c.buffer])it(l)}return{kind:t,size:r,offset:0,values:null,tags:e.tags,numbers:e.numbers,offsets:e.strings.offsets,utf8:e.strings.utf8}}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Gy(n,e){const t=e.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n.idOf(e[o]);return rd(r,t,{validate:!1})}const Wy=new Set(["string","integer","mixed"]),Vy=new Set(["integer","double","date","dateTime"]),jy=new Set(["interval","timestamp"]),qy=new Set(["static","dynamic","slice"]),Ta=Object.freeze({name:null,description:null,creator:null,created:null,modified:null,keywords:Object.freeze([]),sourceFormat:null,sourceVersion:null,idType:null,timeFormat:null,timeRepresentation:null,mode:null,declaredMultigraph:null,weightOrigin:null,extra:Object.freeze({})});function Vr(n,e){return new P("E_COLUMN_TYPE",`meta.${n} has an unsupported value`,{field:n,found:typeof e})}function vr(n,e){if(e===null||typeof e=="string")return e;throw Vr(n,e)}function Gs(n,e,t){if(e===null)return null;if(typeof e=="string"&&t.has(e))return e;throw Vr(n,e)}function Hy(n){if(n===null)return null;if(typeof n!="object")throw Vr("weightOrigin",n);const e=n,t=r=>{const o=e[r];if(o==null)return null;if(typeof o!="string")throw Vr(`weightOrigin.${r}`,o);return o};return Object.freeze({format:t("format"),id:t("id"),title:t("title"),type:t("type"),namespace:t("namespace")})}function Ky(n,e){const t=(r,o)=>{const s=e[r];return s===void 0?n[r]:o(s)};return Object.freeze({name:t("name",r=>vr("name",r)),description:t("description",r=>vr("description",r)),creator:t("creator",r=>vr("creator",r)),created:t("created",r=>vr("created",r)),modified:t("modified",r=>vr("modified",r)),keywords:t("keywords",r=>{if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw Vr("keywords",r);return Object.freeze([...r])}),sourceFormat:t("sourceFormat",r=>vr("sourceFormat",r)),sourceVersion:t("sourceVersion",r=>vr("sourceVersion",r)),idType:t("idType",r=>Gs("idType",r,Wy)),timeFormat:t("timeFormat",r=>Gs("timeFormat",r,Vy)),timeRepresentation:t("timeRepresentation",r=>Gs("timeRepresentation",r,jy)),mode:t("mode",r=>Gs("mode",r,qy)),declaredMultigraph:t("declaredMultigraph",r=>{if(r===null||typeof r=="boolean")return r;throw Vr("declaredMultigraph",r)}),weightOrigin:t("weightOrigin",r=>Hy(r)),extra:t("extra",r=>ht("meta","graph",{dtype:"json",extra:r}).extra)})}const Yy=4294967295;class bt{constructor(e,t){this.used=0,this.ctor=e,this.resizable=t?.resizable??ga,this.backing=this.allocate(t?.capacity??0)}get length(){return this.used}get capacity(){return this.backing.length}get array(){return this.backing}push(e){const t=this.used;return t>=this.backing.length&&(this.backing=$u(this.backing,this.ctor,t+1,this.resizable)),this.backing[t]=e,this.used=t+1,t}pushAll(e){const t=this.used,r=t+e.length;return this.ensureCapacity(r),this.backing.set(e,t),this.used=r,t}get(e){return this.backing[e]}set(e,t){this.backing[e]=t}ensureCapacity(e){e>this.backing.length&&(this.backing=$u(this.backing,this.ctor,e,this.resizable))}resize(e,t=0){e>this.used&&(this.ensureCapacity(e),this.backing.fill(t,this.used,e)),this.used=e}view(){return new this.ctor(this.backing.buffer,0,this.used)}trim(){const e=new this.ctor(new ArrayBuffer(this.used*this.ctor.BYTES_PER_ELEMENT),0,this.used);return e.set(this.view()),e}clear(){this.used=0}release(){this.used=0,this.backing=this.allocate(0)}allocate(e){const t=this.ctor.BYTES_PER_ELEMENT,r=e===0?0:Tu(Lo(e,wa),t);return new this.ctor(Ou(r,this.resizable),0,r/t)}}class xn{constructor(e){this.bits=0,this.words=new bt(Uint32Array,{capacity:Fe(e?.capacity??0),resizable:e?.resizable})}get length(){return this.bits}push(e){const t=this.bits;return t%32===0&&this.words.push(0),e&&ba(this.words.array,t,!0),this.bits=t+1,t}get(e){return Le(this.words.array,e)}set(e,t){ba(this.words.array,e,t)}count(){return gr(this.words.array,this.bits)}resize(e,t=!1){const r=this.bits;this.words.resize(Fe(e),0),e<r?ya(this.words.array,e):t&&e>r&&this.setRange(r,e),this.bits=e}setRange(e,t){const{array:r}=this.words;let o=e;for(;o<t&&o%32!==0;)Ht(r,o++);const s=t-t%32;for(o<s&&(r.fill(Yy,o/32,s/32),o=s);o<t;)Ht(r,o++)}view(){return this.words.view()}trim(){return this.words.trim()}clear(){this.bits=0,this.words.clear()}release(){this.bits=0,this.words.release()}}const Xy=Object.freeze([]),Oa=2**24;function $a(n){if(n>Oa)throw new P("E_TOO_LARGE",`node count ${n} exceeds the ${Oa} nodes with explicit ids one builder can hold`,{count:n,max:Oa})}function gn(n,e,t,r){return new P("E_COLUMN_TYPE",`row ${e} of ${n.dtype} column "${n.name}": ${t}`,{column:n.name,domain:n.domain,row:e,found:r})}function Ra(n){const e=Ls(n);if(e===null)throw new P("E_COLUMN_TYPE","an unset value cannot start an inferred column",{reason:"unset"});return e}function Da(n){switch(n){case"bool":return"bool";case"i32":case"u8":return"i32";case"u32":case"f32":case"f64":return"f64";case"dict":case"string":return"string";case"list":case"json":return"json";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function Qy(n,e,t){const r=n.itemDtype,o=n.itemComponents??1;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":Jy(n,e,t,r,o);return;case"bool":if(typeof t!="boolean")throw gn(n,e,"list item is not a boolean",typeof t);return;case"dict":case"string":if(typeof t!="string")throw gn(n,e,"list item is not a string",typeof t);wr(t,{column:n.name,row:e});return;case"json":cn(t,n.name);return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Jy(n,e,t,r,o){if(o===1){if(typeof t!="number"||!yr(r,t))throw gn(n,e,`list item is not a representable ${r}`,typeof t);return}if(!Array.isArray(t)||t.length!==o)throw gn(n,e,`list item is not ${o} numbers`,typeof t);for(const s of t)if(typeof s!="number"||!yr(r,s))throw gn(n,e,`list item component is not a representable ${r}`,typeof s)}class Ws{constructor(e,t,r,o){this.length=0,this.typed=null,this.bits=null,this.values=null,this.dictionary=null,this.validity=null,this.meta=e,this.resizable=r,t?(this.inferrer=new zu,this.inferrer.widenTo(Da(e.dtype))):this.inferrer=null,this.allocate(o)}get inferred(){return this.inferrer!==null}get inferredDtype(){return this.inferrer===null?null:this.inferrer.dtype}ensureLength(e){if(e<=this.length)return;const{meta:t}=this;if(this.typed!==null)this.typed.resize(e*t.components,this.fillNumber());else if(this.bits!==null)this.bits.resize(e,t.fill===!0);else if(this.values!==null){const r=this.fillValue();for(let o=this.length;o<e;o++)this.values.push(r)}this.validity!==null&&this.validity.resize(e,!1),this.length=e}isSet(e){return e>=this.length?!1:this.validity===null||this.validity.get(e)}write(e,t){if(this.ensureLength(e+1),t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json"))return this.unset(e),null;let r=null;if(this.inferrer!==null){const o=this.meta.dtype;if(this.inferrer.observeValue(t)){const s=this.inferrer.dtype;this.widenTo(s),r={from:o,to:s}}this.storeRaw(e,t)}else this.store(e,t);return this.validity!==null&&this.validity.set(e,!0),r}checkValue(e,t){if(t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json")){if(this.validity===null)throw this.unsetError(e);return}if(this.inferrer!==null){Ls(t),this.checkRaw(e,t);return}this.coerce(e,t)}unset(e){if(this.ensureLength(e+1),this.validity===null)throw this.unsetError(e);this.validity.set(e,!1),this.writeFill(e)}unsetError(e){return new P("E_COLUMN_TYPE",`row ${e} of non-nullable column "${this.meta.name}" cannot be unset`,{column:this.meta.name,row:e,field:"nullable"})}read(e){if(!this.isSet(e))return;if(this.inferrer!==null)return Br(this.values[e],this.inferrer.dtype);const{meta:t}=this,{dtype:r,components:o}=t;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(o===1)return s.get(e);const i=new Array(o);for(let a=0;a<o;a++)i[a]=s.get(e*o+a);return i}case"bool":return this.bits.get(e);case"dict":{const s=this.typed.get(e);return this.dictionary.values[s]}case"string":case"list":case"json":return this.values[e];default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}widenTo(e){const{meta:t}=this,r=ht(t.name,t.domain,{dtype:e,nullable:!0,role:t.role??void 0,extra:t.extra});if(this.inferrer!==null){this.inferrer.widenTo(e),this.meta=r;return}const o=this.length,s=new Array(o),i=new xn({capacity:o,resizable:this.resizable});i.resize(o,!1);for(let a=0;a<o;a++)this.isSet(a)&&(s[a]=this.read(a),i.set(a,!0));this.meta=r,this.inferrer=new zu,this.inferrer.widenTo(e),this.typed=null,this.bits=null,this.dictionary=null,this.values=s,this.validity=i}gather(e,t){const r=e===null?this.length:e.length,o=new Ws(this.meta,this.inferred,this.resizable,this.dictionary??void 0);o.ensureLength(r);const{components:s}=this.meta,i=t!==null&&this.meta.refersTo!==null;for(let a=0;a<r;a++){const c=e===null?a:e[a];if(this.isSet(c)){if(o.typed!==null&&this.typed!==null)if(i){const l=sd(this.typed.get(c),t);if(l===x){o.unsetDangling(a);continue}o.typed.set(a,l)}else for(let l=0;l<s;l++)o.typed.set(a*s+l,this.typed.get(c*s+l));else if(o.bits!==null&&this.bits!==null)o.bits.set(a,this.bits.get(c));else if(o.values!==null&&this.values!==null){let l=this.values[c];if(i){const u=l,d=[];for(const f of u){const h=sd(f,t);h!==x&&d.push(h)}if(d.length===0&&u.length>0){o.unsetDangling(a);continue}l=d}o.values[a]=l}o.validity!==null&&o.validity.set(a,!0)}}return o}unsetDangling(e){if(this.validity!==null)return;const{meta:t}=this;this.meta=ht(t.name,t.domain,{...Sn(t),nullable:!0});const r=new xn({capacity:this.length,resizable:this.resizable});r.resize(this.length,!1);const{typed:o}=this;for(let s=0;s<e;s++)o?.get(s)!==x&&r.set(s,!0);this.validity=r}toColumn(e){this.ensureLength(e);const{meta:t}=this,{dtype:r,components:o}=t;if(this.inferrer!==null){const a=this.values,c=new Array(e);for(let l=0;l<e;l++)c[l]=this.isSet(l)?a[l]:void 0;return Vo(t,c)}let s=null;this.validity!==null&&this.validity.count()!==e&&(s=this.validity.trim());const i={meta:t,length:e,data:null,validity:s,nullCount:s===null?0:e-this.validity.count(),dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null};switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const a=Ju(r,e*o);return a.set(this.typed.view().subarray(0,e*o)),i.data=a,t.refersTo!==null&&this.validity===null&&Zy(i,a,e),Tt(i)}case"bool":return i.data=this.bits.trim(),Tt(i);case"dict":{const a=new Uint32Array(e);return a.set(this.typed.view().subarray(0,e)),i.data=a,i.dictionary=[...this.dictionary.values],Tt(i)}case"string":case"list":case"json":{const a=this.values,c=new Array(e);for(let l=0;l<e;l++){const u=this.isSet(l)?a[l]:void 0;c[l]=u===void 0?this.unsetEntry():u}return Vo(t,c)}default:{const a=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}byteLength(){let e=0;return this.typed!==null&&(e+=this.typed.array.byteLength),this.bits!==null&&(e+=Fe(this.bits.length)*4),this.validity!==null&&(e+=Fe(this.validity.length)*4),e}allocate(e){const{meta:t}=this,{dtype:r}=t,o={resizable:this.resizable};if(this.inferrer!==null){this.values=[],this.validity=new xn(o);return}switch(r){case"f32":this.typed=new bt(Float32Array,o);break;case"f64":this.typed=new bt(Float64Array,o);break;case"i32":this.typed=new bt(Int32Array,o);break;case"u32":this.typed=new bt(Uint32Array,o);break;case"u8":this.typed=new bt(Uint8Array,o);break;case"bool":this.bits=new xn(o);break;case"dict":{this.typed=new bt(Uint32Array,o),this.dictionary=e??Pa(t);break}case"string":case"list":case"json":this.values=[];break;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}this.validity=t.nullable?new xn(o):null}fillNumber(){const{meta:e}=this;if(e.dtype==="dict"){const t=this.dictionary,r=typeof e.fill=="string"?e.fill:"";if(this.validity===null)return t.intern(r);const o=t.codeOf(r);return o===x?0:o}return typeof e.fill=="number"?e.fill:0}fillValue(){if(this.inferrer===null)switch(this.meta.dtype){case"string":return typeof this.meta.fill=="string"?this.meta.fill:"";case"list":return Xy;default:return}}unsetEntry(){if(!this.meta.nullable)return this.meta.dtype==="json"?null:this.fillValue()}writeFill(e){const{components:t}=this.meta;if(this.typed!==null){const r=this.fillNumber();for(let o=0;o<t;o++)this.typed.set(e*t+o,r)}else this.bits!==null?this.bits.set(e,this.meta.fill===!0):this.values!==null&&(this.values[e]=this.fillValue())}storeRaw(e,t){this.checkRaw(e,t),this.values[e]=typeof t=="string"?Ro(t):t}checkRaw(e,t){const{meta:r}=this;typeof t=="string"?wr(t,{column:r.name,row:e}):typeof t=="object"&&cn(t,`${r.name}[${e}]`)}store(e,t){this.put(e,this.coerce(e,t))}coerce(e,t){const{meta:r}=this,{dtype:o,components:s}=r;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":{const i=typeof t=="boolean"?Number(t):t;if(typeof i=="number"){if(!yr(o,i))throw gn(r,e,`${i} is not representable`,i);return i}if(s===1||!Yu(i,s))throw gn(r,e,`not ${s} number(s)`,typeof i);for(let a=0;a<s;a++)if(!yr(o,i[a]))throw gn(r,e,`${i[a]} is not representable`,i[a]);return i}case"bool":return Br(t,"bool")===!0;case"dict":case"string":{const i=Br(t,"string");if(typeof i!="string")throw gn(r,e,"not a string",typeof t);return wr(i,{column:r.name,row:e}),Ro(i)}case"list":{if(!Array.isArray(t))throw gn(r,e,"not an array",typeof t);for(const i of t)Qy(r,e,i);return t.map(i=>typeof i=="string"?Ro(i):i)}case"json":return cn(t,`${r.name}[${e}]`),t;default:{const i=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}put(e,t){const{dtype:r,components:o}=this.meta;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(typeof t=="number"){if(o===1)s.set(e,t);else for(let a=0;a<o;a++)s.set(e*o+a,t);return}const i=t;for(let a=0;a<o;a++)s.set(e*o+a,i[a]);return}case"bool":this.bits.set(e,t===!0);return;case"dict":this.typed.set(e,this.dictionary.intern(t));return;case"string":case"list":case"json":this.values[e]=t;return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}}function sd(n,e){return n<e.length?e[n]:x}function Zy(n,e,t){let r=null;for(let o=0;o<t;o++)e[o]===x&&(r??=In(t,!0),Kt(r,o),n.nullCount++);if(r!==null){const{meta:o}=n;n.meta=ht(o.name,o.domain,{...Sn(o),nullable:!0}),n.validity=r}}function jr(n,e,t,r,o){return new Ws(ht(n,e,t),r,o)}class id{constructor(e,t){this.lists=e,this.alive=t,this.found=[],this.list=0,this.edge=e[0][0]}step(){for(;this.edge===x;){if(this.list++,this.list===this.lists.length)return!0;this.edge=this.lists[this.list][0]}const[,e,t,r]=this.lists[this.list];return this.alive.get(this.edge)&&t.get(this.edge)===r&&this.found.push(this.edge),this.edge=e.get(this.edge),!1}}class La{constructor(e){this.ids=null,this.idToIndex=null,this.weight=null,this.weightSet=null,this.weightMode="none",this.liveNodeCount=0,this.liveEdgeCount=0,this.selfLoopCount=0,this.nodeColumns=[],this.edgeColumns=[],this.extensions=[],this.options=e;const{resizable:t}=e,r=e.expectedNodes??0,o=e.expectedEdges??0;this.nodeAlive=new xn({capacity:r,resizable:t}),this.firstOut=new bt(Uint32Array,{capacity:r,resizable:t}),this.firstIn=new bt(Uint32Array,{capacity:r,resizable:t}),this.src=new bt(Uint32Array,{capacity:o,resizable:t}),this.dst=new bt(Uint32Array,{capacity:o,resizable:t}),this.edgeAlive=new xn({capacity:o,resizable:t}),this.nextOut=new bt(Uint32Array,{capacity:o,resizable:t}),this.nextIn=new bt(Uint32Array,{capacity:o,resizable:t}),e.weighted&&(this.weight=this.allocateWeights(o))}get nodeBound(){return this.nodeAlive.length}get edgeBound(){return this.edgeAlive.length}get hasTombstones(){return this.liveNodeCount<this.nodeBound||this.liveEdgeCount<this.edgeBound}reserve(e,t){e>0&&(this.firstOut.ensureCapacity(e),this.firstIn.ensureCapacity(e)),t>0&&(this.src.ensureCapacity(t),this.dst.ensureCapacity(t),this.nextOut.ensureCapacity(t),this.nextIn.ensureCapacity(t),this.weight!==null&&this.weight.ensureCapacity(t))}materialiseIds(){if(this.ids!==null&&this.idToIndex!==null)return;const e=this.nodeBound;$a(e);const t=new Array(e),r=new Map;for(let o=0;o<e;o++)t[o]=o,r.set(o,o);this.ids=t,this.idToIndex=r}pushNode(e){this.idToIndex!==null&&$a(this.idToIndex.size+1);const t=this.nodeAlive.push(!0);if(this.firstOut.push(x),this.firstIn.push(x),this.ids!==null&&this.idToIndex!==null){const r=e??t;this.ids.push(r),this.idToIndex.set(r,t)}return this.liveNodeCount++,t}pushAnonymousNodes(e){if(this.idToIndex!==null){for(let r=0;r<e;r++)this.pushNode(null);return}const t=this.nodeBound+e;this.nodeAlive.resize(t,!0),this.firstOut.resize(t,x),this.firstIn.resize(t,x),this.liveNodeCount+=e}ensureWeights(){return this.weight===null&&(this.weight=this.allocateWeights(this.edgeBound),this.weight.resize(this.edgeBound,1)),this.weight}trackWeight(e,t){if(this.weightSet!==null){e>=this.weightSet.length&&this.weightSet.resize(e+1,!1),this.weightSet.set(e,t);return}switch(this.weightMode){case"none":this.weightMode=t?"explicit":"omitted";return;case"explicit":t||this.allocateWeightSet(!0,e);return;case"omitted":t&&this.allocateWeightSet(!1,e);return;case"mixed":return;default:{const r=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${r}`,{mode:r})}}}weightExplicit(e){return this.weightSet===null?this.weightMode==="explicit":e<this.weightSet.length&&this.weightSet.get(e)}pushEdge(e,t,r){const o=this.src.push(e);return this.dst.push(t),r!==void 0?this.ensureWeights().push(r):this.weight!==null&&this.weight.push(1),this.trackWeight(o,r!==void 0),this.edgeAlive.push(!0),this.nextOut.push(this.firstOut.get(e)),this.firstOut.set(e,o),this.nextIn.push(this.firstIn.get(t)),this.firstIn.set(t,o),this.liveEdgeCount++,e===t&&this.selfLoopCount++,o}pushEdges(e,t,r){const o=e.length,s=this.edgeBound,i=s+o;return o===0||(this.src.pushAll(e),this.dst.pushAll(t),r!==null?this.ensureWeights().pushAll(r):this.weight!==null&&this.weight.resize(i,1),this.trackWeights(s,o,r!==null),this.edgeAlive.resize(i,!0),this.nextOut.resize(i),this.nextIn.resize(i),this.selfLoopCount+=tb(this.src.array,this.dst.array,s,i,{firstOut:this.firstOut.array,firstIn:this.firstIn.array,nextOut:this.nextOut.array,nextIn:this.nextIn.array}),this.liveEdgeCount+=o),s}trackWeights(e,t,r){const o=e+t;let s=this.weightSet;if(s===null)switch(this.weightMode){case"none":this.weightMode=r?"explicit":"omitted";return;case"explicit":if(r)return;s=this.allocateWeightSet(!0,e);break;case"omitted":if(!r)return;s=this.allocateWeightSet(!1,e);break;case"mixed":return;default:{const i=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${i}`,{mode:i})}}s.length<e&&s.resize(e,!1),s.resize(o,r)}killEdge(e){this.edgeAlive.set(e,!1),this.liveEdgeCount--,this.src.get(e)===this.dst.get(e)&&this.selfLoopCount--}outEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}inEdges(e){const t=[];for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}incidentEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&this.src.get(r)!==e&&t.push(r);return Uint32Array.from(t).sort()}edgesBetween(e,t,r){const o=(u,d)=>[this.firstOut.get(u),this.nextOut,this.dst,d],s=(u,d)=>[this.firstIn.get(u),this.nextIn,this.src,d],i=r||e===t?[o(e,t)]:[o(e,t),s(e,t)],a=r?[s(t,e)]:[o(t,e),s(t,e)],c=new id(i,this.edgeAlive),l=e===t?c:new id(a,this.edgeAlive);for(;;){if(c.step())return Uint32Array.from(c.found).sort();if(l.step())return Uint32Array.from(l.found).sort()}}byteLength(){let e=this.firstOut.array.byteLength+this.firstIn.array.byteLength+this.src.array.byteLength+this.dst.array.byteLength+this.nextOut.array.byteLength+this.nextIn.array.byteLength+Fe(this.nodeAlive.length)*4+Fe(this.edgeAlive.length)*4;this.weight!==null&&(e+=this.weight.array.byteLength),this.weightSet!==null&&(e+=Fe(this.weightSet.length)*4);for(const t of this.nodeColumns)e+=t.byteLength();for(const t of this.edgeColumns)e+=t.byteLength();for(const t of this.extensions)for(const r of t.columns)e+=r.byteLength();return e}allocateWeights(e){const{resizable:t}=this.options;return this.options.weightDtype==="f64"?new bt(Float64Array,{capacity:e,resizable:t}):new bt(Float32Array,{capacity:e,resizable:t})}allocateWeightSet(e,t){const r=new xn({capacity:t+1,resizable:this.options.resizable});return r.resize(t,e),r.push(!e),this.weightSet=r,this.weightMode="mixed",r}}function ad(n,e){const t=new Uint32Array(n);let r=0;for(let s=0;s<n;s++)(e[s>>>5]>>>(s&31)&1)===1?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<n;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function eb(n){const e=n.length,t=new Uint32Array(e);let r=0;for(let s=0;s<e;s++)n[s]===s?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<e;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function tb(n,e,t,r,o){const{firstOut:s,firstIn:i,nextOut:a,nextIn:c}=o;let l=0;for(let u=t;u<r;u++){const d=n[u],f=e[u];a[u]=s[d],s[d]=u,c[u]=i[f],i[f]=u,d===f&&l++}return l}function nb(n,e,t,r,o,s,i){const{firstOut:a,firstIn:c,nextOut:l,nextIn:u}=i,d=t.length;let f=0;for(let h=0;h<d;h++){const g=t[h],w=r[n[g]],p=r[e[g]];o[h]=w,s[h]=p,l[h]=a[w],a[w]=h,u[h]=c[p],c[p]=h,w===p&&f++}return f}function rb(n,e,t){const r=e.length;for(let o=0;o<r;o++)t[o]=n[e[o]]}function ob(n,e,t,r){for(let o=0;o<r;o++)Le(e,o)&&(t[o]=n[o])}function cd(n,e){const{nodes:t,edges:r}=e,o=new La({...n.options,weighted:n.weight!==null||e.mergedWeights!==null,expectedNodes:t.count,expectedEdges:r.count});if(o.nodeAlive.resize(t.count,!0),o.firstOut.resize(t.count,x),o.firstIn.resize(t.count,x),o.liveNodeCount=t.count,n.ids!==null){const l=new Array(t.count),u=new Map;for(let d=0;d<t.count;d++){const f=n.ids[t.origin[d]];l[d]=f,u.set(f,d)}o.ids=l,o.idToIndex=u}const{remap:s}=t,i=r.count,{origin:a}=r;if(o.weightMode=n.weightMode,(n.weightSet!==null||e.mergedWeightSet!==null)&&(o.weightSet=new xn({capacity:i,resizable:n.options.resizable}),o.weightMode="mixed"),o.src.resize(i),o.dst.resize(i),o.nextOut.resize(i),o.nextIn.resize(i),o.edgeAlive.resize(i,!0),o.liveEdgeCount=i,o.selfLoopCount=nb(n.src.array,n.dst.array,a,s,o.src.array,o.dst.array,{firstOut:o.firstOut.array,firstIn:o.firstIn.array,nextOut:o.nextOut.array,nextIn:o.nextIn.array}),o.weight!==null){o.weight.resize(i);const l=o.weight.array;n.weight===null?l.fill(1,0,i):rb(n.weight.array,a,l),e.mergedWeights!==null&&e.mergedWeightStored!==null&&ob(e.mergedWeights,e.mergedWeightStored,l,i)}if(o.weightSet!==null){o.weightSet.resize(i,!1);for(let l=0;l<i;l++){let u=n.weightExplicit(a[l]);e.mergedWeightSet!==null&&Le(e.mergedWeightSet,l)&&(u=!0),u&&o.weightSet.set(l,!0)}}const c={node:s,edge:e.edgeValues??r.remap};return o.nodeColumns=n.nodeColumns.map(l=>l.gather(t.origin,Ma(l,c))),o.edgeColumns=n.edgeColumns.map(l=>l.gather(r.origin,Ma(l,c))),o.extensions=n.extensions.map(l=>({name:l.name,rowCount:l.rowCount,columns:l.columns.map(u=>u.gather(null,Ma(u,c)))})),o}function Ma(n,e){switch(n.meta.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ua(n){return n instanceof Uint32Array||n instanceof Int32Array||n instanceof Float32Array||n instanceof Float64Array||n instanceof Uint8Array}function sb(n){if(typeof n!="object"||n===null||Array.isArray(n)||Ua(n))return!1;const e=n;return typeof e.dtype=="string"&&typeof e.meta=="object"&&typeof e.length=="number"}function ib(n){return n.mutations}function Vs(n){n.sealed=!0}function ab(n){it(n);for(const e of Sa(n))it(e)}class wn{constructor(e){this.mutations=0,this.sealed=!1;const{domain:t,rowCount:r}=e;if(!(Number.isInteger(r)&&r>=0))throw new P("E_COLUMN_LENGTH",`invalid row count ${r} for a ${t} table`,{domain:t,found:r});this.domain=t,this.rowCount=r,this.columns=new Map;for(const o of e.columns){const{name:s}=o.meta;if(this.columns.has(s))throw new P("E_COLUMN_EXISTS",`column "${s}" is declared twice`,{column:s});this.checkColumn(s,o),this.checkRole(s,o.meta.role,!1),this.columns.set(s,o),ab(o)}}names(){return[...this.columns.keys()]}has(e){return this.columns.has(e)}get(e){return this.columns.get(e)??null}require(e){const t=this.columns.get(e);if(t===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${this.domain} column named "${e}"`,{column:e,domain:this.domain});return t}typed(e,t){const r=this.columns.get(e);return r?.dtype!==t?null:r}requireTyped(e,t){const r=this.require(e);if(r.dtype!==t)throw new P("E_COLUMN_TYPE",`column "${e}" is ${r.dtype}, expected ${t}`,{column:e,expected:t,found:r.dtype});return r}byRole(e){for(const t of this.columns.values())if(t.meta.role===e)return t;return null}value(e,t){return this.require(e).value(t)}isSet(e,t){return this.require(e).isSet(t)}set(e,t,r,o){this.assertWritable(e);const s=r??{};let i;if(Ua(t)){const c=zt("adopt",o?.adopt,["copy","strict"])??"copy";i=Ey(this.domain,this.rowCount,e,t,s,c)}else if(Array.isArray(t))i=xa(this.domain,this.rowCount,e,t,s);else if(sb(t)){if(!gy(t))throw new P("E_COLUMN_TYPE",`column "${e}": not a Column of this package`,{column:e,reason:"foreign column"});i=this.adoptColumn(e,t,r),i!==t&&N0(t)>0&&Gn(i)}else throw new P("E_COLUMN_TYPE",`column "${e}": unsupported data (${typeof t})`,{column:e,found:typeof t});this.checkRole(e,i.meta.role,o?.replaceRole??!1);const a=this.columns.get(e);if(a!==i&&(it(i),a!==t))for(const c of Sa(i))it(c);return this.columns.set(e,i),this.mutations++,i}remove(e){this.assertWritable(e);const t=this.columns.delete(e);return t&&this.mutations++,t}rename(e,t){this.assertWritable(e);const r=this.require(e);if(e===t)return;if(this.columns.has(t))throw new P("E_COLUMN_EXISTS",`cannot rename "${e}": a column named "${t}" exists`,{column:t});const o=Xu(r,ht(t,this.domain,Sn(r.meta)));it(o),Fr(r)&&Gn(o);const s=[...this.columns.entries()];this.columns.clear();for(const[i,a]of s)i===e?this.columns.set(t,o):this.columns.set(i,a);this.mutations++}gpuView(e){return py(this.require(e))}clone(){return new wn({domain:this.domain,rowCount:this.rowCount,columns:[...this.columns.values()]})}[Symbol.iterator](){return this.columns.values()}adoptColumn(e,t,r){this.checkColumn(e,t);const{meta:o}=t;if(r===void 0&&o.name===e&&o.domain===this.domain)return t;const i={...Sn(o),...r};return r?.fill===void 0&&(i.fill=o.fill),Xu(t,ht(e,this.domain,i))}assertWritable(e){if(this.sealed)throw new P("E_FROZEN",`the ${this.domain} table is sealed: its column set cannot change (column "${e}")`,{domain:this.domain,column:e})}checkColumn(e,t){if(t.length!==this.rowCount)throw new P("E_COLUMN_LENGTH",`column "${e}" has ${t.length} rows; the ${this.domain} table has ${this.rowCount}`,{column:e,expected:this.rowCount,found:t.length})}checkRole(e,t,r){if(t!==null){for(const[o,s]of this.columns)if(o!==e&&s.meta.role===t){if(!r)throw new P("E_DUPLICATE_ROLE",`role "${t}" is already held by column "${o}" in the ${this.domain} table`,{role:t,column:e,holder:o});this.columns.delete(o);return}}}}function ld(n,e){const t=n.clone();for(const r of Object.keys(e)){const o=e[r];Ua(o)?t.set(r,o):t.set(r,o.data,o.decl)}return t}function cb(n,e){const{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":return n.meta.components===1?n.data[e]:Array.from(n.data.subarray(e*n.meta.components,(e+1)*n.meta.components)).join(",");case"bool":return Le(n.data,e);case"dict":return n.codes[e];case"string":return n.valueAt(e);case"list":return JSON.stringify(n.sliceOf(e));case"json":return JSON.stringify(n.values[e]);default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function ud(n){if(!n.meta.unique)return;const e=new Map;for(let t=0;t<n.length;t++){if(!n.isSet(t))continue;const r=cb(n,t),o=e.get(r);if(o!==void 0){const s=n.meta.domain==="edge"?"E_DUPLICATE_EDGE_ID":"E_DUPLICATE_ID";throw new P(s,`column "${n.meta.name}" is unique but rows ${o} and ${t} hold the same value`,{column:n.meta.name,domain:n.meta.domain,rows:[o,t],value:n.value(t)})}e.set(r,t)}}function lb(n){for(const e of n)ud(e)}function js(n){return new P("E_COLUMN_TYPE",`column ${JSON.stringify(n.meta.name)} of dtype ${n.dtype} cannot hold edge ids`,{column:n.meta.name,dtype:n.dtype,reason:"edge id dtype"})}function ub(n,e){switch(n.dtype){case"string":return n.valueAt(e);case"dict":return n.dictionary[n.codes[e]];case"f32":case"f64":case"i32":case"u32":case"u8":return n.data[e*n.meta.components];case"bool":case"list":case"json":throw js(n);default:throw js(n)}}function dd(n){switch(n.dtype){case"string":case"dict":case"f32":case"f64":case"i32":case"u32":case"u8":return!0;case"bool":case"list":case"json":return!1;default:return!1}}function db(n){if(!dd(n))throw js(n);const e=new Map,t=n.length;for(let r=0;r<t;r++){if(!n.isSet(r))continue;const o=ub(n,r);e.has(o)||e.set(o,r)}return e}class fb{constructor(e){if(!dd(e))throw js(e);this.column=e,this.map=null,this.builtVersion=-1}get built(){return this.map!==null&&this.builtVersion===this.column.version}get size(){return this.ensure().size}indexOf(e){const t=this.ensure().get(e);return t===void 0?x:t}has(e){return this.ensure().has(e)}ensure(){const{version:e}=this.column;return(this.map===null||this.builtVersion!==e)&&(this.map=db(this.column),this.builtVersion=e),this.map}}const Ho=["rowPtr","colIdx","weights","arcToEdge","edgeToArc"];function hb(n){const e=n.identity?0:n.arcCount,t=n.identity?0:n.edgeCount;return[4*(n.nodeCount+1),4*n.arcCount,n.weighted?4*n.arcCount:0,4*e,4*t]}function gb(n){return{rowPtr:new Uint32Array(n.nodeCount+1),colIdx:new Uint32Array(n.arcCount),weights:n.weighted?new Float32Array(n.arcCount):null,arcToEdge:n.identity?null:new Uint32Array(n.arcCount),edgeToArc:n.identity?null:new Uint32Array(n.edgeCount),arena:null}}function fd(n){const e=hb(n),t=V0(e,ft),r=new ArrayBuffer(t.byteLength),o={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let s=0;for(let l=0;l<Ho.length;l++){const u=t.offsets[l];if(u===null)continue;const d=Object.freeze({byteOffset:u,byteLength:e[l]});o[Ho[l]]=d,l<=2&&(s=u+e[l])}const i=(l,u)=>{const d=o[l];return d===null?new Uint32Array(0):new Uint32Array(r,d.byteOffset,u)};let a=null;if(n.weighted){const l=o.weights;a=l===null?new Float32Array(0):new Float32Array(r,l.byteOffset,n.arcCount)}const c=Object.freeze({buffer:r,byteOffset:0,byteLength:t.byteLength,alignment:ft,segments:Object.freeze(o),hotByteLength:s});return{rowPtr:i("rowPtr",n.nodeCount+1),colIdx:i("colIdx",n.arcCount),weights:a,arcToEdge:n.identity?null:i("arcToEdge",n.arcCount),edgeToArc:n.identity?null:i("edgeToArc",n.edgeCount),arena:c}}function wb(n,e){return e?fd(n):gb(n)}function pb(n){return{nodeCount:n.rowPtr.length-1,arcCount:n.colIdx.length,edgeCount:n.edgeToArc===null?n.colIdx.length:n.edgeToArc.length,weighted:n.weights!==null,identity:n.arcToEdge===null}}function mb(n){const e=fd(pb(n));return e.rowPtr.set(n.rowPtr),e.colIdx.set(n.colIdx),e.weights!==null&&n.weights!==null&&e.weights.set(n.weights),e.arcToEdge!==null&&n.arcToEdge!==null&&e.arcToEdge.set(n.arcToEdge),e.edgeToArc!==null&&n.edgeToArc!==null&&e.edgeToArc.set(n.edgeToArc),e}function Fa(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<r?o=i+1:s=i}return o}function hd(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<=r?o=i+1:s=i}return o}function yb(n,e,t,r){const o=n[t+1],s=Fa(e,n[t],o,r);return s<o&&e[s]===r?s:x}function qs(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r),a=hd(e,i,s,r);return[i,a]}function gd(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r);return hd(e,i,s,r)-i}function bb(n,e){let t=0,r=n.length;for(;t<r;){const o=t+Math.floor((r-t)/2);n[o]<=e?t=o+1:r=o}return t-1}function vb(n,e,t){return gd(n,e,t,t)}const wd=1024,pd=32,Ab=1;function Ba(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return e}class Ko{constructor(e,t,r,o,s){this.source=e,this.directed=e.directed,this.nodeCount=e.nodeCount,this.arcCount=e.arcCount,this.rowPtr=t,this.colIdx=r,this.weights=o,this.fwdArcCache=s,this.fwdArcIsIdentity=s===null,this.arcToEdgeCache=null,this.arcToEdgeOwned=!1}get fwdArc(){return this.fwdArcCache??=Ba(this.arcCount),this.fwdArcCache}get arcToEdge(){if(this.arcToEdgeCache===null)if(this.fwdArcIsIdentity)this.arcToEdgeCache=this.source.arcToEdge;else if(this.source.flags.arcToEdgeIsIdentity)this.arcToEdgeCache=this.fwdArc;else{const{fwdArc:e}=this,t=this.source.arcToEdge,r=new Uint32Array(this.arcCount);for(let o=0;o<r.length;o++)r[o]=t[e[o]];this.arcToEdgeCache=r,this.arcToEdgeOwned=!0}return this.arcToEdgeCache}get ownedByteLength(){let e=0;return this.directed&&(e+=this.rowPtr.byteLength+this.colIdx.byteLength,this.weights!==null&&(e+=this.weights.byteLength)),this.fwdArcCache!==null&&(e+=this.fwdArcCache.byteLength),this.arcToEdgeOwned&&this.arcToEdgeCache!==null&&(e+=this.arcToEdgeCache.byteLength),e}materialised(){const e={rowPtr:this.rowPtr,colIdx:this.colIdx};return this.weights!==null&&(e.weights=this.weights),this.fwdArcCache!==null&&(e.fwdArc=this.fwdArcCache),this.arcToEdgeCache!==null&&(e.arcToEdge=this.arcToEdgeCache),e}}function Eb(n){const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o,weights:s}=n;if(!n.directed)return new Ko(n,r,o,s,null);const i=new Uint32Array(e+1);for(let d=0;d<t;d++)i[o[d]+1]++;for(let d=0;d<e;d++)i[d+1]+=i[d];const a=new Uint32Array(t),c=new Uint32Array(t),l=s===null?null:new Float32Array(t),u=i.slice(0,e);for(let d=0;d<e;d++){const f=r[d+1];for(let h=r[d];h<f;h++){const g=o[h],w=u[g]++;a[w]=d,c[w]=h,l!==null&&s!==null&&(l[w]=s[h])}}return new Ko(n,i,a,l,c)}function md(n,e,t){const r=new Uint32Array(t);for(let o=0;o<e;o++){const s=n[o+1];for(let i=n[o];i<s;i++)r[i]=o}return r}function _b(n){return yd(n,md(n.rowPtr,n.nodeCount,n.arcCount))}function yd(n,e){return Object.freeze({src:e,dst:n.colIdx,weights:n.weights,get arcToEdge(){return n.arcToEdge}})}function bd(n){const{nodeCount:e,edgeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;if(n.flags.arcToEdgeIsIdentity)return za(n,md(o,e,r),s,i);const{arcToEdge:a,edgeToArc:c}=n,l=new Uint32Array(t),u=new Uint32Array(t);for(let f=0;f<e;f++){const h=o[f+1];for(let g=o[f];g<h;g++){const w=a[g];c[w]===g&&(l[w]=f,u[w]=s[g])}}let d=null;if(i!==null){d=new Float32Array(t);for(let f=0;f<t;f++)d[f]=i[c[f]]}return za(n,l,u,d)}function za(n,e,t,r){return Object.freeze({src:e,dst:t,weights:r,get arc(){return n.edgeToArc}})}function Ar(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++)t[r]=n[r+1]-n[r];return t}function Ib(n,e){const t=new Uint32Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function vd(n,e,t){const r=new Float64Array(t);for(let o=0;o<t;o++){const s=n[o+1];let i=0;for(let a=n[o];a<s;a++)i+=e[a];r[o]=i}return r}function Ga(n){return new Float64Array(n)}function kb(n,e){const t=new Float64Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function Sb(n){const{weights:e,edgeCount:t}=n;if(e===null)return t;let r=0;if(n.flags.arcToEdgeIsIdentity){for(let s=0;s<e.length;s++)r+=e[s];return r}const{edgeToArc:o}=n;for(let s=0;s<t;s++)r+=e[o[s]];return r}function Pb(n){const{nodeCount:e,rowPtr:t,colIdx:r,selfLoopCount:o}=n,s=new Uint32Array(e),i=new Uint32Array(o);let a=0;for(let c=0;c<e;c++){const[l,u]=qs(t,r,c,c);s[c]=u-l;for(let d=l;d<u&&a<o;d++)i[a++]=d}return{selfLoopArcs:i,selfLoopsPerNode:s}}function xb(n,e){const{weights:t,nodeCount:r,rowPtr:o,colIdx:s}=n;if(t===null)return Ga(e.selfLoopsPerNode);const i=new Float64Array(r);for(let a=0;a<r;a++){if(e.selfLoopsPerNode[a]===0)continue;const[c,l]=qs(o,s,a,a);let u=0;for(let d=c;d<l;d++)u+=t[d];i[a]=u}return i}function Cb(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant I7 violated: arc ${t} in row ${n} targeting ${e} has no mate in row ${e}`,{invariant:"I7",row:n,arc:t,target:e})}function Nb(n){if(n.directed)throw new P("E_DIRECTED","mate() is defined for undirected snapshots only",{directed:!0});const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o}=n,s=new Uint32Array(t),i=r.slice(0,e);for(let a=0;a<e;a++){const c=r[a+1];let l=i[a];for(;l<c;){const u=o[l];let d=l+1;for(;d<c&&o[d]===u;)d++;const f=d-l;if(u===a)for(let h=0;h<f;h++)s[l+h]=l+h;else{const h=i[u];if(u<a||h+f>r[u+1]||o[h]!==a||o[h+f-1]!==a)throw Cb(a,u,l);for(let g=0;g<f;g++)s[l+g]=h+g,s[h+g]=l+g;i[u]=h+f}l=d}i[a]=c}return s}function Ad(n,e){const t=Ar(n,e);let r=0;for(let d=0;d<e;d++)t[d]>r&&(r=t[d]);const o=new Uint32Array(r+1);for(let d=0;d<e;d++)o[t[d]]++;let s=0;for(let d=r;d>=0;d--){const f=o[d];o[d]=s,s+=f}const i=new Uint32Array(e);let a=0,c=0,l=0;for(let d=0;d<e;d++){const f=t[d];i[o[f]++]=d,f>=wd?a++:f>=pd?c++:f>=Ab&&l++}const u=new Uint32Array([0,a,a+c,a+c+l,e]);return Object.freeze({perm:i,segmentOffsets:u})}function Tb(n,e){if(!n.directed)return!0;const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;for(let u=0;u<=t;u++)if(o[u]!==e.rowPtr[u])return!1;const a=e.colIdx;for(let u=0;u<r;u++)if(s[u]!==a[u])return!1;const c=e.weights;if(i===null||c===null)return!0;if(!n.flags.multigraph){for(let u=0;u<r;u++)if(i[u]!==c[u])return!1;return!0}let l=0;for(;l<r;){let u=l+1;for(;u<r&&s[u]===s[l]&&u<o[Ob(o,t,l)+1];)u++;if(u-l===1){if(i[l]!==c[l])return!1}else if(!$b(i,c,l,u))return!1;l=u}return!0}function Ob(n,e,t){let r=0,o=e;for(;o-r>1;){const s=r+o>>>1;n[s]<=t?r=s:o=s}return r}function $b(n,e,t,r){const o=n.slice(t,r).sort(),s=e.slice(t,r).sort();for(let i=0;i<o.length;i++)if(o[i]!==s[i]&&!(Number.isNaN(o[i])&&Number.isNaN(s[i])))return!1;return!0}function Rb(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.ownedByteLength:0;case"coo":return t.src.byteLength;case"edgeList":{const r=t;let o=r.src.byteLength;return r.dst!==n.colIdx&&(o+=r.dst.byteLength),r.weights!==null&&r.weights!==n.weights&&(o+=r.weights.byteLength),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return t.byteLength;case"degreeOrder":case"reverseDegreeOrder":{const r=t;return r.perm.byteLength+r.segmentOffsets.byteLength}case"totalWeight":case"symmetric":return 0;default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Wa(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.materialised():{};case"coo":return{src:t.src};case"edgeList":{const r=t,o={src:r.src};return r.dst!==n.colIdx&&(o.dst=r.dst),r.weights!==null&&r.weights!==n.weights&&(o.weights=r.weights),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return{data:t};case"degreeOrder":case"reverseDegreeOrder":{const r=t;return{perm:r.perm,segmentOffsets:r.segmentOffsets}}case"totalWeight":case"symmetric":return{};default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Ed(n,e){return n instanceof Float64Array?new Float64Array(e):n instanceof Float32Array?new Float32Array(e):n instanceof Int32Array?new Int32Array(e):new Uint32Array(e)}function Db(n,e,t,r){const{edgeCount:o,arcCount:s}=n;if(zt("reducer",t,["first","sum","max","min"]),e.length!==s)throw new P("E_COLUMN_LENGTH",`perArc has ${e.length} entries, expected ${s}`,{expected:s,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const i=Ed(e,o),{edgeToArc:a,arcToEdge:c}=n;for(let l=0;l<o;l++)i[l]=e[a[l]];switch(t){case"first":break;case"sum":for(let l=0;l<s;l++){const u=c[l];a[u]!==l&&(i[u]+=e[l])}break;case"max":for(let l=0;l<s;l++){const u=c[l];e[l]>i[u]&&(i[u]=e[l])}break;case"min":for(let l=0;l<s;l++){const u=c[l];e[l]<i[u]&&(i[u]=e[l])}break;default:{const l=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(l)}`,{reducer:l})}}return i}function Va(n,e,t){const{edgeCount:r,arcCount:o}=n;if(e.length!==r)throw new P("E_COLUMN_LENGTH",`perEdge has ${e.length} entries, expected ${r}`,{expected:r,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const s=t??Ed(e,o),{arcToEdge:i}=n;for(let a=0;a<o;a++)s[a]=e[i[a]];return s}function ie(n,e,t={}){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function Lb(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Mb(n,e,t){let r=0;for(let o=0;o<t;o++){const s=n[o+1];for(let i=n[o];i<s;i++)e[i]===o&&r++}return r}function qr(n){for(let e=0;e<n.length;e++)if(n[e]!==e)return!1;return!0}function _d(n){const{directed:e,nodeCount:t,rowPtr:r,colIdx:o,weights:s,arcToEdge:i}=n;let a=!0,c=!0,l=!0;if(s!==null)for(let u=0;u<s.length;u++){const d=s[u];d!==1&&(a=!1),d>=0||(c=!1),Number.isFinite(d)||(l=!1)}return{multigraph:Lb(r,o,t),hasSelfLoops:n.selfLoopCount>0,arcToEdgeIsIdentity:e&&(i===null||qr(i)),weighted:s!==null,allWeightsOne:a,nonNegativeWeights:c,finiteWeights:l}}function Ub(n){const{rowPtr:e,colIdx:t,nodeCount:r,arcCount:o}=n;if(e.length!==r+1)throw ie("I1",`rowPtr has ${e.length} entries, expected ${r+1}`,{expected:r+1,found:e.length});if(e[0]!==0)throw ie("I1",`rowPtr[0] is ${e[0]}, expected 0`,{row:0,found:e[0]});for(let s=0;s<r;s++)if(e[s+1]<e[s])throw ie("I1",`rowPtr decreases at row ${s}: ${e[s]} -> ${e[s+1]}`,{row:s});if(e[r]!==o||t.length!==o)throw ie("I1",`rowPtr[${r}] = ${e[r]}, colIdx.length = ${t.length}, arcCount = ${o}`,{row:r,found:e[r],expected:o,colIdxLength:t.length})}function Fb(n){const{colIdx:e,nodeCount:t}=n;for(let r=0;r<e.length;r++)if(e[r]>=t)throw ie("I2",`colIdx[${r}] = ${e[r]} is not below nodeCount ${t}`,{arc:r,found:e[r]})}function Bb(n){const e=[["nodeCount",n.nodeCount],["edgeCount",n.edgeCount],["arcCount",n.arcCount],["selfLoopCount",n.selfLoopCount]];for(const[t,r]of e)if(!Number.isInteger(r)||r<0||r>Te)throw ie("I3",`${t} = ${r} is not an integer in [0, MAX_COUNT]`,{count:t,found:r});if(n.edgeCount>n.arcCount)throw ie("I3",`edgeCount ${n.edgeCount} exceeds arcCount ${n.arcCount}`,{edgeCount:n.edgeCount,arcCount:n.arcCount});if(n.selfLoopCount>n.edgeCount)throw ie("I3",`selfLoopCount ${n.selfLoopCount} exceeds edgeCount ${n.edgeCount}`,{selfLoopCount:n.selfLoopCount,edgeCount:n.edgeCount})}function zb(n){const{rowPtr:e,colIdx:t,nodeCount:r}=n,s=n.flags.arcToEdgeIsIdentity?null:n.arcToEdge;for(let i=0;i<r;i++){const a=e[i+1];for(let c=e[i]+1;c<a;c++){if(t[c]<t[c-1])throw ie("I4",`row ${i} is not sorted at arc ${c}`,{row:i,arc:c});if(t[c]===t[c-1]&&s!==null&&s[c]<=s[c-1])throw ie("I4",`parallel arcs ${c-1} and ${c} in row ${i} are not in edge order`,{row:i,arc:c})}}}function Gb(n){const{arcCount:e,edgeCount:t}=n;if(n.flags.arcToEdgeIsIdentity){if(!n.directed||e!==t)throw ie("I5","identity permutation claimed on a snapshot where it cannot hold",{directed:n.directed,arcCount:e,edgeCount:t});return}const{arcToEdge:r,edgeToArc:o}=n;if(r.length!==e)throw ie("I5",`arcToEdge has ${r.length} entries, expected ${e}`,{expected:e,found:r.length});if(o.length!==t)throw ie("I5",`edgeToArc has ${o.length} entries, expected ${t}`,{expected:t,found:o.length});for(let s=0;s<e;s++)if(r[s]>=t)throw ie("I5",`arcToEdge[${s}] = ${r[s]} is not below edgeCount ${t}`,{arc:s,found:r[s]});for(let s=0;s<t;s++)if(o[s]>=e)throw ie("I5",`edgeToArc[${s}] = ${o[s]} is not below arcCount ${e}`,{edge:s,found:o[s]})}function Wb(n){if(n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:e,edgeToArc:t,edgeCount:r}=n;for(let o=0;o<r;o++)if(e[t[o]]!==o)throw ie("I5",`arcToEdge[edgeToArc[${o}]] = ${e[t[o]]}, expected ${o}`,{edge:o,arc:t[o]})}function Id(n,e){if(!n.directed)return;const{arcCount:t,edgeCount:r}=n;if(t!==r)throw ie("I6",`directed snapshot has arcCount ${t} but edgeCount ${r}`,{arcCount:t,edgeCount:r});if(!e||n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:o}=n,s=new Uint8Array(r);for(let i=0;i<t;i++){const a=o[i];if(a>=r||s[a]===1)throw ie("I6",`edge ${a} appears more than once in arcToEdge (arc ${i})`,{arc:i,edge:a});s[a]=1}}function Vb(n){if(n.directed)return;const e=2*n.edgeCount-n.selfLoopCount;if(n.arcCount!==e)throw ie("I7",`undirected snapshot has arcCount ${n.arcCount}, expected 2 * ${n.edgeCount} - ${n.selfLoopCount} = ${e}`,{arcCount:n.arcCount,expected:e})}function jb(n){if(n.directed)return;const{nodeCount:e,arcCount:t,edgeCount:r,rowPtr:o,colIdx:s,weights:i,arcToEdge:a}=n,c=new Uint8Array(r);for(let u=0;u<t;u++){const d=a[u];if(c[d]===2)throw ie("I7",`edge ${d} appears more than twice in arcToEdge (arc ${u})`,{arc:u,edge:d});c[d]++}const l=o.slice(0,e);for(let u=0;u<e;u++){const d=o[u+1];let f=l[u];if(f<o[u]||f>d)throw ie("I7",`row ${u} was over-consumed by mates from earlier rows`,{row:u});for(;f<d;){const h=s[f];let g=f+1;for(;g<d&&s[g]===h;)g++;const w=g-f;if(h===u){for(let p=f;p<g;p++)if(c[a[p]]!==1)throw ie("I7",`self-loop edge ${a[p]} has more than one arc`,{row:u,arc:p,edge:a[p]})}else{if(h<u)throw ie("I7",`arc ${f} in row ${u} targets ${h} but row ${h} holds no mate`,{row:u,arc:f,target:h});const p=l[h],m=o[h+1];for(let y=0;y<w;y++){const b=f+y,v=p+y;if(v>=m||s[v]!==u)throw ie("I7",`arc ${b} in row ${u} targeting ${h} has no mate in row ${h}`,{row:u,arc:b,target:h});if(a[v]!==a[b])throw ie("I7",`arcs ${b} and ${v} should share a logical edge but hold ${a[b]} and ${a[v]}`,{row:u,arc:b,mate:v});if(c[a[b]]!==2)throw ie("I7",`edge ${a[b]} of arc ${b} does not have two arcs`,{row:u,arc:b,edge:a[b]});if(i!==null&&i[b]!==i[v])throw ie("I7",`arcs ${b} and ${v} carry different weights ${i[b]} and ${i[v]}`,{row:u,arc:b,mate:v})}if(p+w<m&&s[p+w]===u)throw ie("I7",`row ${h} holds more arcs to ${u} than row ${u} holds to ${h}`,{row:h,arc:p+w,target:u});l[h]=p+w}f=g}l[u]=d}}function qb(n){const{weights:e,arcCount:t}=n;if(e!==null&&e.length!==t)throw ie("I8",`weights has ${e.length} entries, expected ${t}`,{expected:t,found:e.length})}function Hb(n){const{weights:e}=n;if(e!==null){for(let t=0;t<e.length;t++)if(Number.isNaN(e[t]))throw ie("I8",`weights[${t}] is NaN`,{arc:t})}}function Kb(n){const e=Mb(n.rowPtr,n.colIdx,n.nodeCount);if(e!==n.selfLoopCount)throw ie("I9",`selfLoopCount is ${n.selfLoopCount} but ${e} loop arcs exist`,{reason:"selfLoopCount",expected:e,found:n.selfLoopCount});const t=_d({directed:n.directed,nodeCount:n.nodeCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:n.flags.arcToEdgeIsIdentity?null:n.arcToEdge,selfLoopCount:n.selfLoopCount}),r=["multigraph","hasSelfLoops","arcToEdgeIsIdentity","weighted","allWeightsOne","nonNegativeWeights","finiteWeights"];for(const o of r)if(n.flags[o]!==t[o])throw ie("I9",`flag ${o} is ${n.flags[o]} but the arrays say ${t[o]}`,{flag:o,found:n.flags[o],expected:t[o]})}function Yb(n,e,t){const r=n.segments[e];if(r===null)return;if(t===null)throw ie("I10",`arena names a segment for absent core array ${e}`,{array:e});const o=r.byteOffset-n.byteOffset;if(o<0||o%ft!==0||o+r.byteLength>n.byteLength)throw ie("I10",`arena segment ${e} at ${r.byteOffset} is not 256-aligned inside the arena`,{array:e,byteOffset:r.byteOffset});if(t.buffer!==n.buffer||t.byteOffset!==r.byteOffset||t.byteLength!==r.byteLength)throw ie("I10",`core array ${e} is not the view its arena segment describes`,{array:e,byteOffset:t.byteOffset,byteLength:t.byteLength})}function Xb(n,e){if(!j0(e))throw ie("I10",`core array ${n} is not 4-byte aligned`,{array:n,byteOffset:e.byteOffset,byteLength:e.byteLength});if(!pa(e))throw ie("I10",`core array ${n} is not a view over a plain ArrayBuffer`,{array:n,reason:"buffer"})}function Qb(n){const e=n.flags.arcToEdgeIsIdentity,t=[["rowPtr",n.rowPtr],["colIdx",n.colIdx],["weights",n.weights],["arcToEdge",e?null:n.arcToEdge],["edgeToArc",e?null:n.edgeToArc]];for(const[i,a]of t)a!==null&&Xb(i,a);const{arena:r}=n;if(r===null)return;const{alignment:o}=r;if(o!==ft)throw ie("I10",`arena alignment is ${o}, expected ${ft}`,{found:o});for(const[i,a]of t)Yb(r,i,a);let s=0;for(const i of["rowPtr","colIdx","weights"]){const a=r.segments[i];a!==null&&(s=a.byteOffset+a.byteLength-r.byteOffset)}if(r.hotByteLength!==s)throw ie("I10",`arena.hotByteLength is ${r.hotByteLength}, expected ${s}`,{reason:"hotByteLength",found:r.hotByteLength,expected:s})}function Jb(n){if(n.ids.size!==n.nodeCount)throw ie("I11",`ids.size is ${n.ids.size}, expected nodeCount ${n.nodeCount}`,{expected:n.nodeCount,found:n.ids.size})}function Zb(n){const{ids:e,nodeCount:t}=n;for(let r=0;r<t;r++){const o=e.idOf(r);if(typeof o=="number"&&Number.isNaN(o))throw ie("I11",`id of node ${r} is NaN`,{index:r});const s=e.indexOf(o);if(s!==r)throw ie("I11",`ids.indexOf(ids.idOf(${r})) is ${s}`,{index:r,found:s})}}function Ke(n,e,t,r={}){return ie("I12",`column "${e.meta.name}" of table ${n}: ${t}`,{table:n,column:e.meta.name,...r})}function kd(n,e,t,r,o){if(t.length!==r+1)throw Ke(n,e,`offsets has ${t.length} entries, expected ${r+1}`,{expected:r+1,found:t.length});if(t[0]!==0)throw Ke(n,e,`offsets[0] is ${t[0]}`,{row:0});for(let s=0;s<r;s++)if(t[s+1]<t[s])throw Ke(n,e,`offsets decrease at row ${s}`,{row:s});if(t[r]!==o)throw Ke(n,e,`offsets[${r}] is ${t[r]}, expected ${o}`,{row:r,found:t[r],expected:o})}function Sd(n,e,t,r,o,s){for(let i=0;i<t.length;i++){const a=t[i];if(a===x){const c=Math.floor(i/r);if(s!==void 0&&(s===null||Le(s,c)))throw Ke(n,e,`row ${c} is set but holds INVALID_INDEX`,{row:c});continue}if(a>=o)throw Ke(n,e,`value ${a} at ${i} is not below ${o}`,{row:Math.floor(i/r),found:a,expected:o})}}function Pd(n,e,t){switch(e.dtype){case"u32":Sd(n,e,e.data,e.meta.components,t,e.validity);return;case"list":{const{child:r}=e;if(r.dtype!=="u32")throw Ke(n,e,`refersTo list requires a u32 child, found ${r.dtype}`);Sd(n,e,r.data,1,t,void 0);return}default:throw Ke(n,e,`refersTo requires dtype u32, found ${e.dtype}`)}}function xd(n){switch(n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return[["data",n.data],["validity",n.validity]];case"dict":return[["codes",n.codes],["validity",n.validity]];case"string":return[["offsets",n.offsets],["utf8",n.utf8],["validity",n.validity]];case"list":return[["offsets",n.offsets],["validity",n.validity],...xd(n.child).map(([e,t])=>[`child.${e}`,t])];case"json":return[["validity",n.validity]];default:throw ie("I12",`unknown dtype ${n.dtype}`)}}function e1(n,e,t,r){if(e.length!==t)throw Ke(n,e,`has ${e.length} rows, expected ${t}`,{expected:t,found:e.length});const{validity:o,meta:s}=e,i=Math.ceil(t/32);if(o!==null&&o.length!==i)throw Ke(n,e,`validity has ${o.length} words, expected ${i}`,{expected:i,found:o.length});const a=o===null?0:t-gr(o,t);if(e.nullCount!==a)throw Ke(n,e,`nullCount is ${e.nullCount}, the validity bitmap says ${a}`,{expected:a,found:e.nullCount,reason:"nullCount"});for(const[u,d]of xd(e))if(d!==null&&!pa(d))throw Ke(n,e,`${u} is not a view over a plain ArrayBuffer`,{array:u,reason:"buffer"});const c=s.refersTo==="node"?r.nodeCount:r.edgeCount,{dtype:l}=e;switch(l){case"f32":case"f64":case"i32":case"u32":case"u8":{const u=t*s.components;if(e.data.length!==u)throw Ke(n,e,`data has ${e.data.length} values, expected ${u}`,{expected:u,found:e.data.length});s.refersTo!==null&&Pd(n,e,c);break}case"bool":if(e.data.length!==i)throw Ke(n,e,`bool data has ${e.data.length} words, expected ${i}`,{expected:i,found:e.data.length});break;case"dict":{if(e.codes.length!==t)throw Ke(n,e,`codes has ${e.codes.length} entries, expected ${t}`,{expected:t,found:e.codes.length});const u=e.dictionary.length;for(let d=0;d<t;d++)if(e.codes[d]>=u&&(o===null||Le(o,d)))throw Ke(n,e,`code ${e.codes[d]} at row ${d} is not below ${u}`,{row:d,found:e.codes[d]});break}case"string":kd(n,e,e.offsets,t,e.utf8.length);break;case"list":{const{child:u}=e;if(kd(n,e,e.offsets,t,u.length),u.validity!==null)throw Ke(n,e,"list child column has a validity bitmap");s.refersTo!==null&&Pd(n,e,c);break}case"json":if(e.values.length!==t)throw Ke(n,e,`values has ${e.values.length} entries, expected ${t}`,{expected:t,found:e.values.length});break;default:throw Ke(n,e,`unknown dtype ${String(l)}`)}}function Cd(n,e,t,r){for(const o of e)e1(n,o,t,r)}function t1(n){const e=[["nodes",n.nodes,n.nodeCount],["edges",n.edges,n.edgeCount],["graph",n.graph,1]];for(const[t,r,o]of e){if(r.rowCount!==o)throw ie("I12",`table ${t} has ${r.rowCount} rows, expected ${o}`,{table:t,expected:o,found:r.rowCount});Cd(t,r,o,n)}for(const[t,r]of n.extensions)Cd(`extensions[${t}]`,r,r.rowCount,n)}function n1(n){if(n.edges.rowCount!==n.edgeCount)throw ie("I13",`edge table has ${n.edges.rowCount} rows, expected edgeCount ${n.edgeCount}`,{expected:n.edgeCount,found:n.edges.rowCount})}function Nd(n){Bb(n),Ub(n),Fb(n),Gb(n),Id(n,!1),Vb(n),qb(n),Qb(n),Jb(n),n1(n),t1(n)}function r1(n){Nd(n),zb(n),Wb(n),Id(n,!0),Hb(n),jb(n),Kb(n),Zb(n);const e=[["nodes",n.nodes],["edges",n.edges],["graph",n.graph],...[...n.extensions].map(([t,r])=>[`extensions[${t}]`,r])];for(const[t,r]of e)for(const o of r)o1(t,o)}function o1(n,e){try{ud(e)}catch(t){throw t instanceof P&&(t.code==="E_DUPLICATE_ID"||t.code==="E_DUPLICATE_EDGE_ID")?Ke(n,e,t.message,{...t.details,reason:"unique",cause:t.code}):t}}class s1{constructor(e){const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,directed:i}=e,a=new Uint32Array(r),c=new Uint32Array(t),l=i?new Uint32Array(t):Ar(o,t);for(let u=0;u<t;u++){const d=o[u+1];for(let f=o[u];f<d;f++){a[f]=u;const h=s[f];h===u&&c[u]++,i&&l[h]++}}this.arcRow=a,this.loops=c,this.inDegree=l}inDegreePrefix(){const e=this.inDegree.length,t=new Uint32Array(e+1);for(let r=0;r<e;r++)t[r+1]=t[r]+this.inDegree[r];return t}}function Ot(n,e,t,r){return ie(r,`carried view ${n}.${e} disagrees with the core at ${t}`,{view:n,member:e,index:t,reason:"view"})}function Er(n,e,t,r,o){for(let s=0;s<r.length;s++)if(!Object.is(t[s],r[s])&&t[s]!==r[s])throw Ot(n,e,s,o)}function Td(n,e,t){const r=new Uint8Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s>=t.length||r[s]===1)throw Ot(n,e,o,"I2");r[s]=1}}function i1(n,e){Er("outDegree","data",e,Ar(n.rowPtr,n.nodeCount),"I2")}function a1(n,e){Er("inDegree","data",e,n.inDegree,"I2")}function c1(n,e,t){const r=Ar(n.rowPtr,n.nodeCount),o=n.directed?e.inDegree:e.loops;for(let s=0;s<r.length;s++)if(t[s]!==r[s]+o[s])throw Ot("degree","data",s,"I2")}function l1(n,e){Er("selfLoopsPerNode","data",e,n.loops,"I2")}function u1(n,e,t){const{colIdx:r,arcCount:o}=n;for(let s=0;s<t.length;s++){const i=t[s];if(i>=o||r[i]!==e.arcRow[i]||s>0&&i<=t[s-1])throw Ot("selfLoopArcs","data",s,"I2")}}function d1(n,e){Er("coo","src",e,n.arcRow,"I2")}function f1(n,e,t,r,o){const{edgeCount:s,edgeToArc:i,colIdx:a,arcCount:c}=n,l=n.weights;for(let u=0;u<s;u++){const d=i[u];if(d>=c||t[u]!==e.arcRow[d])throw Ot("edgeList","src",u,"I2");if(r!==null&&r[u]!==a[d])throw Ot("edgeList","dst",u,"I2");if(o!==null&&l!==null&&!Object.is(o[u],l[d]))throw Ot("edgeList","weights",u,"I17")}}function h1(n,e,t){const{arcCount:r,arcToEdge:o,colIdx:s}=n;for(let i=0;i<r;i++){const a=t[i],c=s[i]===e.arcRow[i];if(a>=r||t[a]!==i||o[a]!==o[i]||a===i!==c)throw Ot("mate","data",i,"I2")}}function g1(n,e,t,r){Td(n,"perm",t);let o=0,s=0,i=0;for(let c=0;c<t.length;c++){const l=e[t[c]];if(c>0){const u=e[t[c-1]];if(l>u||l===u&&t[c]<t[c-1])throw Ot(n,"perm",c,"I2")}l>=wd?o++:l>=pd?s++:l>=1&&i++}const a=[0,o,o+s,o+s+i,t.length];Er(n,"segmentOffsets",r,a,"I2")}function w1(n,e,t,r,o){const s=n[t-1],i=e[s];if(o<i||o===i&&r<=s)throw Ot("reverse","fwdArc",t,"I2")}function p1(n,e,t){const{nodeCount:r,arcCount:o,colIdx:s}=n,i=n.weights,{rowPtr:a,fwdArc:c}=t,l=t.colIdx,u=t.weights;if(a[0]!==0||a[r]!==o)throw Ot("reverse","rowPtr",0,"I2");Er("reverse","rowPtr",a,e.inDegreePrefix(),"I2"),Td("reverse","fwdArc",c);for(let d=0;d<r;d++){const f=a[d+1];for(let h=a[d];h<f;h++){const g=c[h],w=e.arcRow[g];if(s[g]!==d||l[h]!==w)throw Ot("reverse","colIdx",h,"I2");if(h>a[d]&&w1(c,e.arcRow,h,g,w),u!==null&&i!==null&&!Object.is(u[h],i[g]))throw Ot("reverse","weights",h,"I17")}}}function m1(n,e,t){Er(n,"data",e,t,"I17")}const y1="@graphty/graph-format@4e2e91d4b533",b1=new Set(["totalWeight","symmetric"]),v1=new TextEncoder;function A1(n=Eu){if(!n)throw new P("E_UNSUPPORTED","the wire format cannot be written on a big-endian host",{reason:"big-endian host"})}const Yo="$num",Od="$esc";function E1(n){return Number.isNaN(n)?{[Yo]:"NaN"}:n===1/0?{[Yo]:"Infinity"}:n===-1/0?{[Yo]:"-Infinity"}:Object.is(n,-0)?{[Yo]:"-0"}:n}function qn(n){if(typeof n=="number")return E1(n);if(Array.isArray(n))return n.map(e=>qn(e));if(kn(n)){const e=Object.keys(n),t={};for(const r of e)$d(t,r,qn(n[r]));return e.length===1&&(e[0]===Yo||e[0]===Od)?{[Od]:t}:t}return n}function $d(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}class ja{constructor(e,t=!1){this.buffers=[],this.copied=[],this.segments=[],this.bufferIndex=new Map,this.placed=new Map,this.cursor=0,this.mode=e,this.transfer=t}get regionLength(){return hr(this.cursor,ft)}indexOf(e){return this.bufferIndex.get(e)??null}ref(e,t,r=!1){if(r&&Gn(e.buffer),this.mode==="reference")return{buffer:this.bufferIndexOf(e.buffer),byteOffset:e.byteOffset,byteLength:e.byteLength,dtype:t,length:e.length};const o=`${this.bufferIndexOf(e.buffer)}:${e.byteOffset}:${e.byteLength}:${t}`,s=this.placed.get(o);if(s!==void 0)return s;const i=hr(this.cursor,ft);this.cursor=i+e.byteLength;const a={buffer:0,byteOffset:i,byteLength:e.byteLength,dtype:t,length:e.length};return this.placed.set(o,a),this.segments.push({view:e,ref:a}),a}finalise(){if(!(this.mode!=="reference"||!this.transfer))for(let e=0;e<this.buffers.length;e++){const t=this.buffers[e];Fr(t)&&(this.buffers[e]=t.slice(0),this.copied.push(e))}}bufferIndexOf(e){const t=this.bufferIndex.get(e);if(t!==void 0)return t;const r=this.buffers.length;return this.bufferIndex.set(e,r),this.buffers.push(e),r}}function qa(n){return n instanceof Uint32Array?"u32":n instanceof Int32Array?"i32":n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":"u8"}const Rd=new WeakMap,Dd=new WeakMap;function Ld(n,e){return n.offsets.length===e+1}function _1(n){const e=Rd.get(n);if(e!==void 0&&Ld(e,n.length))return e;const t=Do(n,n.length);return Rd.set(n,t),t}function I1(n){const e=Dd.get(n);if(e?.version===n.version&&Ld(e.encoded,n.length))return e.encoded;const t=new Array(n.length);for(let o=0;o<n.length;o++){const s=n.values[o];t[o]=s===void 0||!n.isSet(o)?"":JSON.stringify(qn(s))}const r=Do(t,t.length);return Dd.set(n,{version:n.version,encoded:r}),r}function Md(n,e,t){return{offsets:n.ref(e.offsets,"u32",t),utf8:n.ref(e.utf8,"utf8",t)}}function k1(n){return{name:n.name,domain:n.domain,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype,itemComponents:n.itemComponents,nullable:n.nullable,mutable:n.mutable,role:n.role,refersTo:n.refersTo,unique:n.unique,default:qn(n.default),fill:qn(n.fill),options:n.options===null?null:qn(n.options),origin:n.origin===null?null:{...n.origin},dynamic:n.dynamic,extra:qn(n.extra)}}function Ud(n,e,t){const r=t||Fr(e),o={meta:k1(e.meta),data:null,validity:e.validity===null?null:n.ref(e.validity,"u32",r),nullCount:e.nullCount,dictionary:null,strings:null,offsets:null,child:null,jsonText:null},{dtype:s}=e;switch(s){case"f32":case"f64":case"i32":case"u32":case"u8":o.data=n.ref(e.data,s,r);break;case"bool":o.data=n.ref(e.data,"u32",r);break;case"dict":o.data=n.ref(e.codes,"u32",r),o.dictionary=Md(n,_1(e.dictionary),r);break;case"string":o.strings={offsets:n.ref(e.offsets,"u32",r),utf8:n.ref(e.utf8,"utf8",r)};break;case"list":o.offsets=n.ref(e.offsets,"u32",r),o.child=Ud(n,e.child,r);break;case"json":o.jsonText=Md(n,I1(e),r);break;default:{const i=s;throw new P("E_UNSUPPORTED",`unknown dtype ${i}`,{dtype:i})}}return o}function Hs(n,e){const t=[],r=Fr(e);for(const o of e)t.push(Ud(n,o,r));return t}function S1(n,e){const{ids:t}=e;if(!(t instanceof Yt))throw new P("E_UNSUPPORTED","the snapshot's id map is not a NodeIdMap of this package",{reason:"foreign id map"});const r=zy(t),o=Fr(t);return{kind:r.kind,size:r.size,offset:r.offset,values:r.values===null?null:n.ref(r.values,qa(r.values),o),tags:r.tags===null?null:n.ref(r.tags,"u8",o),numbers:r.numbers===null?null:n.ref(r.numbers,"f64",o),offsets:r.offsets===null?null:n.ref(r.offsets,"u32",o),utf8:r.utf8===null?null:n.ref(r.utf8,"utf8",o)}}function P1(n){return{name:n.name,description:n.description,creator:n.creator,created:n.created,modified:n.modified,keywords:[...n.keywords],sourceFormat:n.sourceFormat,sourceVersion:n.sourceVersion,idType:n.idType,timeFormat:n.timeFormat,timeRepresentation:n.timeRepresentation,mode:n.mode,declaredMultigraph:n.declaredMultigraph,weightOrigin:n.weightOrigin===null?null:{...n.weightOrigin},extra:qn(n.extra)}}function x1(n,e,t){if(t===void 0||t.length===0)return null;const r={};let o=0;for(const s of new Set(t)){if(b1.has(s))continue;const i=_v(e,s);if(i===null)continue;const a={};let c=!1;for(const[l,u]of Object.entries(Wa(e,s,i))){const d=u;a[l]=n.ref(d,qa(d)),c=!0}c&&(r[s]=a,o++)}return o===0?null:r}function Ha(n,e,t,r=!0){A1();const o=n.flags.arcToEdgeIsIdentity,s={rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:o?null:n.arcToEdge,edgeToArc:o?null:n.edgeToArc},i={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null},a=e.ref(n.rowPtr,"u32");i.rowPtr=a;for(const p of Ho){const m=s[p];p!=="rowPtr"&&m!==null&&m.length>0&&(i[p]=e.ref(m,qa(m)))}const c=C1(n,e,i),l=S1(e,n),u=r?Hs(e,n.nodes):[],d=r?Hs(e,n.edges):[],f=r?Hs(e,n.graph):[],h=[];if(r)for(const[p,m]of n.extensions)h.push({name:p,rowCount:m.rowCount,columns:Hs(e,m)});const g=x1(e,n,t);return e.finalise(),{manifest:{format:la,wire:[zn,_u],producer:y1,formatVersion:Mr,directed:n.directed,counts:{nodes:n.nodeCount,edges:n.edgeCount,arcs:n.arcCount,selfLoops:n.selfLoopCount},flags:{...n.flags},core:{rowPtr:a,colIdx:i.colIdx,weights:i.weights,arcToEdge:i.arcToEdge,edgeToArc:i.edgeToArc},arena:c,ids:l,nodeColumns:u,edgeColumns:d,graphColumns:f,extensions:h,meta:P1(n.meta),views:g,copied:e.copied,label:n.label},layout:e}}function C1(n,e,t){if(e.mode==="container"){let s=0,i=0;for(const a of Ho){const c=t[a];c!==null&&(s=c.byteOffset+c.byteLength,(a==="rowPtr"||a==="colIdx"||a==="weights")&&(i=s))}return{buffer:0,byteOffset:0,byteLength:s,hotByteLength:i}}const{arena:r}=n;if(r===null)return null;const o=e.indexOf(r.buffer);return o===null?null:{buffer:o,byteOffset:r.byteOffset,byteLength:r.byteLength,hotByteLength:r.hotByteLength}}function N1(n,e={}){const t=e.transfer===!0,r=new ja("reference",t),{manifest:o}=Ha(n,r,e.includeViews,e.includeColumns!==!1);return t&&Fd.set(n,[...r.buffers]),{manifest:o,buffers:r.buffers}}const Fd=new WeakMap;function T1(n){const e=Fd.get(n);if(e!==void 0)return[...e];const t=new ja("reference",!1);return Ha(n,t,void 0,!0),t.buffers.filter(r=>!Fr(r))}function O1(n){return v1.encode(JSON.stringify(n))}const $1=new Set(["u32","i32","f32","f64","u8","utf8"]),R1=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),D1=new Set(["identity","dense","numeric","string","mixed"]),L1=new Set(["string","integer","mixed"]),M1=new Set(["integer","double","date","dateTime"]),U1=new Set(["interval","timestamp"]),F1=new Set(["static","dynamic","slice"]),Bd=new Set(["__proto__","constructor","prototype"]),zd="$num",Gd="$esc",Wd=256;function Hr(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):n===void 0?"undefined":`a ${typeof n}`}const B1="graphty.skippedColumns";function re(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function vt(n,e){if(!kn(n))throw re(e,"expected an object");return n}function Ks(n,e){if(!Array.isArray(n))throw re(e,"expected an array");return n}function Xo(n,e){if(typeof n!="string")throw re(e,"expected a string");return n}function Cn(n,e){return n==null?null:Xo(n,e)}function _r(n,e){if(typeof n!="boolean")throw re(e,"expected a boolean");return n}function z1(n,e){return n==null?null:_r(n,e)}function Nn(n,e){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>Te)throw re(e,`expected an integer in [0, ${Te}]`,{found:n});return n===0?0:n}function Ys(n,e,t){if(n==null)return null;if(typeof n!="string"||!t.has(n))throw re(e,`unexpected value ${Hr(n)}`,{found:n});return n}function Vd(n){return typeof n=="string"&&R1.has(n)}function Hn(n,e,t=0){if(t>Wd)throw re(e,`JSON nesting deeper than ${Wd}`,{reason:"nesting"});if(Array.isArray(n))return n.map((o,s)=>Hn(o,`${e}[${s}]`,t+1));if(!kn(n))return n;const r=Object.keys(n);if(r.length===1&&r[0]===zd){const o=n[zd];switch(o){case"NaN":return Number.NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;case"-0":return-0;default:throw re(e,`unknown number tag ${Hr(o)}`,{found:o})}}if(r.length===1&&r[0]===Gd){const o=n[Gd];if(!kn(o))throw re(e,"an escaped object must hold a plain object",{found:typeof o});return jd(o,e,t)}return jd(n,e,t)}function jd(n,e,t){const r={};for(const o of Object.keys(n)){if(Bd.has(o))throw re(e,`forbidden key "${o}"`,{key:o});$d(r,o,Hn(n[o],`${e}.${o}`,t+1))}return r}function G1(n){const e=[n];for(;e.length>0;){const t=e.pop();if(Array.isArray(t))for(const r of t)e.push(r);else if(typeof t=="object"&&t!==null)for(const r of Object.keys(t)){if(Bd.has(r))throw re("manifest",`forbidden key "${r}"`,{key:r});e.push(t[r])}}}function qd(n,e){let t;try{t=JSON.parse(n)}catch(r){throw re(e,`not valid JSON (${r instanceof Error?r.message:String(r)})`)}return G1(t),t}function W1(n,e){return{level:e,copy:!1,unknownColumns:"error"}}function Hd(n,e,t){return{byteLength:t,locate(r){return{buffer:n,byteOffset:e+r}},read(r,o){const s=new Uint8Array(new ArrayBuffer(Mo(o)),0,o);return s.set(new Uint8Array(n,e+r,o)),s}}}function V1(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function j1(n){switch(n){case"u32":case"i32":case"f32":return 4;case"f64":return 8;case"u8":case"utf8":return 1;default:{const e=n;throw re("dtype",`unknown wire dtype ${e}`,{dtype:e})}}}function Kd(n,e,t,r){switch(n){case"u32":return new Uint32Array(e,t,r);case"i32":return new Int32Array(e,t,r);case"f32":return new Float32Array(e,t,r);case"f64":return new Float64Array(e,t,r);case"u8":case"utf8":return new Uint8Array(e,t,r);default:{const o=n;throw re("dtype",`unknown wire dtype ${o}`,{dtype:o})}}}function Xs(n,e){const t=vt(n,e),{dtype:r}=t;if(typeof r!="string"||!$1.has(r))throw re(e,`unknown wire dtype ${Hr(r)}`,{found:r});const o=["buffer","byteOffset","byteLength","length"];for(const s of o){const i=t[s];if(typeof i!="number"||!Number.isInteger(i)||i<0)throw re(`${e}.${s}`,"expected a non-negative integer",{found:i})}return{buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,dtype:r,length:t.length}}function Ka(n,e){return n instanceof P&&(n.code.startsWith("E_COLUMN")||n.code==="E_DUPLICATE_ROLE")?new P("E_BAD_SERIALIZATION",`${e}: ${n.message}`,{ref:e,reason:n.message,cause:n.code,...n.details}):n instanceof Error?n:re(e,String(n))}class q1{constructor(e,t){this.ranges=[],this.skipped=[],this.regions=e,this.options=t}get structure(){return this.options.level!=="none"}get full(){return this.options.level==="full"}array(e,t,r,o){const s=Xs(e,t);if(s.dtype!==r)throw re(t,`expected dtype ${r}, found ${s.dtype}`,{expected:r,found:s.dtype});const i=this.regions[s.buffer];if(i===void 0)throw re(t,`buffer index ${s.buffer} is out of range (${this.regions.length} buffers)`,{found:s.buffer,buffers:this.regions.length});const a=j1(s.dtype);if(s.byteOffset%a!==0)throw re(t,`byteOffset ${s.byteOffset} is not a multiple of ${a}`,{byteOffset:s.byteOffset,elementSize:a});if(s.byteLength!==s.length*a)throw re(t,`byteLength ${s.byteLength} is not length ${s.length} * ${a}`,{byteLength:s.byteLength,length:s.length,elementSize:a});if(s.byteOffset+s.byteLength>i.byteLength)throw re(t,`range [${s.byteOffset}, ${s.byteOffset+s.byteLength}) exceeds the buffer`,{byteOffset:s.byteOffset,byteLength:s.byteLength,bufferByteLength:i.byteLength});const c=i.locate(s.byteOffset,s.byteLength);if(c!==null&&c.byteOffset%a===0)return this.ranges.push({buffer:c.buffer,start:c.byteOffset,end:c.byteOffset+s.byteLength,kind:o,path:t}),Kd(s.dtype,c.buffer,c.byteOffset,s.length);const l=i.read(s.byteOffset,s.byteLength);return Kd(s.dtype,l.buffer,0,s.length)}u32(e,t,r){return this.array(e,t,"u32",r)}utf8(e,t,r,o,s=!1){const i=vt(e,t),a=this.u32(i.offsets,`${t}.offsets`,o),c=this.array(i.utf8,`${t}.utf8`,"utf8",o);if(a.length===0)throw re(`${t}.offsets`,"a Utf8 store needs at least one offset");if((this.structure||s)&&ha(a,c,r??a.length-1,t),this.full){const l=Wn.fromEncoded(a,c).firstMalformedRow();if(l!==-1)throw re(t,`malformed UTF-8 in row ${l}`,{row:l})}return{offsets:a,utf8:c}}checkOverlaps(){const e=this.ranges.filter(t=>(t.kind==="core"||t.kind==="immutable")&&t.end>t.start);for(const t of this.ranges)if(!(t.kind!=="mutable"||t.end===t.start)){for(const r of e)if(r.buffer===t.buffer&&t.start<r.end&&r.start<t.end)throw re(t.path,`mutable column overlaps ${r.path}`,{overlaps:r.path})}}column(e,t,r,o,s){const i=vt(e,s),a=vt(i.meta,`${s}.meta`),c=Xo(a.name,`${s}.meta.name`);if(this.skipUnknownDtype(a,c,t,r,s))return null;const l=this.columnMeta(a,c,t,s),u=l.mutable?"mutable":"immutable",d=Gr(l,o,i.validity===null||i.validity===void 0?null:this.u32(i.validity,`${s}.validity`,u)),f=i.nullCount;switch(l.dtype){case"f32":case"f64":case"i32":case"u32":d.data=this.array(i.data,`${s}.data`,l.dtype,u);break;case"u8":{const g=this.array(i.data,`${s}.data`,"u8",u);d.data=Ds(g)?g:H0(g);break}case"bool":d.data=this.u32(i.data,`${s}.data`,u);break;case"dict":{d.data=this.u32(i.data,`${s}.data`,u);const g=this.utf8(i.dictionary,`${s}.dictionary`,null,u,!0);d.dictionary=fa(g.utf8,g.offsets,0,g.offsets.length-1);break}case"string":{const g=this.utf8(i.strings,`${s}.strings`,o,u);d.offsets=g.offsets,d.utf8=g.utf8;break}case"list":{const g=this.u32(i.offsets,`${s}.offsets`,u);if(g.length!==o+1)throw re(`${s}.offsets`,`expected ${o+1} offsets, found ${g.length}`,{expected:o+1,found:g.length});d.offsets=g;const w=this.column(i.child,t,r,g[o],`${s}.child`);if(w===null||w.dtype==="list")throw re(`${s}.child`,"a list column needs a non-list child column");d.child=w;break}case"json":d.values=this.jsonRows(i.jsonText,o,`${s}.jsonText`,u);break;default:{const g=l.dtype;throw re(`${s}.meta.dtype`,`unknown dtype ${g}`,{dtype:g})}}let h;try{h=Tt(d)}catch(g){throw Ka(g,s)}if(this.structure&&h.nullCount!==f)throw re(`${s}.nullCount`,`manifest says ${String(f)}, the bitmap says ${h.nullCount}`,{expected:h.nullCount,found:f});return h}skipUnknownDtype(e,t,r,o,s){const{dtype:i,itemDtype:a}=e;if(!(!Vd(i)||i==="list"&&!Vd(a)))return!1;const l=i==="list"?a:i;if(this.options.unknownColumns==="skip")return this.skipped.push({domain:r,table:o,name:t,dtype:String(l)}),!0;throw new P("E_UNSUPPORTED",`column "${t}" has unknown dtype ${String(l)}`,{dtype:l,column:t,ref:s})}columnMeta(e,t,r,o){const s=`${o}.meta`,i=(l,u)=>{const d=e[l];return d==null?void 0:u(d,`${s}.${l}`)},a=(l,u)=>{if(typeof l!="number")throw re(u,"expected a number",{found:l});return l},c={name:t,dtype:e.dtype,components:i("components",a),itemDtype:i("itemDtype",l=>l),itemComponents:i("itemComponents",a),nullable:i("nullable",_r),mutable:i("mutable",_r),role:i("role",Xo),refersTo:i("refersTo",l=>l),unique:i("unique",_r),default:Hn(e.default,`${s}.default`),fill:Hn(e.fill,`${s}.fill`),options:i("options",(l,u)=>Hn(l,u)),origin:i("origin",l=>l),dynamic:i("dynamic",_r),extra:i("extra",(l,u)=>Hn(l,u))};try{return ht(t,r,c)}catch(l){throw Ka(l,o)}}jsonRows(e,t,r,o){const s=this.utf8(e,r,t,o,!0),i=fa(s.utf8,s.offsets,0,t),a=new Array(t);for(let c=0;c<t;c++){const l=i[c];a[c]=l===""?void 0:Hn(qd(l,`${r}[${c}]`),`${r}[${c}]`)}return a}table(e,t,r,o,s){const i=Ks(e,s),a=[],c=new Set;for(let l=0;l<i.length;l++){const u=this.column(i[l],t,r,o,`${s}[${l}]`);if(u!==null){if(c.has(u.meta.name))throw re(`${s}[${l}].meta.name`,`column "${u.meta.name}" is declared twice`,{column:u.meta.name});c.add(u.meta.name),a.push(u)}}try{return new wn({domain:t,rowCount:o,columns:a})}catch(l){throw Ka(l,s)}}ids(e){const t=vt(e,"ids"),r=t.kind;if(typeof r!="string"||!D1.has(r))throw new P("E_UNSUPPORTED",`unknown id map kind ${Hr(r)}`,{kind:r,ref:"ids.kind"});const o=r,s=Nn(t.size,"ids.size"),i=t.offset??0;if(typeof i!="number")throw re("ids.offset","expected a number",{found:i});const c={kind:o,size:s,offset:o==="identity"?i:0,values:null,tags:null,numbers:null,offsets:null,utf8:null};switch(o){case"identity":break;case"dense":c.values=this.u32(t.values,"ids.values","immutable");break;case"numeric":c.values=this.array(t.values,"ids.values","f64","immutable");break;case"string":{c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}case"mixed":{c.tags=this.array(t.tags,"ids.tags","u8","immutable"),c.numbers=this.array(t.numbers,"ids.numbers","f64","immutable"),c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}default:{const l=o;throw new P("E_UNSUPPORTED",`unknown id map kind ${l}`,{kind:l})}}return $y(c,this.options.level)}views(e){const t=new Map;if(e==null)return t;const r=vt(e,"views");for(const o of Object.keys(r)){const s=vt(r[o],`views.${o}`),i=new Map;for(const a of Object.keys(s)){const c=`views.${o}.${a}`,l=Xs(s[a],c);i.set(a,this.array(l,c,l.dtype,"view"))}t.set(o,i)}return t}}function Xt(n,e,t,r,o,s){const i=`views.${e}.${t}`,a=n.get(t);if(a===void 0){if(s)throw re(i,"the carried view is missing this member");return null}if(!(a instanceof r))throw re(i,`expected ${r.name}, found ${a.constructor.name}`,{expected:r.name,found:a.constructor.name});if(a.length!==o)throw re(i,`expected ${o} entries, found ${a.length}`,{expected:o,found:a.length});return a}function Yd(n,e,t,r){return Xt(n,e,"data",t,r,!0)}function H1(n,e,t){let r=null;const o={snapshot:n,verify:t,facts:()=>(r??=new s1(n),r)};for(const[s,i]of e)Y1(s,n.directed)||X1(o,s,i)}const K1=new Set(["reverse","inDegree","weightedInDegree","reverseDegreeOrder"]);function Y1(n,e){return e?n==="mate":K1.has(n)}function X1(n,e,t){const{snapshot:r}=n;switch(e){case"reverse":Q1(n,t);break;case"coo":J1(n,t);break;case"edgeList":Z1(n,t);break;case"outDegree":Kr(n,"outDegree",t,r.nodeCount,o=>{i1(r,o)});break;case"degree":Kr(n,"degree",t,r.nodeCount,o=>{c1(r,n.facts(),o)});break;case"selfLoopsPerNode":Kr(n,"selfLoopsPerNode",t,r.nodeCount,o=>{l1(n.facts(),o)});break;case"inDegree":Kr(n,"inDegree",t,r.nodeCount,o=>{a1(n.facts(),o)});break;case"selfLoopArcs":Kr(n,"selfLoopArcs",t,r.selfLoopCount,o=>{u1(r,n.facts(),o)});break;case"mate":Kr(n,"mate",t,r.arcCount,o=>{h1(r,n.facts(),o)});break;case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":e2(n,e,t);break;case"degreeOrder":case"reverseDegreeOrder":t2(n,e,t);break}}function Xd(n,e,t){if(t!==null&&n.weights===null)throw re(`views.${e}.weights`,"weights carried for an unweighted snapshot")}function Q1(n,e){const{snapshot:t}=n,{nodeCount:r,arcCount:o}=t,s=Xt(e,"reverse","rowPtr",Uint32Array,r+1,!0),i=Xt(e,"reverse","colIdx",Uint32Array,o,!0),a=Xt(e,"reverse","fwdArc",Uint32Array,o,!0),c=Xt(e,"reverse","weights",Float32Array,o,t.weights!==null);Xd(t,"reverse",c);const l=new Ko(t,s,i,c,a);n.verify&&p1(t,n.facts(),l),Yr(t,"reverse",l)}function J1(n,e){const{snapshot:t}=n,r=Xt(e,"coo","src",Uint32Array,t.arcCount,!0);n.verify&&d1(n.facts(),r),Yr(t,"coo",yd(t,r))}function Z1(n,e){const{snapshot:t}=n,{edgeCount:r}=t,o=t.flags.arcToEdgeIsIdentity,s=Xt(e,"edgeList","src",Uint32Array,r,!0),i=Xt(e,"edgeList","dst",Uint32Array,r,!o),a=Xt(e,"edgeList","weights",Float32Array,r,t.weights!==null&&!o);Xd(t,"edgeList",a),n.verify&&f1(t,n.facts(),s,i,a),Yr(t,"edgeList",za(t,s,i??t.colIdx,a??t.weights))}function Kr(n,e,t,r,o){const s=Yd(t,e,Uint32Array,r);n.verify&&o(s),Yr(n.snapshot,e,s)}function e2(n,e,t){const{snapshot:r}=n,o=Yd(t,e,Float64Array,r.nodeCount);if(n.verify){m1(e,o,r[e]());return}Yr(r,e,o)}function t2(n,e,t){const{snapshot:r}=n,{nodeCount:o}=r,s=Xt(t,e,"perm",Uint32Array,o,!0),i=Xt(t,e,"segmentOffsets",Uint32Array,5,!0);if(n.verify){const a=e==="degreeOrder"?Ar(r.rowPtr,o):n.facts().inDegree;g1(e,a,s,i)}Yr(r,e,Object.freeze({perm:s,segmentOffsets:i}))}function n2(n){const e=vt(n,"core"),t=r=>{const o=e[r];return o==null?null:Xs(o,`core.${r}`)};return{rowPtr:Xs(e.rowPtr,"core.rowPtr"),colIdx:t("colIdx"),weights:t("weights"),arcToEdge:t("arcToEdge"),edgeToArc:t("edgeToArc")}}function r2(n,e,t,r){const o=n.u32(e.rowPtr,"core.rowPtr","core");let s;if(e.colIdx===null){if(t.arcs!==0)throw re("core.colIdx",`null although counts.arcs is ${t.arcs}`);s=new Uint32Array(0)}else s=n.u32(e.colIdx,"core.colIdx","core");let i=null;if(e.weights!==null){if(!r.weighted)throw re("core.weights","present although flags.weighted is false");i=n.array(e.weights,"core.weights","f32","core")}else if(r.weighted){if(t.arcs!==0)throw re("core.weights",`null although flags.weighted is true and counts.arcs is ${t.arcs}`);i=new Float32Array(0)}const a=r.arcToEdgeIsIdentity,c=(l,u,d)=>{if(l!==null){if(a)throw re(`core.${u}`,"present although flags.arcToEdgeIsIdentity is true");return n.u32(l,`core.${u}`,"core")}if(a)return null;if(d!==0)throw re(`core.${u}`,`null although the permutation is not the identity and the count is ${d}`);return new Uint32Array(0)};return{rowPtr:o,colIdx:s,weights:i,arcToEdge:c(e.arcToEdge,"arcToEdge",t.arcs),edgeToArc:c(e.edgeToArc,"edgeToArc",t.edges)}}function o2(n,e,t,r,o){if(e===null||t===null||t.length===0||!(e.buffer===r.buffer&&e.byteOffset>=r.byteOffset&&e.byteOffset+e.byteLength<=r.byteOffset+r.byteLength))return null;const i=e.byteOffset-r.byteOffset;if(i%ft!==0)throw re(`core.${n}`,`inside the arena at offset ${i}, not a multiple of ${ft}`,{byteOffset:i});if(t.buffer!==o.buffer||t.byteOffset!==o.byteOffset+i)throw re(`core.${n}`,"the arena describes a segment the array is not a view of");return Object.freeze({byteOffset:o.byteOffset+i,byteLength:e.byteLength})}function s2(n,e,t,r,o){if(n==null)return null;const s=vt(n,"arena"),i=Nn(s.buffer,"arena.buffer"),a=Nn(s.byteOffset,"arena.byteOffset"),c=Nn(s.byteLength,"arena.byteLength"),l=e[i];if(l===void 0)throw re("arena.buffer",`buffer index ${i} is out of range`,{found:i});if(a+c>l.byteLength)throw re("arena",`range [${a}, ${a+c}) exceeds the buffer`,{byteOffset:a,byteLength:c,bufferByteLength:l.byteLength});const u=l.locate(a,c);if(u===null)return null;const d={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let f=0;const h={buffer:i,byteOffset:a,byteLength:c},g=Ho;for(const w of g){const p=o2(w,t[w],r[w],h,u);p!==null&&(d[w]=p,(w==="rowPtr"||w==="colIdx"||w==="weights")&&(f=p.byteOffset-u.byteOffset+p.byteLength))}if(o&&s.hotByteLength!==f)throw re("arena.hotByteLength",`manifest says ${String(s.hotByteLength)}, the segments say ${f}`,{expected:f,found:s.hotByteLength});return Object.freeze({buffer:u.buffer,byteOffset:u.byteOffset,byteLength:c,alignment:ft,segments:Object.freeze(d),hotByteLength:f})}function i2(n){const e=vt(n,"flags"),t=r=>_r(e[r],`flags.${r}`);return{multigraph:t("multigraph"),hasSelfLoops:t("hasSelfLoops"),arcToEdgeIsIdentity:t("arcToEdgeIsIdentity"),weighted:t("weighted"),allWeightsOne:t("allWeightsOne"),nonNegativeWeights:t("nonNegativeWeights"),finiteWeights:t("finiteWeights")}}function a2(n,e){if(n==null)return null;const t=vt(n,e),r=o=>Cn(t[o],`${e}.${o}`);return{format:r("format"),id:r("id"),title:r("title"),type:r("type"),namespace:r("namespace")}}function c2(n){const e=vt(n,"meta"),t=e.keywords??[],r=Ks(t,"meta.keywords").map((s,i)=>Xo(s,`meta.keywords[${i}]`)),o=Hn(e.extra??{},"meta.extra");if(!kn(o))throw re("meta.extra","expected an object");return Object.freeze({name:Cn(e.name,"meta.name"),description:Cn(e.description,"meta.description"),creator:Cn(e.creator,"meta.creator"),created:Cn(e.created,"meta.created"),modified:Cn(e.modified,"meta.modified"),keywords:Object.freeze(r),sourceFormat:Cn(e.sourceFormat,"meta.sourceFormat"),sourceVersion:Cn(e.sourceVersion,"meta.sourceVersion"),idType:Ys(e.idType,"meta.idType",L1),timeFormat:Ys(e.timeFormat,"meta.timeFormat",M1),timeRepresentation:Ys(e.timeRepresentation,"meta.timeRepresentation",U1),mode:Ys(e.mode,"meta.mode",F1),declaredMultigraph:z1(e.declaredMultigraph,"meta.declaredMultigraph"),weightOrigin:a2(e.weightOrigin,"meta.weightOrigin"),extra:Object.freeze(o)})}function Qd(n){if(n.format!==la)throw re("format",`expected "${la}", found ${Hr(n.format)}`,{found:n.format});const e=Ks(n.wire,"wire"),t=e[0],r=e[1];if(typeof t!="number"||typeof r!="number"||!Number.isInteger(t)||!Number.isInteger(r))throw re("wire","expected [major, minor] integers",{found:n.wire});if(t!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${t} is not supported (reader: ${zn})`,{kind:"wire",found:t,supported:zn});if(n.formatVersion!==Mr)throw new P("E_UNSUPPORTED_VERSION",`formatVersion ${Hr(n.formatVersion)} is not supported (reader: ${Mr})`,{kind:"format",found:n.formatVersion,supported:Mr});return[t,r]}function l2(n,e,t,r){const o=vt(n,"manifest");Qd(o);const s=new q1(e,t),i=_r(o.directed,"directed"),a=vt(o.counts,"counts"),c={nodes:Nn(a.nodes,"counts.nodes"),edges:Nn(a.edges,"counts.edges"),arcs:Nn(a.arcs,"counts.arcs"),selfLoops:Nn(a.selfLoops,"counts.selfLoops")},l=i2(o.flags);if(l.arcToEdgeIsIdentity&&(!i||c.arcs!==c.edges))throw re("flags.arcToEdgeIsIdentity","set on an undirected graph or with arcs !== edges");const u=n2(o.core),d=r2(s,u,c,l),f=s2(o.arena,e,u,d,s.structure),h=s.ids(o.ids),g=s.table(o.nodeColumns??[],"node",null,c.nodes,"nodeColumns"),w=s.table(o.edgeColumns??[],"edge",null,c.edges,"edgeColumns"),p=s.table(o.graphColumns??[],"graph",null,1,"graphColumns"),m=new Map,y=Ks(o.extensions??[],"extensions");for(let I=0;I<y.length;I++){const k=`extensions[${I}]`,N=vt(y[I],k),C=Xo(N.name,`${k}.name`);if(m.has(C))throw re(`${k}.name`,`extension table "${C}" appears twice`,{table:C});const O=Nn(N.rowCount,`${k}.rowCount`);m.set(C,s.table(N.columns,"extension",C,O,`${k}.columns`))}let b=c2(o.meta??{});if(s.skipped.length>0){const I=Object.freeze(s.skipped.map(k=>Object.freeze({...k})));b=Object.freeze({...b,extra:Object.freeze({...b.extra,[B1]:I})})}const v=s.views(o.views);s.structure&&s.checkOverlaps();const A={label:Cn(o.label,"label"),serial:null,directed:i,nodeCount:c.nodes,edgeCount:c.edges,arcCount:c.arcs,selfLoopCount:c.selfLoops,rowPtr:d.rowPtr,colIdx:d.colIdx,weights:d.weights,arcToEdge:d.arcToEdge,edgeToArc:d.edgeToArc,flags:l,ids:h,nodes:g,edges:w,graph:p,extensions:m,meta:b,arena:f,checksum:!1},E=pf(A);return t.level==="full"?E.validate({level:"full"}):t.level==="structure"&&E.validate({level:"structure"}),t.level!=="full"&&H1(E,v,t.level==="structure"),E}const Tn=16,u2=new TextDecoder("utf-8",{fatal:!0});function Jd(n,e){const t=new ja("container"),{manifest:r}=Ha(n,t,e.includeViews,!0),o=O1(r);return{manifestBytes:o,regionStart:hr(Tn+o.byteLength,ft),segments:t.segments,regionLength:t.regionLength}}function Zd(n,e){n.set(ua,0);const t=new DataView(n.buffer,n.byteOffset,n.byteLength);t.setUint16(4,zn,!0),t.setUint16(6,_u,!0),new Uint32Array(n.buffer,n.byteOffset+8,1)[0]=da,t.setUint32(12,e,!0)}function ef(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function d2(n,e={}){const t=Jd(n,e),r=new Uint8Array(t.regionStart+t.regionLength);Zd(r,t.manifestBytes.byteLength),r.set(t.manifestBytes,Tn);for(const o of t.segments)r.set(ef(o.view),t.regionStart+o.ref.byteOffset);return r}function*f2(n){const e=new Uint8Array(n.regionStart);Zd(e,n.manifestBytes.byteLength),e.set(n.manifestBytes,Tn),yield e;for(const t of n.segments){if(t.ref.byteLength===0)continue;const r=new Uint8Array(hr(t.ref.byteLength,ft));r.set(ef(t.view)),yield r}}function h2(n,e={}){return f2(Jd(n,e))}function g2(n,e){if(e<Tn)throw re("header",`truncated: ${e} bytes, expected at least ${Tn}`,{byteLength:e});for(let a=0;a<ua.length;a++)if(n[a]!==ua[a])throw re("magic","not a GSNP container",{found:Array.from(n.subarray(0,4))});const t=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t.getUint16(4,!0),o=t.getUint16(6,!0);if(r!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${r} is not supported (reader: ${zn})`,{kind:"wire",found:r,supported:zn});const s=t.getUint32(8,Eu);if(s!==da)throw re("endianness",`probe reads 0x${s.toString(16)}; the container was written on another endianness`,{found:s,expected:da});const i=t.getUint32(12,!0);if(Tn+i>e)throw re("manifest",`truncated: ${i} manifest bytes declared, ${e} bytes in total`,{manifestLength:i,byteLength:e});return{major:r,minor:o,manifestLength:i}}function w2(n,e){let t;try{t=u2.decode(n)}catch{throw re("manifest","not valid UTF-8")}const r=qd(t,"manifest");if(typeof r!="object"||r===null||Array.isArray(r))throw re("manifest","expected an object");const o=r,[s,i]=Qd(o);if(s!==e.major||i!==e.minor)throw re("wire",`manifest says [${s}, ${i}], the header says [${e.major}, ${e.minor}]`,{found:[s,i],header:[e.major,e.minor]});return o}function p2(n,e){const t=W1(e,"full"),r=n instanceof Uint8Array?n:new Uint8Array(n),o=g2(r,r.byteLength),s=w2(r.subarray(Tn,Tn+o.manifestLength),o),i=hr(Tn+o.manifestLength,ft),a=Math.max(0,r.byteLength-i),{buffer:c}=r;let l;if(!t.copy&&!V1(c)&&r.byteOffset%8===0)l=Hd(c,r.byteOffset+i,a);else{const u=new Uint8Array(hr(a,ft));a>0&&u.set(r.subarray(i)),l=Hd(u.buffer,0,a)}return l2(s,[l],t)}function m2(n,e,t){for(let r=1;r<t;r++){const o=n[r],s=n[r-1];if(o<s||o===s&&e[r]<e[r-1])return!1}return!0}function y2(n,e){return new P("E_INVALID_WEIGHT",`edge ${n} has a NaN weight`,{edge:n,weight:e})}function b2(n,e,t){let r=1/0,o=-1/0;for(let s=0;s<e;s++){const i=Math.fround(n[s]);if(Number.isNaN(i))throw y2(s,n[s]);i<r&&(r=i,t[0]=i),i>o&&(o=i,t[1]=i)}}function v2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c&&s++}return s}function A2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c?s++:(r[a+1]++,o[c+1]++)}return s}function tf(n,e){for(let t=0;t<e;t++)n[t+1]+=n[t]}function E2(n,e,t,r){let o=!1;for(let s=0;s<t;s++){const i=e[s];r[s]=i,s>0&&n[s]===n[s-1]&&e[s-1]===i&&(o=!0)}return o}function _2(n,e,t,r,o){for(let s=0;s<t;s++){const i=2*r[e[s]]++;o[i]=n[s],o[i+1]=s}}function I2(n,e,t,r,o,s){for(let i=0;i<t;i++){const a=n[i],c=e[i],l=r[c]++;if(o[2*l]=a,o[2*l+1]=i,s[l>>>5]|=1<<(l&31),a!==c){const u=2*r[a]++;o[u]=c,o[u+1]=i}}}function k2(n,e,t,r,o,s){for(let i=0;i<n;i++){const a=2*e[i+1];for(let c=2*e[i];c<a;c+=2){const l=r[t[c]]++;o[l]=i,s[l]=t[c+1]}}}function S2(n,e,t,r,o,s){const{targetStart:i,byTarget:a,declared:c}=e;for(let l=0;l<n;l++){const u=i[l+1];for(let d=i[l];d<u;d++){const f=a[2*d+1],h=t[a[2*d]]++;r[h]=l,o[h]=f,(c[d>>>5]>>>(d&31)&1)===1&&(s[f]=h)}}}function P2(n,e){const t=n.length;for(let r=0;r<t;r++)e[n[r]]=r}function x2(n,e,t){const r=n.length;for(let o=0;o<r;o++)t[o]=e[n[o]]}function C2(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Ya(n,e){const{directed:t,nodeCount:r,edgeCount:o,src:s,dst:i}=n,a=n.weights;let c=!0,l=!0,u=!0;if(a!==null&&o>0){const k=new Float64Array([1/0,-1/0]);b2(a,o,k);const N=k[0],C=k[1];c=N===1&&C===1,l=N>=0,u=N>-1/0&&C<1/0}const d=new Uint32Array(r+1),f=new Uint32Array(r+1),h=t?v2(s,i,o,d,f):A2(s,i,o,d,f),g=t?o:2*o-h,w=t&&m2(s,i,o),p=wb({nodeCount:r,arcCount:g,edgeCount:o,weighted:a!==null,identity:w},e),{rowPtr:m,colIdx:y,weights:b,arcToEdge:v,edgeToArc:A}=p;tf(f,r),m.set(f);let E;if(w)E=E2(s,i,o,y),b!==null&&a!==null&&b.set(a.subarray(0,o));else if(v!==null&&A!==null){tf(d,r);const k=f;k.set(d);const N=new Uint32Array(2*g);let C=null;t?_2(s,i,o,k,N):(C=new Uint32Array(g+31>>>5),I2(s,i,o,k,N,C)),k.set(m),C===null?(k2(r,d,N,k,y,v),P2(v,A)):S2(r,{targetStart:d,byTarget:N,declared:C},k,y,v,A),b!==null&&a!==null&&x2(v,a,b),E=C2(m,y,r)}else throw new P("E_UNSUPPORTED","unreachable: a non-identity core without permutation arrays",{directed:t,arcCount:g});const I=Object.freeze({multigraph:E,hasSelfLoops:h>0,arcToEdgeIsIdentity:w,weighted:b!==null,allWeightsOne:c,nonNegativeWeights:l,finiteWeights:u});return{core:p,arcCount:g,selfLoopCount:h,flags:I}}function N2(n,e){return n instanceof Uint8Array?mr(e):n instanceof Uint32Array?new Uint32Array(e):n instanceof Int32Array?new Int32Array(e):n instanceof Float32Array?new Float32Array(e):new Float64Array(e)}function T2(n,e){const t=n.validity;let r=null,o=0;for(let s=0;s<e.length;s++){const i=e[s];i!==x&&(t===null||Le(t,i))||(r??=In(e.length,!0),Kt(r,s),o++)}return{validity:r,nullCount:o}}function Xa(n,e){return n.nullable||e===0?n:Object.freeze({...n,nullable:!0})}function O2(n,e){for(let t=0;t<e.length;t++){const r=e[t];if(r!==x&&r>=n.length)throw new P("E_INDEX_RANGE",`indexMap[${t}] = ${r} is outside the column of ${n.length} rows`,{index:t,found:r,length:n.length,column:n.meta.name})}}function $2(n,e,t){const{length:r}=e,{components:o,fill:s}=t,i=N2(n.data,r*o);typeof s=="number"&&s!==0&&i.fill(s);for(let a=0;a<r;a++){const c=e[a];if(c!==x)for(let l=0;l<o;l++)i[a*o+l]=n.data[c*o+l]}return i}function R2(n,e,t){const{length:r}=e,o=new Uint32Array(Fe(r)).fill(t.fill===!0?4294967295:0);for(let s=0;s<r;s++){const i=e[s];i!==x&&(Le(n.data,i)?Ht(o,s):Kt(o,s))}return o}function D2(n,e,t){const r=typeof t.fill=="string"?n.codeOf(t.fill):x,o=r===x?0:r,s=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const a=e[i];s[i]=a===x?o:n.codes[a]}return s}function L2(n,e,t){const r=typeof t.fill=="string"?t.fill:"",o=new Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];o[s]=i===x?r:n.valueAt(i)}return o}function M2(n,e){const t=new Uint32Array(e.length+1);let r=0;for(let o=0;o<e.length;o++){const s=e[o];s!==x&&(r+=n[s+1]-n[s]),t[o+1]=r}return t}function U2(n,e,t){const r=new Uint32Array(t);let o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i!==x)for(let a=n[i];a<n[i+1];a++)r[o++]=a}return r}function F2(n,e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const o=e[r];t[r]=o===x?void 0:n.values[o]}return t}function B2(n,e,t){const{meta:r}=n,{dtype:o}=e;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":n.data=$2(e,t,r);return;case"bool":n.data=R2(e,t,r);return;case"dict":n.data=D2(e,t,r);return;case"string":n.offsets=null,n.utf8=null,n.strings=L2(e,t,r);return;case"list":{const s=M2(e.offsets,t);n.offsets=s,n.child=Qo(e.child,U2(e.offsets,t,s[t.length]));return}case"json":n.values=F2(e,t);return;default:{const s=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Qo(n,e){O2(n,e);const{validity:t,nullCount:r}=T2(n,e),o={...Us(n),meta:Xa(n.meta,r),length:e.length,validity:t};return B2(o,n,e),Tt(o)}function nf(n,e){if(n.meta.refersTo===null)return n;const t=r=>r===x||r>=e.length?x:e[r];if(n.dtype==="u32"){const{length:r}=n,o=new Uint32Array(r);let s=n.validity===null?null:n.validity.slice(),{nullCount:i}=n;for(let c=0;c<r;c++){const l=t(n.data[c]);o[c]=l,l===x&&(s===null||Le(s,c))&&(s??=In(r,!0),Kt(s,c),i++)}const a={...Us(n),meta:Xa(n.meta,i),data:o,validity:s};return Tt(a)}if(n.dtype==="list"&&n.child.dtype==="u32"){const{length:r,offsets:o,child:s}=n,i=new Array(r);let a=n.validity===null?null:n.validity.slice(),{nullCount:c}=n;for(let f=0;f<r;f++){const h=[],g=o[f],w=o[f+1];for(let p=g;p<w;p++){const m=t(s.data[p]);m!==x&&h.push(m)}i[f]=h,w>g&&h.length===0&&(a===null||Le(a,f))&&(a??=In(r,!0),Kt(a,f),c++)}const l=Xa(n.meta,c),u=Vo(Object.freeze({...l,nullable:!0}),i),d={...Us(u),meta:l,validity:a};return Tt(d)}throw new P("E_COLUMN_TYPE",`column "${n.meta.name}" has refersTo but is not u32 or a list of u32`,{column:n.meta.name,field:"refersTo"})}function rf(n,e){return n.refersTo==="node"?e.node:n.refersTo==="edge"?e.edge:null}function Qa(n,e,t,r){const o=n.rowCount,s=[];for(const i of n){const a=rf(i.meta,r);let c=i;a!==null&&(c=nf(i,a)),s.push(c)}return new wn({domain:n.domain,rowCount:o,columns:s})}function of(n,e,t){const r=[];for(const o of n){const s=Qo(o,e),i=rf(o.meta,t);r.push(i===null?s:nf(s,i))}return new wn({domain:n.domain,rowCount:e.length,columns:r})}function At(n,e){return In(n,e===!0)}function _e(n,e){return Le(n,e)}function pn(n,e,t){ba(n,e,t)}function z2(n,e){return gr(n,e)}function sf(n,e){return X0(n,e)}function Qs(n,e,t){const r=Fe(e);if(n.length<r)throw new P("E_MASK_LENGTH",`mask over ${t} has ${n.length} words; ${r} needed for ${e} ${t}`,{found:n.length,required:r,length:e})}const af=Object.freeze({droppedEdges:0,mergedEdges:0});function cf(){return{parts:null,nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function Jo(n,e={}){const t=Ya(n,e.arena!==!1),{core:r}=t;return{arcCount:t.arcCount,selfLoopCount:t.selfLoopCount,rowPtr:r.rowPtr,colIdx:r.colIdx,weights:r.weights,arcToEdge:r.arcToEdge,edgeToArc:r.edgeToArc,flags:t.flags,arena:r.arena}}function Zo(n,e,t){return{label:n.label,serial:null,directed:t.directed,nodeCount:t.nodeCount,edgeCount:t.edgeCount,arcCount:e.arcCount,selfLoopCount:e.selfLoopCount,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,flags:e.flags,ids:t.ids,nodes:t.nodes,edges:t.edges,graph:n.graph,extensions:t.extensions,meta:n.meta,arena:e.arena,checksum:!1}}function es(n,e,t){if(e===null&&t===null||n.extensions.size===0)return n.extensions;const r=new Map;for(const[o,s]of n.extensions)r.set(o,Qa(s,null,s.rowCount,{node:e,edge:t}));return r}function G2(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++){const o=n[r];o!==x&&t[o]===x&&(t[o]=r)}return t}function Js(n){const e=n.length,t=new Uint32Array(e).fill(x);let r=0,o=0,s=0;for(let a=0;a<e;a++)n[a]===a?t[a]=r++:n[a]===x?o++:s++;if(o===0&&s===0)return{count:r,remap:null,origin:null,dropped:o,merged:s};const i=new Uint32Array(e);for(let a=0;a<e;a++){const c=n[a];i[a]=c===x?x:t[c]}return{count:r,remap:i,origin:G2(i,r),dropped:o,merged:s}}function W2(n,e){return n.length===e&&qr(n)}function ts(n,e,t){const{count:r,origin:o}=e,s=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){const c=o===null?a:o[a];s[a]=t===null?n.src[c]:t[n.src[c]],i[a]=t===null?n.dst[c]:t[n.dst[c]]}return{src:s,dst:i}}function Ja(n,e){if(e!==void 0)for(const t of Object.keys(e))zt(`${n}.${t}`,e[t],Sy)}function ns(n,e,t){const{count:r,remap:o,origin:s}=e;if(n===null){if(t!=="sum")return null;const a=new Float32Array(r);if(o===null)return a.fill(1),a;for(let c=0;c<o.length;c++)o[c]!==x&&a[o[c]]++;return a}if(o===null||s===null)return n;const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=n[s[a]];if(t==="first")return i;for(let a=0;a<o.length;a++){const c=o[a];if(c===x||s[c]===a)continue;const l=n[a];switch(t){case"last":i[c]=l;break;case"sum":i[c]+=l;break;case"min":l<i[c]&&(i[c]=l);break;case"max":l>i[c]&&(i[c]=l);break;default:{const u=t;throw new P("E_UNSUPPORTED",`unknown weight reducer ${String(u)}`,{reducer:u})}}}return i}function Zs(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=e(r)?r:x;return Js(t)}function V2(n,e,t){const{count:r,remap:o}=e,{components:s}=n.meta,i=s,a=new Float64Array(r*i),c=new Uint32Array(r),l=new Uint8Array(r),u=n.data,d=o===null?n.length:o.length;for(let y=0;y<d;y++){const b=o===null?y:o[y];if(!(b===x||!n.isSet(y))){c[b]++;for(let v=0;v<i;v++){const A=u[y*i+v],E=b*i+v;if(l[b]===0)a[E]=A;else switch(t){case"sum":case"mean":a[E]+=A;break;case"min":A<a[E]&&(a[E]=A);break;case"max":A>a[E]&&(a[E]=A);break;default:{const I=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(I)}`,{reducer:I})}}}l[b]=1}}if(t==="mean"){for(let y=0;y<r;y++)if(c[y]>1)for(let b=0;b<i;b++)a[y*i+b]/=c[y]}const h=t==="mean"||t==="sum"&&n.dtype!=="f32"&&n.dtype!=="f64"?"f64":n.dtype;let g;switch(h){case"f64":g=a;break;case"f32":g=new Float32Array(a);break;case"i32":g=new Int32Array(a);break;case"u32":g=new Uint32Array(a);break;case"u8":g=new Uint8Array(new ArrayBuffer(Math.ceil(r*i/4)*4),0,r*i),g.set(a);break;default:{const y=h;throw new P("E_COLUMN_TYPE",`cannot reduce a ${String(y)} column`,{dtype:y})}}let w=null,p=0;for(let y=0;y<r;y++)l[y]===0&&(w??=In(r,!0),Kt(w,y),p++);const m=ht(n.meta.name,n.meta.domain,{dtype:h,components:s,nullable:n.meta.nullable||p>0,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(m,r,w),data:g})}function j2(n,e){const{count:t,remap:r}=e,o=new Uint32Array(t);if(r===null)o.fill(1);else for(let i=0;i<r.length;i++)r[i]!==x&&o[r[i]]++;const s=ht(n.meta.name,n.meta.domain,{dtype:"u32",nullable:!1,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(s,t,null),data:o})}function Za(n,e,t){if(t==="drop"||n.meta.refersTo!==null)return null;const{count:r,remap:o,origin:s}=e;switch(t){case"first":return s===null?n:Qo(n,s);case"last":{if(o===null)return n;const i=new Uint32Array(r);for(let a=0;a<o.length;a++)o[a]!==x&&(i[o[a]]=a);return Qo(n,i)}case"count":return j2(n,e);case"sum":case"min":case"max":case"mean":{const{dtype:i}=n;switch(i){case"f32":case"f64":case"i32":case"u32":case"u8":return V2(n,e,t);case"bool":case"dict":case"string":case"list":case"json":throw new P("E_COLUMN_TYPE",`reducer "${t}" needs a numeric column; "${n.meta.name}" is ${i}`,{column:n.meta.name,dtype:i,reducer:t});default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${String(a)}`,{dtype:a})}}}default:{const i=t;throw new P("E_UNSUPPORTED",`unknown column reducer ${String(i)}`,{reducer:i})}}}function ei(n,e,t,r){const o={node:r,edge:e.remap};if(t===void 0||Object.keys(t).length===0)return e.origin===null?r===null?n.edges:Qa(n.edges,null,n.edgeCount,o):of(n.edges,e.origin,o);const s=[];for(const a of n.edges){const c=t[a.meta.name];if(c===void 0){const u=e.origin===null?a:Qo(a,e.origin);s.push(u);continue}const l=Za(a,e,c);l!==null&&s.push(l)}const i=new wn({domain:"edge",rowCount:e.count,columns:s});return Qa(i,null,e.count,o)}function lf(n,e,t){const r=Zs(n.edgeCount,t),{src:o,dst:s}=ts(e,r,null),i=ns(e.weights,r,"first"),a=Jo({directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,src:o,dst:s,weights:i}),c=ei(n,r,void 0,null);return{parts:Zo(n,a,{directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,ids:n.ids,nodes:n.nodes,edges:c,extensions:es(n,null,r.remap)}),nodeOrigin:null,edgeOrigin:r.origin,nodeRemap:null,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:0}}}function q2(n,e,t){return Qs(t,n.edgeCount,"edges"),lf(n,e,r=>_e(t,r))}function H2(n,e){return lf(n,e,t=>e.src[t]!==e.dst[t])}function uf(n,e,t,r){return new P("E_INDEX_RANGE",`inducedSubgraph selection[${n}] = ${e} is ${r} (nodeCount ${t})`,{index:n,found:e,nodeCount:t,reason:r})}function K2(n,e){const{nodeCount:t}=n;if(e instanceof Uint32Array){const r=new Uint8Array(t),o=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];if(i>=t)throw uf(s,i,t,"out of range");if(r[i]===1)throw uf(s,i,t,"repeated");r[i]=1,o[s]=i}return o}return Qs(e.mask,t,"nodes"),sf(e.mask,t)}function df(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++)t[n[r]]=r;return t}function ff(n,e,t,r){const o=t===null?n.nodeCount:t.length,s=t===null?null:df(t,n.nodeCount),{src:i,dst:a}=ts(e,r,s),c=ns(e.weights,r,"first"),l=Jo({directed:n.directed,nodeCount:o,edgeCount:r.count,src:i,dst:a,weights:c}),u={node:s,edge:r.remap},d=t===null?n.nodes:of(n.nodes,t,u),f=t===null?n.ids:Gy(n.ids,t),h=ei(n,r,void 0,s);return{parts:Zo(n,l,{directed:n.directed,nodeCount:o,edgeCount:r.count,ids:f,nodes:d,edges:h,extensions:es(n,s,r.remap)}),nodeOrigin:t,edgeOrigin:r.origin,nodeRemap:s,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:r.merged}}}function Y2(n,e,t){const r=K2(n,t),o=W2(r,n.nodeCount),s=o?null:r,i=o?null:df(r,n.nodeCount),a=i===null?Zs(n.edgeCount,()=>!0):Zs(n.edgeCount,c=>i[e.src[c]]!==x&&i[e.dst[c]]!==x);return ff(n,e,s,a)}function X2(n,e,t){const{nodeCount:r}=n;if(t.length!==r)throw new P("E_INVALID_PERMUTATION",`perm has ${t.length} entries, expected ${r}`,{expected:r,found:t.length});const o=new Uint8Array(r);for(let a=0;a<r;a++){const c=t[a];if(c>=r||o[c]===1)throw new P("E_INVALID_PERMUTATION",`perm[${a}] = ${c} is out of range or repeated (nodeCount ${r})`,{index:a,found:c,nodeCount:r});o[c]=1}const s=qr(t)?null:t.slice(),i=Zs(n.edgeCount,()=>!0);return ff(n,e,s,i)}function hf(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Q2(n,e,t,r,o){for(let s=0;s<o;s++){const i=e[t+s],a=e[r+s],c=Math.min(i,a),l=Math.max(i,a);n[c]=c,n[l]=c}}function J2(n,e,t={}){const r=t.reciprocal===!0,o=zt("weights",t.weights,Fs)??"first",{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i);for(let y=0;y<i;y++)u[y]=r&&e.src[y]!==e.dst[y]?x:y;for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if(A>y){const[I,k]=qs(a,c,A,y);Q2(u,l,v,I,Math.min(E-v,k-I))}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,o),w=Jo({directed:!1,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,void 0,null);return{parts:Zo(n,w,{directed:!1,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Z2(n,e){const{nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s}=n,i=e.arcToEdge,a=qr(i);let c=null,l=null;if(!a){c=i,l=new Uint32Array(r);for(let f=0;f<o;f++)l[i[f]]=f}const u=_d({directed:!0,nodeCount:t,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,selfLoopCount:s});return Gn(e.rowPtr.buffer),Gn(e.colIdx.buffer),e.weights!==null&&Gn(e.weights.buffer),c!==null&&Gn(c.buffer),{parts:{label:n.label,serial:null,directed:!0,nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,edgeToArc:l,flags:u,ids:n.ids,nodes:n.nodes,edges:n.edges,graph:n.graph,extensions:n.extensions,meta:n.meta,arena:null,checksum:!1},nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function ev(n,e,t={}){const r=zt("weights",t.weights,Fs)??"first",o=zt("selfLoops",t.selfLoops,["keep","drop"])==="drop";Ja("edgeReducers",t.edgeReducers);const{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i).fill(x);for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if((n.directed||A>=y)&&!(A===y&&o)){const I=l[v];for(let k=v;k<E;k++)u[l[k]]=I}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,r),w=Jo({directed:n.directed,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,t.edgeReducers,null);return{parts:Zo(n,w,{directed:n.directed,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Je(n,e){const t=n.length,r=e??new Uint32Array(t);if(r.length!==t)throw new P("E_COLUMN_LENGTH",`out has ${r.length} entries, expected ${t}`,{expected:t,found:r.length});let o=0;for(let i=0;i<t;i++){const a=n[i];if(a===x)throw new P("E_PARTITION",`labels[${i}] is INVALID_INDEX`,{index:i});a>o&&(o=a)}const s=o<4*t+1024?tv(n,r,o):nv(n,r);return{labels:r,count:s}}function tv(n,e,t){const r=new Uint32Array(t+1).fill(x);let o=0;for(let s=0;s<n.length;s++){const i=n[s];let a=r[i];a===x&&(a=o++,r[i]=a),e[s]=a}return o}function nv(n,e){const t=new Map;let r=0;for(let o=0;o<n.length;o++){const s=n[o];let i=t.get(s);i===void 0&&(i=r++,t.set(s,i)),e[o]=i}return r}function rv(n,e){if(n.length!==e)throw new P("E_PARTITION",`partition has ${n.length} entries, expected nodeCount ${e}`,{expected:e,found:n.length});let t=-1;for(let r=0;r<e;r++){const o=n[r];if(o===x)throw new P("E_PARTITION",`partition[${r}] is INVALID_INDEX`,{index:r});o>t&&(t=o)}if(t<e){const r=new Uint8Array(t+1);let o=0;for(let s=0;s<e;s++)r[n[s]]===0&&(r[n[s]]=1,o++);if(o===t+1)return{labels:n.slice(),count:t+1}}return Je(n)}function ov(n,e,t,r,o){const s=[];if(o!==void 0){const i={count:t,remap:e,origin:r};for(const a of n.nodes){const c=o[a.meta.name];if(c===void 0)continue;const l=Za(a,i,c);l!==null&&s.push(l)}}return new wn({domain:"node",rowCount:t,columns:s})}function sv(n,e,t){const r=n.length,o=[];for(let u=0;u<r;u++)n[u]!==x&&o.push(u);const s=new Uint32Array(t+1);for(const u of o)s[e[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const i=new Uint32Array(o.length);for(const u of o)i[s[e[u]]++]=u;s.fill(0);for(const u of o)s[n[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const a=new Uint32Array(o.length);for(let u=0;u<i.length;u++){const d=i[u];a[s[n[d]]++]=d}const c=new Uint32Array(r).fill(x);let l=0;for(;l<a.length;){const u=a[l];let d=l+1;for(;d<a.length&&n[a[d]]===n[u]&&e[a[d]]===e[u];)d++;for(let f=l;f<d;f++)c[a[f]]=u;l=d}return c}function iv(n,e,t,r={}){const o=zt("weights",r.weights,Fs)??"sum",s=zt("selfLoops",r.selfLoops,["keep","drop"])==="drop",i=(zt("parallel",r.parallel,["merge","keep"])??"merge")==="merge";Ja("nodeReducers",r.nodeReducers),Ja("edgeReducers",r.edgeReducers);const{nodeCount:a,edgeCount:c}=n,{labels:l,count:u}=rv(t,a),d=new Uint32Array(u),f=new Uint32Array(u).fill(x);for(let N=0;N<a;N++){const C=l[N];d[C]++,f[C]===x&&(f[C]=N)}const h=new Uint32Array(c),g=new Uint32Array(c);for(let N=0;N<c;N++){const C=l[e.src[N]],O=l[e.dst[N]];C===O&&s?(h[N]=x,g[N]=x):n.directed||C<=O?(h[N]=C,g[N]=O):(h[N]=O,g[N]=C)}let w;if(i)w=sv(h,g,u);else{w=new Uint32Array(c);for(let N=0;N<c;N++)w[N]=h[N]===x?x:N}const p=Js(w),{src:m,dst:y}=ts(e,p,l),b=ns(e.weights,p,o),v=Jo({directed:n.directed,nodeCount:u,edgeCount:p.count,src:m,dst:y,weights:b}),A=ov(n,l,u,f,r.nodeReducers),E=[];if(r.edgeReducers!==void 0)for(const N of n.edges){const C=r.edgeReducers[N.meta.name];if(C===void 0)continue;const O=Za(N,p,C);O!==null&&E.push(O)}const I=new wn({domain:"edge",rowCount:p.count,columns:E});return{parts:Zo(n,v,{directed:n.directed,nodeCount:u,edgeCount:p.count,ids:nd(u),nodes:A,edges:I,extensions:es(n,l,p.remap)}),nodeOrigin:f,edgeOrigin:p.origin,nodeRemap:l,edgeRemap:p.remap,blockSizes:d,report:{droppedEdges:p.dropped,mergedEdges:p.merged}}}function av(n,e,t,r,o){return{label:n.label,serial:n.serial,directed:n.directed,nodeCount:n.nodeCount,edgeCount:n.edgeCount,arcCount:n.arcCount,selfLoopCount:n.selfLoopCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:r,edgeToArc:o,flags:n.flags,ids:n.ids,nodes:ld(n.nodes,e??{}),edges:ld(n.edges,t??{}),graph:n.graph.clone(),extensions:n.extensions,meta:n.meta,arena:n.arena,checksum:!1}}const cv=2166136261,lv=16777619,uv=3421674724,dv=1540483477;class ec{constructor(){this.laneA=cv,this.laneB=uv}word(e){const t=e>>>0;this.laneA=Math.imul(this.laneA^t,lv)>>>0;const r=(t<<16|t>>>16)>>>0;return this.laneB=Math.imul(this.laneB^r,dv)>>>0,this}words(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e[t]);return this}identity(e){this.word(e);for(let t=0;t<e;t++)this.word(t);return this}bytes(e){const{byteLength:t,byteOffset:r}=e;if(this.word(t),r%4===0&&t%4===0){const i=new Uint32Array(e.buffer,r,t/4);for(let a=0;a<i.length;a++)this.word(i[a]);return this}const o=new Uint8Array(e.buffer,r,t);let s=0;for(;s+4<=t;s+=4)this.word(o[s]|o[s+1]<<8|o[s+2]<<16|o[s+3]<<24);if(s<t){let i=0;for(let a=0;s+a<t;a++)i|=o[s+a]<<8*a;this.word(i)}return this}text(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e.charCodeAt(t));return this}digest(){return this.laneA.toString(16).padStart(8,"0")+this.laneB.toString(16).padStart(8,"0")}}function mn(n){return new ec().bytes(n).digest()}function gf(n,e){n.text(e.dtype).word(e.length).word(e.nullCount),e.validity!==null?n.words(e.validity):n.word(0);const{dtype:t}=e;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":n.bytes(e.data);break;case"dict":n.words(e.codes).word(e.dictionary.length);for(const r of e.dictionary)n.text(r);break;case"string":n.words(e.offsets).bytes(e.utf8);break;case"list":n.words(e.offsets),gf(n,e.child);break;case"json":n.text(JSON.stringify(e.values));break;default:K0(t)}}function wf(n){if(ka(n))throw new P("E_DETACHED",`column "${n.meta.name}" was transferred away`,{column:n.meta.name});const e=new ec;return gf(e,n),e.digest()}function fv(n){const e=new ec;return e.word(n.directed?1:0).word(n.nodeCount).word(n.edgeCount).word(n.arcCount).word(n.selfLoopCount),e.words(n.rowPtr).words(n.colIdx),n.weights===null?e.word(0):e.bytes(n.weights),n.flags.arcToEdgeIsIdentity?e.identity(n.arcCount).identity(n.edgeCount):e.words(n.arcToEdge).words(n.edgeToArc),e.digest()}let hv=1;const ti=["reverse","coo","edgeList","outDegree","inDegree","degree","weightedOutDegree","weightedInDegree","weightedDegree","selfLoopWeight","totalWeight","selfLoopArcs","selfLoopsPerNode","mate","degreeOrder","reverseDegreeOrder","symmetric"],gv="__graphtyNoStructuredClone";function wv(){}const tc=new WeakMap;function pv(){return{reverse:null,coo:null,edgeList:null,outDegree:null,inDegree:null,degree:null,weightedOutDegree:null,weightedInDegree:null,weightedDegree:null,selfLoopWeight:null,totalWeight:null,selfLoopArcs:null,selfLoopsPerNode:null,mate:null,degreeOrder:null,reverseDegreeOrder:null,symmetric:null}}function On(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function mv(n){const{nodeCount:e,edgeCount:t,arcCount:r,flags:o}=n;if(n.rowPtr.length!==e+1)throw On("I1",`rowPtr has ${n.rowPtr.length} entries, expected ${e+1}`,{expected:e+1,found:n.rowPtr.length});if(n.colIdx.length!==r)throw On("I1",`colIdx has ${n.colIdx.length} entries, expected ${r}`,{expected:r,found:n.colIdx.length});if(n.weights!==null&&n.weights.length!==r)throw On("I8",`weights has ${n.weights.length} entries, expected ${r}`,{expected:r,found:n.weights.length});const s=o.arcToEdgeIsIdentity;if(n.arcToEdge===null!==s||n.edgeToArc===null!==s)throw On("I9","arcToEdge / edgeToArc must be null exactly when flags.arcToEdgeIsIdentity",{flag:"arcToEdgeIsIdentity",found:s});if(s&&(!n.directed||r!==t))throw On("I9","flags.arcToEdgeIsIdentity requires a directed snapshot with arcCount === edgeCount",{flag:"arcToEdgeIsIdentity",directed:n.directed,arcCount:r,edgeCount:t});if(n.arcToEdge!==null&&n.arcToEdge.length!==r)throw On("I5",`arcToEdge has ${n.arcToEdge.length} entries, expected ${r}`,{expected:r,found:n.arcToEdge.length});if(n.edgeToArc!==null&&n.edgeToArc.length!==t)throw On("I5",`edgeToArc has ${n.edgeToArc.length} entries, expected ${t}`,{expected:t,found:n.edgeToArc.length});if(n.ids.size!==e)throw On("I11",`ids.size is ${n.ids.size}, expected ${e}`,{expected:e,found:n.ids.size});if(n.nodes.rowCount!==e||n.edges.rowCount!==t||n.graph.rowCount!==1)throw On("I12","table row counts do not match nodeCount / edgeCount / 1",{nodes:n.nodes.rowCount,edges:n.edges.rowCount,graph:n.graph.rowCount})}function ni(n,e){for(const t of e)t.meta.mutable||n.columns.set(t,wf(t))}let yv=class yu{constructor(e){mv(e),this[Au]=!0,this.serial=e.serial??hv++,this.label=e.label,this.formatVersion=Mr,this.directed=e.directed,this.nodeCount=e.nodeCount,this.edgeCount=e.edgeCount,this.arcCount=e.arcCount,this.selfLoopCount=e.selfLoopCount,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.weights=e.weights,this.flags=Object.freeze({...e.flags}),this.ids=e.ids,this.nodes=e.nodes,this.edges=e.edges,this.graph=e.graph,this.extensions=e.extensions,this.meta=e.meta,this.arena=e.arena;let t=null;if(e.checksum){t={core:new Map,columns:new WeakMap,views:new Map},t.core.set("rowPtr",mn(e.rowPtr)),t.core.set("colIdx",mn(e.colIdx)),e.weights!==null&&t.core.set("weights",mn(e.weights)),e.arcToEdge!==null&&t.core.set("arcToEdge",mn(e.arcToEdge)),e.edgeToArc!==null&&t.core.set("edgeToArc",mn(e.edgeToArc)),ni(t,e.nodes),ni(t,e.edges),ni(t,e.graph);for(const o of e.extensions.values())ni(t,o)}const r={arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,views:pv(),checksums:t,contentHash:null,edgeIds:null};Object.defineProperty(this,"state",{value:r,enumerable:!1,writable:!1,configurable:!1}),tc.set(this,r),bv(e),Object.defineProperty(this,gv,{value:wv,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get detached(){return this.rowPtr.length===0}get arcToEdge(){this.assertAttached();const{state:e}=this;return e.arcToEdge===null&&(e.arcToEdge=Ba(this.arcCount),e.checksums?.core.set("arcToEdge",mn(e.arcToEdge))),e.arcToEdge}get edgeToArc(){this.assertAttached();const{state:e}=this;return e.edgeToArc===null&&(e.edgeToArc=Ba(this.edgeCount),e.checksums?.core.set("edgeToArc",mn(e.edgeToArc))),e.edgeToArc}outArcs(e){return this.assertAttached(),[this.rowPtr[e],this.rowPtr[e+1]]}outDegreeOf(e){return this.assertAttached(),this.rowPtr[e+1]-this.rowPtr[e]}findArc(e,t){return this.assertAttached(),yb(this.rowPtr,this.colIdx,e,t)}hasArc(e,t){return this.findArc(e,t)!==x}arcsBetween(e,t){return this.assertAttached(),qs(this.rowPtr,this.colIdx,e,t)}multiplicity(e,t){return this.assertAttached(),gd(this.rowPtr,this.colIdx,e,t)}arcSource(e){this.assertAttached();const{coo:t}=this.state.views;return t!==null?t.src[e]:bb(this.rowPtr,e)}edgeSource(e){this.assertAttached();const t=this.state.views.edgeList;return t!==null?t.src[e]:this.arcSource(this.edgeToArc[e])}edgeTarget(e){return this.colIdx[this.edgeToArc[e]]}edgeIndexOf(e){const{state:t}=this,r=ib(this.edges);if(t.edgeIds?.version!==r){const o=this.edges.byRole("id");t.edgeIds={version:r,column:o,index:o===null?null:new fb(o)}}return t.edgeIds.index===null?x:t.edgeIds.index.indexOf(e)}reverse(){return this.cached("reverse",()=>Eb(this))}coo(){return this.cached("coo",()=>_b(this))}edgeList(){return this.cached("edgeList",()=>bd(this))}outDegree(){return this.cached("outDegree",()=>Ar(this.rowPtr,this.nodeCount))}inDegree(){return this.cached("inDegree",()=>this.directed?Ar(this.reverse().rowPtr,this.nodeCount):this.outDegree())}degree(){return this.cached("degree",()=>Ib(this.outDegree(),this.directed?this.inDegree():this.selfLoopsPerNode()))}weightedOutDegree(){return this.cached("weightedOutDegree",()=>this.weights===null?Ga(this.outDegree()):vd(this.rowPtr,this.weights,this.nodeCount))}weightedInDegree(){return this.cached("weightedInDegree",()=>{if(!this.directed)return this.weightedOutDegree();const e=this.reverse();return e.weights===null?Ga(this.inDegree()):vd(e.rowPtr,e.weights,this.nodeCount)})}weightedDegree(){return this.cached("weightedDegree",()=>kb(this.weightedOutDegree(),this.directed?this.weightedInDegree():this.selfLoopWeight()))}selfLoopWeight(){return this.cached("selfLoopWeight",()=>xb(this,{selfLoopArcs:this.selfLoopArcs(),selfLoopsPerNode:this.selfLoopsPerNode()}))}totalWeight(){return this.cached("totalWeight",()=>Sb(this))}selfLoopArcs(){return this.cached("selfLoopArcs",()=>this.materialiseSelfLoops().selfLoopArcs)}selfLoopsPerNode(){return this.cached("selfLoopsPerNode",()=>this.materialiseSelfLoops().selfLoopsPerNode)}selfLoopsAt(e){return this.assertAttached(),vb(this.rowPtr,this.colIdx,e)}mate(){return this.cached("mate",()=>Nb(this))}degreeOrder(e){if((zt("of",e?.of,["forward","reverse"])??"forward")==="reverse"&&this.directed)return this.cached("reverseDegreeOrder",()=>Ad(this.reverse().rowPtr,this.nodeCount));const r=this.cached("degreeOrder",()=>Ad(this.rowPtr,this.nodeCount));return this.directed||(this.state.views.reverseDegreeOrder=r),r}isSymmetric(){return this.cached("symmetric",()=>this.directed?Tb(this,this.reverse()):!0)}prepare(e){for(const t of e)this.materialiseView(t);return this}dropCaches(){const{state:e}=this;for(const t of ti)e.views[t]=null;e.checksums?.views.clear(),this.flags.arcToEdgeIsIdentity&&(e.arcToEdge=null,e.edgeToArc=null,e.checksums?.core.delete("arcToEdge"),e.checksums?.core.delete("edgeToArc"));for(const t of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const r of t)wy(r)}cachedViews(){if(this.detached)return this.dropCaches(),[];const{views:e}=this.state;return ti.filter(t=>e[t]!==null)}toUndirected(e){return this.assertAttached(),this.directed?this.wrapDerived(J2(this,this.edgeEndpoints(),e)):this.wrapDerived(cf())}transpose(){return this.assertAttached(),this.directed?this.wrapDerived(Z2(this,this.reverse())):this.wrapDerived(cf())}simplified(e){return this.assertAttached(),this.wrapDerived(ev(this,this.edgeEndpoints(),e))}withoutSelfLoops(){return this.assertAttached(),this.wrapDerived(H2(this,this.edgeEndpoints()))}filterEdges(e){return this.assertAttached(),this.wrapDerived(q2(this,this.edgeEndpoints(),e))}inducedSubgraph(e){return this.assertAttached(),this.wrapDerived(Y2(this,this.edgeEndpoints(),e))}contract(e,t){return this.assertAttached(),this.wrapDerived(iv(this,this.edgeEndpoints(),e,t))}relabel(e){return this.assertAttached(),this.wrapDerived(X2(this,this.edgeEndpoints(),e))}seal(){Vs(this.nodes),Vs(this.edges),Vs(this.graph);for(const e of this.extensions.values())Vs(e)}withColumns(e,t){this.assertAttached();const r=this.flags.arcToEdgeIsIdentity,o=av(this,e,t,r?null:this.arcToEdge,r?null:this.edgeToArc);return new yu({...o,checksum:this.state.checksums!==null})}byteLength(e={}){let t=this.rowPtr.byteLength+this.colIdx.byteLength;return this.weights!==null&&(t+=this.weights.byteLength),this.flags.arcToEdgeIsIdentity||(t+=this.arcToEdge.byteLength+this.edgeToArc.byteLength),e.views===!0&&(t+=Av(this,this.state.views)),e.columns===!0&&(t+=Ev(this)),e.ids===!0&&(t+=this.ids.byteLength()),t}contentHash(){this.assertAttached();const{state:e}=this;return e.contentHash??=fv(this),e.contentHash}transferables(){return this.assertAttached(),T1(this)}toWire(e){return this.assertAttached(),N1(this,e)}toBytes(e){return this.assertAttached(),d2(this,e)}toByteChunks(e){return this.assertAttached(),h2(this,e)}validate(e={}){this.assertAttached();const t=zt("level",e.level,["structure","full"])??"full";if(typeof e.checksum!="boolean"&&e.checksum!==void 0)throw new P("E_UNSUPPORTED","validate option checksum must be a boolean",{field:"checksum",found:e.checksum,reason:"unsupported option"});if(xy(this.ids))throw new P("E_DETACHED","the id map's storage was transferred away",{serial:this.serial});for(const r of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const o of r)if(ka(o))throw new P("E_DETACHED",`column "${o.meta.name}" was transferred away`,{column:o.meta.name,serial:this.serial});e.checksum===!0&&this.verifyChecksums(),t==="structure"?Nd(this):r1(this)}assertAttached(){if(this.rowPtr.length===0)throw new P("E_DETACHED","the snapshot's core buffer was transferred away",{serial:this.serial})}cached(e,t){this.assertAttached();const{views:r}=this.state,o=r[e];if(o!==null)return o;const s=t();return r[e]=s,this.recordView(e,s),s}materialiseSelfLoops(){const e=Pb(this),{views:t}=this.state;return t.selfLoopArcs===null&&(t.selfLoopArcs=e.selfLoopArcs,this.recordView("selfLoopArcs",e.selfLoopArcs)),t.selfLoopsPerNode===null&&(t.selfLoopsPerNode=e.selfLoopsPerNode,this.recordView("selfLoopsPerNode",e.selfLoopsPerNode)),{selfLoopArcs:t.selfLoopArcs,selfLoopsPerNode:t.selfLoopsPerNode}}recordView(e,t){mf(this,this.state,e,t)}verifyChecksums(){const e=this.state.checksums;if(e===null)throw new P("E_INVALID_SNAPSHOT","no checksums were recorded for this snapshot",{reason:"no-checksum"});const t=(i,a)=>new P("E_INVALID_SNAPSHOT",`checksum mismatch: ${i} was modified after freeze`,{reason:"checksum",...a}),{state:r}=this,o=[["rowPtr",this.rowPtr],["colIdx",this.colIdx],["weights",this.weights],["arcToEdge",r.arcToEdge],["edgeToArc",r.edgeToArc]];for(const[i,a]of o){const c=e.core.get(i);if(c!==void 0&&a!==null&&mn(a)!==c)throw t(`core array ${i}`,{array:i})}const s=[["nodes",this.nodes],["edges",this.edges],["graph",this.graph],...[...this.extensions].map(([i,a])=>[`extensions[${i}]`,a])];for(const[i,a]of s)for(const c of a){const l=e.columns.get(c);if(l!==void 0&&wf(c)!==l)throw t(`column "${c.meta.name}" of ${i}`,{table:i,column:c.meta.name})}for(const i of ti){const a=r.views[i];if(a!==null)for(const[c,l]of Object.entries(Wa(this,i,a))){const u=e.views.get(`${i}.${c}`);if(u!==void 0&&mn(l)!==u)throw t(`view ${i}.${c}`,{view:i,member:c})}}}edgeEndpoints(){return this.state.views.edgeList??bd(this)}wrapDerived(e){return{snapshot:e.parts===null?this:new yu({...e.parts,checksum:this.state.checksums!==null}),nodeOrigin:e.nodeOrigin,edgeOrigin:e.edgeOrigin,nodeRemap:e.nodeRemap,edgeRemap:e.edgeRemap,blockSizes:e.blockSizes,report:e.report}}materialiseView(e){switch(e){case"reverse":this.reverse();break;case"coo":this.coo();break;case"edgeList":this.edgeList();break;case"outDegree":this.outDegree();break;case"inDegree":this.inDegree();break;case"degree":this.degree();break;case"weightedOutDegree":this.weightedOutDegree();break;case"weightedInDegree":this.weightedInDegree();break;case"weightedDegree":this.weightedDegree();break;case"selfLoopWeight":this.selfLoopWeight();break;case"totalWeight":this.totalWeight();break;case"selfLoopArcs":this.selfLoopArcs();break;case"selfLoopsPerNode":this.selfLoopsPerNode();break;case"mate":this.mate();break;case"degreeOrder":this.degreeOrder();break;case"reverseDegreeOrder":this.degreeOrder({of:"reverse"});break;case"symmetric":this.isSymmetric();break;default:{const t=e;throw new P("E_UNSUPPORTED",`unknown view ${String(t)}`,{view:t})}}}};function bv(n){const e=new Set([n.rowPtr.buffer,n.colIdx.buffer]);n.weights!==null&&e.add(n.weights.buffer),n.arcToEdge!==null&&e.add(n.arcToEdge.buffer),n.edgeToArc!==null&&e.add(n.edgeToArc.buffer);for(const t of Oy(n.ids))e.add(t);for(const t of e)it(t);it(n.ids),it(n.nodes),it(n.edges),it(n.graph);for(const t of n.extensions.values())it(t)}function pf(n){return new yv(n)}function vv(n){if(typeof n!="object"||n===null)return!1;const e=n;return e[Au]===!0&&e.formatVersion===Mr}function Av(n,e){let t=0;for(const r of ti){const o=e[r];o!==null&&!(r==="reverseDegreeOrder"&&o===e.degreeOrder)&&(t+=Rb(n,r,o))}return t}function Ev(n){let e=0;for(const t of[n.nodes,n.edges,n.graph,...n.extensions.values()])for(const r of t)e+=r.byteLength;return e}function mf(n,e,t,r){const o=e.checksums;if(o!==null)for(const[s,i]of Object.entries(Wa(n,t,r)))o.views.set(`${t}.${s}`,mn(i))}function Yr(n,e,t){const r=tc.get(n);return r?.views[e]!==null?!1:(r.views[e]=t,mf(n,r,e,t),!0)}function _v(n,e){const t=tc.get(n);return t===void 0?null:t.views[e]}const Iv=new Set(["keep","error","first","last","sum","min","max"]);function yf(n,e,t){if(typeof e!="string"||!Iv.has(e))throw t(n,e);return e}const kv="graphty.weight";function nc(){return performance.now()}function Sv(n){if(n.selfLoopCount===0)return;const e=n.edgeBound;for(let t=0;t<e;t++)if(n.edgeAlive.get(t)&&n.src.get(t)===n.dst.get(t)){const r=n.src.get(t);throw new P("E_SELF_LOOP",`edge ${t} is a self-loop at node ${r}`,{edge:t,node:r})}}function Pv(n){const e=n.edgeAlive.view().slice(),t=n.src.view(),r=n.dst.view(),o=n.edgeBound;for(let s=0;s<o;s++)t[s]===r[s]&&Le(e,s)&&Kt(e,s);return e}function bf(n,e){const t=n.edgeBound;return{directed:e,nodeCount:n.nodeBound,edgeCount:t,src:n.src.view(),dst:n.dst.view(),weights:n.weight===null?null:n.weight.view()}}function xv(n,e,t,r,o,s){const{rowPtr:i,colIdx:a,arcToEdge:c}=n.core,l=e.nodeBound,u=e.edgeBound,d={staging:e,weights:e.weight===null?null:e.weight.view(),policy:r,countMultiplicity:o,builderIndex:s},f=new Uint32Array(u);for(let w=0;w<u;w++)f[w]=w;const h={survivorOf:f,reduced:null,stored:null,explicit:null,merged:0},g=[];for(let w=0;w<l;w++){const p=i[w+1];let m=i[w];for(;m<p;){const y=a[m],b=Cv(a,m,p);b-m>1&&(t||y>=w)&&(Nv(g,c,m,b),Tv(d,h,w,y,g)),m=b}}return h.merged===0?null:{...h}}function Cv(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Nv(n,e,t,r){n.length=0;for(let o=t;o<r;o++)n.push(e===null?o:e[o])}function Tv(n,e,t,r,o){const{policy:s,staging:i,builderIndex:a}=n;if(s==="error"){const f=[a(o[0]),a(o[1])];throw new P("E_DUPLICATE_EDGE",`edges ${f[0]} and ${f[1]} both connect ${t} -> ${r}`,{source:t,target:r,edges:f})}const c=s==="last"?o[o.length-1]:o[0],l=Ov(n,t,r,o),u=e.survivorOf.length;l!==null&&(e.reduced??=new Float64Array(u),e.stored??=new Uint32Array(Fe(u)),e.reduced[c]=l,Ht(e.stored,c)),(l!==null||o.some(f=>i.weightExplicit(f)))&&!i.weightExplicit(c)&&(e.explicit??=new Uint32Array(Fe(u)),Ht(e.explicit,c));for(const f of o)f!==c&&(e.survivorOf[f]=c,e.merged++)}function Ov(n,e,t,r){const{policy:o}=n;if(o!=="sum"&&o!=="min"&&o!=="max")return null;const s=$v(n.weights,r,o,n.countMultiplicity);if(s!==null&&Number.isNaN(s)){const i=r.map(n.builderIndex);throw new P("E_INVALID_WEIGHT",`duplicateEdges "${o}" over edges ${i.join(", ")} (${e} -> ${t}) yields NaN`,{source:e,target:t,edges:i,policy:o,reason:"reducer"})}return s}function $v(n,e,t,r){if(n===null)return t==="sum"&&r?e.length:null;let o=n[e[0]];for(let s=1;s<e.length;s++){const i=n[e[s]];switch(t){case"sum":o+=i;break;case"min":o=Math.min(o,i);break;case"max":o=Math.max(o,i);break;default:{const a=t;throw new P("E_UNSUPPORTED",`unknown reducer ${a}`,{policy:a})}}}return o}function Rv(n,e,t){const{weight:r}=n;if(r===null||e===0)return null;const o=r.view(),s=t==="f64"&&Dv(o,e),i=n.weightSet!==null||n.weightMode==="omitted";if(!s&&!i)return null;const a=s?"f64":"f32",c=ht(kv,"edge",{dtype:a,role:"weight",nullable:i}),l=a==="f64"?new Float64Array(e):new Float32Array(e);l.set(o.subarray(0,e));const u=i?Lv(n,e):null;return Tt({...Gr(c,e,u),data:l})}function Dv(n,e){for(let t=0;t<e;t++){const r=n[t];if(Math.fround(r)!==r)return!0}return!1}function Lv(n,e){const t=new Uint32Array(Fe(e));for(let r=0;r<e;r++)n.weightExplicit(r)&&Ht(t,r);return t}function Mv(n,e){return n.ids===null||n.idToIndex===null?nd(e):rd(n.ids,e,{map:n.idToIndex})}function rc(n,e,t,r=[]){const o=t.map(i=>i.toColumn(e)),s=new wn({domain:n,rowCount:e,columns:[...o,...r]});return lb(s),s}function Uv(n){const e=[];for(const[t,r]of n)e.push(xa("graph",1,t,[r.value],r.decl??{}));return new wn({domain:"graph",rowCount:1,columns:e})}function Fv(n,e,t,r){if(e===null&&t===null)return null;const o=new Uint32Array(n);for(let s=0;s<n;s++){let i=e===null?s:e.remap[s];i!==x&&t!==null&&r!==null&&(i=r.remap[t.survivorOf[i]]),o[s]=i}return qr(o)?null:o}function Bv(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return{remap:e,origin:e,count:n}}function ri(n,e){return new P("E_UNSUPPORTED",`freeze option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function zv(n){n.duplicateEdges!==void 0&&yf("duplicateEdges",n.duplicateEdges,ri);for(const e of["arena","release","profile","checksum"]){const t=n[e];if(t!==void 0&&typeof t!="boolean")throw ri(e,t)}if(n.label!==void 0&&typeof n.label!="string")throw ri("label",n.label);if(n.prepare!==void 0&&!Array.isArray(n.prepare))throw ri("prepare",n.prepare)}function Gv(n,e){const t=e.profile===!0,r={},o=t?nc():0;let s=o;const i=H=>{if(t){const Y=nc();r[H]=(r[H]??0)+(Y-s),s=Y}},{directed:a}=n,c=n.staging;zv(e);const l=e.arena!==!1,u=e.duplicateEdges??n.options.duplicateEdges,d=n.options.selfLoops,f=c.nodeBound,h=c.edgeBound,g=h-c.liveEdgeCount;d==="error"&&Sv(c);const w=a?c.liveEdgeCount:2*c.liveEdgeCount-c.selfLoopCount;if(w>Te)throw new P("E_TOO_LARGE",`arc count ${w} exceeds MAX_COUNT`,{count:w,max:Te});let p=c,m=null,y=null,b=0;const v=d==="drop"&&c.selfLoopCount>0;if(c.hasTombstones||v){const H=ad(f,c.nodeAlive.view()),Y=ad(h,v?Pv(c):c.edgeAlive.view());b=v?c.selfLoopCount:0,p=cd(c,{nodes:H,edges:Y,edgeValues:null,mergedWeights:null,mergedWeightStored:null,mergedWeightSet:null}),m=H,y=Y}i("compact");const A=p.nodeBound;let E=Ya(bf(p,a),l&&u==="keep");i("sort");let I=null,k=null;if(u!=="keep"){const H=y;if(I=xv(E,p,a,u,n.options.weighted!==!1,Y=>H===null?Y:H.origin[Y]),I!==null){const{survivorOf:Y}=I,ee=eb(Y);let Z=null,J=null;if(I.reduced!==null&&I.stored!==null){Z=new Float64Array(ee.count),J=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.stored,ne)&&(Z[ee.remap[ne]]=I.reduced[ne],Ht(J,ee.remap[ne]))}let ce=null;if(I.explicit!==null){ce=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.explicit,ne)&&Ht(ce,ee.remap[ne])}const de=new Uint32Array(Y.length);for(let ne=0;ne<Y.length;ne++)de[ne]=ee.remap[Y[ne]];p=cd(p,{nodes:Bv(A),edges:ee,edgeValues:de,mergedWeights:Z,mergedWeightStored:J,mergedWeightSet:ce}),k=ee,E=Ya(bf(p,a),l)}else l&&(E={...E,core:mb(E.core)});i("duplicates")}const N=p.edgeBound,{core:C,arcCount:O,selfLoopCount:T,flags:$}=E,L=Rv(p,N,n.options.weightDtype);i("weights");const F=Mv(p,A);i("ids");const M=rc("node",A,p.nodeColumns),R=rc("edge",N,p.edgeColumns,L===null?[]:[L]),D=Uv(n.graphValues),U=new Map;for(const H of p.extensions)U.set(H.name,rc("extension",H.rowCount,H.columns));i("columns");const B={label:e.label??null,serial:null,directed:a,nodeCount:A,edgeCount:N,arcCount:O,selfLoopCount:T,rowPtr:C.rowPtr,colIdx:C.colIdx,weights:C.weights,arcToEdge:C.arcToEdge,edgeToArc:C.edgeToArc,flags:$,ids:F,nodes:M,edges:R,graph:D,extensions:U,meta:n.meta,arena:C.arena,checksum:e.checksum===!0},V=pf(B);e.prepare!==void 0&&e.prepare.length>0&&V.prepare(e.prepare),i("snapshot"),t&&(r.total=nc()-o);const W=m!==null&&!qr(m.remap)?m.remap:null,q=Fv(h,y,I,k),K=I===null?0:I.merged,X=Object.freeze({nodeRemap:W,edgeRemap:q,compacted:W!==null||q!==null,droppedSelfLoops:b,mergedEdges:K,droppedEdges:g+b+K,widened:Object.freeze(n.widened.map(H=>Object.freeze({...H}))),timings:Object.freeze({...r})});return{snapshot:V,report:X,staging:p}}const Wv=new Set(["keep","drop","error"]),Vv=new Set(["f32","f64"]),jv="graphty.directed",qv="graphty.pair";function Kn(n,e){return new P("E_UNSUPPORTED",`builder option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function Hv(n){if(typeof n!="object"||n===null)throw Kn("options",n);if(typeof n.directed!="boolean")throw Kn("directed",n.directed);const e=n.weighted??"auto";if(e!=="auto"&&typeof e!="boolean")throw Kn("weighted",e);const t=n.weightDtype??"f32";if(!Vv.has(t))throw Kn("weightDtype",t);const r=yf("duplicateEdges",n.duplicateEdges??"keep",Kn),o=n.selfLoops??"keep";if(!Wv.has(o))throw Kn("selfLoops",o);const s=n.addMissingNodes??!0;if(typeof s!="boolean")throw Kn("addMissingNodes",s);const i=a=>{const c=n[a];if(c===void 0)return null;if(!Number.isInteger(c)||c<0)throw Kn(a,c);return c};return{fixed:{weighted:e,weightDtype:t,duplicateEdges:r,selfLoops:o,addMissingNodes:s,expectedNodes:i("expectedNodes"),expectedEdges:i("expectedEdges")},directed:n.directed}}function Kv(n){const e={};for(const t of Object.keys(n)){const r=n[t];r!==void 0&&(e[t]=r)}return e}function vf(n,e){return n.dtype===e.dtype&&n.components===e.components&&n.itemDtype===e.itemDtype&&n.itemComponents===e.itemComponents}class oi{constructor(e){this.locked=!1,this.optionsCache=null,this.nodeNames=null,this.edgeNames=null,this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutations=0,this.dirtyFlag=!0,this.disposed=!1;const t=Hv(e);this.fixed=t.fixed,this.directedValue=t.directed,this.staging=this.freshStaging()}static from(e,t){const r=Kv(t??{}),o=e.edges.byRole("weight"),s=r.weightDtype??(o!==null&&o.dtype==="f64"?"f64":void 0),i=r.weighted??(e.flags.weighted?!0:void 0),a=new oi({directed:e.directed,expectedNodes:e.nodeCount,expectedEdges:e.edgeCount,...r,...s===void 0?{}:{weightDtype:s},...i===void 0?{}:{weighted:i}});return a.addGraph(e,{onDuplicateNode:"error"}),a.setMeta(e.meta),a}get options(){return this.check(),this.optionsCache??=Object.freeze({directed:this.directedValue,...this.fixed}),this.optionsCache}get directed(){return this.check(),this.directedValue}get directedLocked(){return this.check(),this.locked}get nodeCount(){return this.check(),this.staging.liveNodeCount}get edgeCount(){return this.check(),this.staging.liveEdgeCount}get nodeBound(){return this.check(),this.staging.nodeBound}get edgeBound(){return this.check(),this.staging.edgeBound}get mutationCount(){return this.check(),this.mutations}get dirty(){return this.check(),this.dirtyFlag}setDirected(e,t){if(this.check(),e!==this.directedValue){if(this.locked)throw new P("E_DIRECTED","the builder's direction is locked",{reason:"locked",directed:this.directedValue});if(this.staging.liveEdgeCount===0){this.directedValue=e,this.optionsCache=null,this.mutated();return}if(!e)throw new P("E_DIRECTED","a builder with edges cannot become undirected",{reason:"edges present",edgeCount:this.staging.liveEdgeCount});if(t?.expand!==!0)throw new P("E_DIRECTED","an undirected builder with edges becomes directed only with { expand: true }",{reason:"expand required",edgeCount:this.staging.liveEdgeCount});this.expandToDirected()}}lockDirected(){this.check(),this.locked=!0}addNode(e){return this.check(),this.addValidatedNode(jn(e))}addNodes(e,t){this.check();const o=(Array.isArray(e)?e:[...e]).map(i=>jn(i));if(t!==void 0&&t.length<o.length)throw new P("E_COLUMN_LENGTH",`out has ${t.length} entries for ${o.length} ids`,{expected:o.length,found:t.length});const s=t??new Uint32Array(o.length);for(let i=0;i<o.length;i++)s[i]=this.addValidatedNode(o[i]);return s}addAnonymousNodes(e){if(this.check(),!Number.isInteger(e)||e<0)throw new P("E_INDEX_RANGE",`node count ${e} is not a non-negative integer`,{count:e});const{staging:t}=this,r=t.nodeBound;if(this.checkNodeLimit(e),t.idToIndex!==null){for(let o=r;o<r+e;o++)if(t.idToIndex.has(o))throw new P("E_DUPLICATE_ID",`node id ${o} exists; anonymous node ${o} cannot use it`,{id:o,index:t.idToIndex.get(o)})}return t.pushAnonymousNodes(e),e>0&&this.mutated(),r}hasNode(e){return this.check(),this.lookup(e)!==x}indexOf(e){return this.check(),this.lookup(e)}idOf(e){this.check();const{staging:t}=this;if(!this.isLiveNode(e))throw new P("E_INDEX_RANGE",`node index ${e} is out of range or removed`,{index:e,bound:t.nodeBound});return t.ids===null?e:t.ids[e]}removeNode(e){this.check();const t=this.lookup(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return this.removeLiveNode(t)}removeNodeByIndex(e){if(this.check(),!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e});return this.removeLiveNode(e)}reserve(e,t){this.check();const r=(i,a)=>{if(a===void 0)return 0;if(!Number.isInteger(a)||a<0||a>Te)throw new P("E_TOO_LARGE",`reserve(${i}) ${a} is not an integer in [0, MAX_COUNT]`,{field:i,count:a,max:Te});return a},o=r("nodes",e),s=r("edges",t);$a(o),this.staging.reserve(o,s)}addEdge(e,t,r){this.check();const o=this.checkWeight(r,void 0),s=this.resolveEndpoint(jn(e)),i=this.resolveEndpoint(jn(t));return this.pushEdge(s,i,o)}addEdgeByIndex(e,t,r){this.check();const o=this.checkWeight(r,void 0);return this.checkLiveNode(e),this.checkLiveNode(t),this.pushEdge(e,t,o)}addEdges(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdges: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});for(let c=0;c<o;c++)this.checkLiveNode(e[c]),this.checkLiveNode(t[c]);let s=null;if(r!==void 0){for(let c=0;c<o;c++)this.checkWeight(r[c],c);s=this.fixed.weighted===!1?null:r}this.checkEdgeLimit(o,this.arcsOf(e,t,o));const{staging:i}=this;i.reserve(0,i.edgeBound+o);const a=i.pushEdges(e,t,s);return o>0&&this.mutated(),a}addEdgesByIds(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdgesByIds: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});const s=new Array(o),i=new Array(o),a=new Array(o);for(let l=0;l<o;l++)s[l]=jn(e[l]),i[l]=jn(t[l]),a[l]=this.checkWeight(r===void 0?void 0:r[l],l);if(!this.fixed.addMissingNodes)for(let l=0;l<o;l++)this.requireLive(s[l]),this.requireLive(i[l]);this.checkEdgeLimit(o,this.directedValue?o:2*o);const c=this.staging.edgeBound;for(let l=0;l<o;l++){const u=this.resolveEndpoint(s[l]),d=this.resolveEndpoint(i[l]);this.staging.pushEdge(u,d,a[l])}return o>0&&this.mutated(),c}removeEdge(e){return this.check(),this.isLiveEdge(e)?(this.staging.killEdge(e),this.mutated(),!0):!1}hasEdge(e){return this.check(),this.isLiveEdge(e)}edgeEndpoints(e){return this.check(),this.checkEdge(e),[this.staging.src.get(e),this.staging.dst.get(e)]}edgeWeight(e){this.check(),this.checkEdge(e);const{weight:t}=this.staging;return t===null?1:t.get(e)}setEdgeWeight(e,t){this.check(),this.checkEdge(e);const r=this.checkWeight(t,void 0),{staging:o}=this;r!==void 0&&(o.ensureWeights().set(e,r),o.trackWeight(e,!0)),this.mutated()}outEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.outEdges(e):this.staging.incidentEdges(e)}inEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.inEdges(e):this.staging.incidentEdges(e)}findEdges(e,t){return this.check(),this.checkNodeIndex(e),this.checkNodeIndex(t),this.staging.edgesBetween(e,t,this.directedValue)}declareNodeColumn(e){return this.check(),this.declare("node",e)}declareEdgeColumn(e){return this.check(),this.declare("edge",e)}nodeColumn(e){return this.check(),this.handleOf(this.staging.nodeColumns,e)}edgeColumn(e){return this.check(),this.handleOf(this.staging.edgeColumns,e)}setNodeValue(e,t,r){this.check(),this.checkNodeIndex(t),this.writeCell("node",e,t,r)}setEdgeValue(e,t,r){this.check(),this.checkEdgeIndex(t),this.writeCell("edge",e,t,r)}widenNodeColumn(e,t){this.check(),this.widenColumn("node",e,t)}widenEdgeColumn(e,t){this.check(),this.widenColumn("edge",e,t)}setNodeColumn(e,t,r){this.check(),this.setBulkColumn("node",this.staging.nodeBound,e,t,r??{})}setEdgeColumn(e,t,r){this.check(),this.setBulkColumn("edge",this.staging.edgeBound,e,t,r??{})}setGraphValue(e,t,r){this.check();const o=r??{};ht(e,"graph",{dtype:"json",...o}),t!==void 0&&Qv(e,t,o),this.graphValues.set(e,{decl:o,value:t}),this.mutated()}setMeta(e){this.check(),this.metaValue=Ky(this.metaValue,e),this.mutated()}addExtensionTable(e,t){this.check();const{staging:r}=this;if(r.extensions.some(s=>s.name===e))throw new P("E_COLUMN_EXISTS",`extension table "${e}" already exists`,{table:e});const o=[];for(const s of t){const i=jr(s.name,"extension",s,!1);if(o.some(a=>a.meta.name===i.meta.name))throw new P("E_COLUMN_EXISTS",`column "${s.name}" is declared twice in "${e}"`,{table:e,column:s.name});Xr(o,i.meta,e),o.push(i)}return r.extensions.push({name:e,columns:o,rowCount:0}),this.mutated(),r.extensions.length-1}addExtensionRow(e,t){this.check();const r=this.extensionOf(e);if(t.length!==r.columns.length)throw new P("E_COLUMN_LENGTH",`extension table "${r.name}" has ${r.columns.length} columns; ${t.length} values given`,{table:r.name,expected:r.columns.length,found:t.length});const o=r.rowCount,s=r.columns.map((i,a)=>{const c=this.checkReference(i.meta,t[a]);return i.checkValue(o,c),c});for(let i=0;i<s.length;i++)r.columns[i].write(o,s[i]);return r.rowCount=o+1,this.mutated(),o}addNodeRecord(e,t){this.check();const r=jn(e),o=Object.keys(t);this.checkCells("node",this.prospectiveNodeIndex(r),o,t);const s=this.addValidatedNode(r);for(const i of o)this.writeCell("node",i,s,t[i]);return s}addEdgeRecord(e,t,r,o){this.check();const s=o===void 0?"weight":o;let i;if(s!==null&&Object.prototype.hasOwnProperty.call(r,s)){const l=r[s];if(l!=null){if(typeof l!="number")throw new P("E_INVALID_WEIGHT",`edge weight "${s}" is not a number`,{key:s,found:typeof l});i=l}}const a=Object.keys(r).filter(l=>l!==s);this.checkWeight(i,void 0),this.checkCells("edge",this.staging.edgeBound,a,r);const c=this.addEdge(e,t,i);for(const l of a)this.writeCell("edge",l,c,r[l]);return c}addGraph(e,t){this.check();const r=t?.onDuplicateNode??"merge";if(r!=="merge"&&r!=="error")throw new P("E_UNSUPPORTED",`addGraph option onDuplicateNode has an unsupported value ${String(r)}`,{field:"onDuplicateNode",found:r,reason:"unsupported option"});if(e.directed!==this.directedValue)throw new P("E_DIRECTED",`a ${e.directed?"directed":"undirected"} snapshot cannot be appended to a ${this.directedValue?"directed":"undirected"} builder`,{reason:"direction mismatch",directed:this.directedValue,found:e.directed});const{staging:o}=this,{nodeCount:s,edgeCount:i}=e,a=o.ids===null&&o.nodeBound===0&&e.ids.kind==="identity"&&e.ids.offset===0,c=new Uint32Array(s);let l=s;if(!a){l=0;for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);if(m===x)l++;else if(r==="error")throw new P("E_DUPLICATE_ID",`node id ${Pn(p)} already exists`,{id:p,index:m})}}this.checkNodeLimit(l);const u=e.edgeList();this.checkEdgeLimit(i,this.arcsOf(u.src,u.dst,i));const d=e.edges.byRole("weight"),f=new Array(i);for(let w=0;w<i;w++){let p;d!==null?p=d.isSet(w)?d.value(w):void 0:u.weights!==null&&(p=u.weights[w]),f[w]=this.checkWeight(p,w)}for(const w of e.nodes)this.checkIncomingColumn("node",w);for(const w of e.edges)w!==d&&this.checkIncomingColumn("edge",w);for(const[w,p]of e.extensions)this.checkIncomingExtension(w,p);if(a){const w=this.addAnonymousNodes(s);for(let p=0;p<s;p++)c[p]=w+p}else for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);c[w]=m===x?this.addValidatedNode(p):m}e.flags.weighted&&this.fixed.weighted!==!1&&o.ensureWeights();const h=new Uint32Array(i);for(let w=0;w<i;w++)h[w]=this.pushEdge(c[u.src[w]],c[u.dst[w]],f[w]);const g={node:c,edge:h};for(const w of e.nodes)this.copyColumn("node",w,c,g);for(const w of e.edges)w!==d&&this.copyColumn("edge",w,h,g);for(const w of e.graph)w.isSet(0)&&this.setGraphValue(w.meta.name,w.value(0),Sn(w.meta));for(const[w,p]of e.extensions)this.appendExtension(w,p,g);this.mutated()}freeze(e){return this.freezeWithReport(e).snapshot}freezeWithReport(e){this.check();const t=e??{},r={staging:this.staging,directed:this.directedValue,options:this.options,graphValues:this.graphValues,meta:this.metaValue,widened:this.widenings},o=Gv(r,t);return this.staging=o.staging,this.widenings=[],this.dirtyFlag=!1,t.release===!0&&(this.staging=this.freshStaging()),{snapshot:o.snapshot,report:o.report}}clear(){this.check(),this.staging=this.freshStaging(),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutated()}dispose(){this.disposed||(this.staging=new La({weightDtype:this.fixed.weightDtype,weighted:!1,expectedNodes:null,expectedEdges:null,resizable:void 0}),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.disposed=!0)}byteLength(){return this.check(),this.staging.byteLength()}check(){if(this.disposed)throw new P("E_BUILDER_DISPOSED","the builder was disposed",{})}mutated(){this.mutations++,this.dirtyFlag=!0}freshStaging(){return new La({weightDtype:this.fixed.weightDtype,weighted:this.fixed.weighted===!0,expectedNodes:this.fixed.expectedNodes,expectedEdges:this.fixed.expectedEdges,resizable:void 0})}prospectiveNodeIndex(e){const{staging:t}=this;return t.idToIndex===null?typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<t.nodeBound?e:t.nodeBound:t.idToIndex.get(typeof e=="number"&&e===0?0:e)??t.nodeBound}lookup(e){const{staging:t}=this;if(t.idToIndex===null)return typeof e!="number"||!Number.isInteger(e)||e<0||e>=t.nodeBound?x:t.nodeAlive.get(e)?e:x;const r=t.idToIndex.get(typeof e=="number"&&e===0?0:e);return r===void 0||!t.nodeAlive.get(r)?x:r}isLiveNode(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.nodeBound&&t.nodeAlive.get(e)}isLiveEdge(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.edgeBound&&t.edgeAlive.get(e)}checkNodeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.nodeBound)throw new P("E_INDEX_RANGE",`node index ${e} is out of range`,{index:e,bound:this.staging.nodeBound})}checkEdgeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.edgeBound)throw new P("E_INDEX_RANGE",`edge index ${e} is out of range`,{edge:e,bound:this.staging.edgeBound})}checkLiveNode(e){if(!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e})}checkEdge(e){if(!this.isLiveEdge(e))throw new P("E_INDEX_RANGE",`edge index ${e} is out of range or removed`,{edge:e,bound:this.staging.edgeBound})}checkNodeLimit(e){if(this.staging.nodeBound+e>Te)throw new P("E_TOO_LARGE",`node count ${this.staging.nodeBound+e} exceeds MAX_COUNT`,{count:this.staging.nodeBound+e,max:Te})}checkEdgeLimit(e,t){const{staging:r}=this,o=r.edgeBound+e,i=(this.directedValue?r.liveEdgeCount:2*r.liveEdgeCount-r.selfLoopCount)+t;if(o>Te||i>Te)throw new P("E_TOO_LARGE",`edge count ${o} (${i} arcs) exceeds MAX_COUNT`,{count:o,arcs:i,max:Te})}arcsOf(e,t,r){if(this.directedValue)return r;let o=0;for(let s=0;s<r;s++)o+=e[s]===t[s]?1:2;return o}addValidatedNode(e){const{staging:t}=this;t.materialiseIds();const o=t.idToIndex.get(e);if(o!==void 0)return t.nodeAlive.get(o)||(t.nodeAlive.set(o,!0),t.liveNodeCount++,this.mutated()),o;this.checkNodeLimit(1);const s=t.pushNode(typeof e=="string"?Ro(e):e);return this.mutated(),s}resolveEndpoint(e){const t=this.lookup(e);if(t!==x)return t;if(this.fixed.addMissingNodes)return this.addValidatedNode(e);throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}requireLive(e){if(this.lookup(e)===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}removeLiveNode(e){const{staging:t}=this,r=[];for(let o=t.firstOut.get(e);o!==x;o=t.nextOut.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));for(let o=t.firstIn.get(e);o!==x;o=t.nextIn.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));return t.nodeAlive.set(e,!1),t.liveNodeCount--,this.mutated(),Uint32Array.from(r).sort()}checkWeight(e,t){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new P("E_INVALID_WEIGHT",`weight ${String(e)} is not a number`,{weight:e,...t===void 0?{}:{edge:t}});if(this.fixed.weighted===!1){if(e!==1)throw new P("E_INVALID_WEIGHT",`weight ${e} on a builder declared unweighted`,{weight:e,reason:"unweighted builder",...t===void 0?{}:{edge:t}});return}return e}}pushEdge(e,t,r){this.checkEdgeLimit(1,this.directedValue||e===t?1:2);const o=this.staging.pushEdge(e,t,r);return this.mutated(),o}expandToDirected(){const{staging:e}=this,t=e.liveEdgeCount;this.checkEdgeLimit(t,t);const r={name:jv,dtype:"bool",role:"directed"},o={name:qv,dtype:"u32",role:"pair",refersTo:"edge"};this.checkDeclaration("edge",r),this.checkDeclaration("edge",o);const s=this.declare("edge",r),i=this.declare("edge",o),a=e.edgeColumns[s],c=e.edgeColumns[i],l=e.edgeBound;for(let u=0;u<l;u++){if(!e.edgeAlive.get(u))continue;a.write(u,!1);const d=e.src.get(u),f=e.dst.get(u);if(d===f)continue;const g=e.weightExplicit(u)&&e.weight!==null?e.weight.get(u):void 0,w=e.pushEdge(f,d,g);a.write(w,!1),c.write(u,w),c.write(w,u)}this.directedValue=!0,this.optionsCache=null,this.mutated()}columnsOf(e){return e==="node"?this.staging.nodeColumns:this.staging.edgeColumns}handleOf(e,t){const r=this.columnIndex(e,t);return r<0?x:r}columnIndex(e,t){let o=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;if(o?.columns!==e||o.map.size!==e.length){const s=new Map;for(let i=0;i<e.length;i++)s.set(e[i].meta.name,i);o={columns:e,map:s},e===this.staging.nodeColumns?this.nodeNames=o:e===this.staging.edgeColumns&&(this.edgeNames=o)}return o.map.get(t)??-1}pushColumn(e,t){e.push(t);const r=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;return r!==null&&r.columns===e&&r.map.size===e.length-1&&r.map.set(t.meta.name,e.length-1),e.length-1}declare(e,t){const{meta:r,existing:o}=this.checkDeclaration(e,t);if(o!==x)return o;const s=this.columnsOf(e);return this.mutated(),this.pushColumn(s,new Ws(r,!1))}checkDeclaration(e,t){if(typeof t.name!="string"||t.name.length===0)throw new P("E_COLUMN_TYPE","a column declaration needs a non-empty name",{field:"name",found:t.name});const r=ht(t.name,e,t),o=this.columnsOf(e),s=this.columnIndex(o,r.name);if(s>=0){if(vf(o[s].meta,r))return{meta:r,existing:s};throw new P("E_COLUMN_EXISTS",`${e} column "${r.name}" is already declared as ${o[s].meta.dtype}`,{column:r.name,domain:e,found:o[s].meta.dtype,expected:r.dtype})}return Xr(o,r,e),{meta:r,existing:x}}resolveColumn(e,t,r){const o=this.columnsOf(e);if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>=o.length)throw new P("E_UNKNOWN_COLUMN",`no ${e} column with handle ${t}`,{domain:e,handle:t});return o[t]}const s=this.columnIndex(o,t);if(s>=0)return o[s];if(r==null)return null;const i=Ra(r),a=jr(t,e,{dtype:i,nullable:!0},!0);return this.pushColumn(o,a),a}checkCells(e,t,r,o){const s=this.columnsOf(e);for(const i of r){const a=o[i],c=this.columnIndex(s,i),l=c<0?void 0:s[c];l!==void 0?l.checkValue(t,this.checkReference(l.meta,a)):a!=null&&(Ra(a),typeof a=="string"?wr(a,{column:i,row:t}):typeof a=="object"&&cn(a,`${i}[${t}]`))}}checkReference(e,t){if(e.refersTo===null||t===void 0||t===null)return t;const r=e.refersTo==="node"?this.staging.nodeBound:this.staging.edgeBound,o=s=>{if(typeof s=="number"&&s!==x&&!(s>=0&&s<r))throw new P("E_INDEX_RANGE",`column "${e.name}" refers to ${String(e.refersTo)} ${s}, which is not below ${r}`,{column:e.name,refersTo:e.refersTo,found:s,bound:r})};if(Array.isArray(t)){for(const s of t)o(s);return t}return o(t),t===x?void 0:t}checkIncomingColumn(e,t){const r=this.columnsOf(e);this.columnIndex(r,t.meta.name)<0&&Xr(r,t.meta,e)}checkIncomingExtension(e,t){const r=this.staging.extensions.find(s=>s.name===e),o=[...t];if(r===void 0){const s=[];for(const i of o){const a={...Sn(i.meta),name:i.meta.name},c=jr(a.name,"extension",a,!1);if(s.some(l=>l.meta.name===c.meta.name))throw new P("E_COLUMN_EXISTS",`column "${a.name}" is declared twice in "${e}"`,{table:e,column:a.name});Xr(s,c.meta,e),s.push(c)}return}for(const s of o)if(!r.columns.some(i=>i.meta.name===s.meta.name))throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${s.meta.name}"`,{table:e,column:s.meta.name})}widenColumn(e,t,r){const o=this.columnsOf(e);let s;if(typeof t=="number")s=Number.isInteger(t)&&t>=0&&t<o.length?o[t]:void 0;else{const c=this.columnIndex(o,t);s=c<0?void 0:o[c]}if(s===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${e} column ${String(t)}`,{domain:e,column:t});const i=s.inferredDtype;if(i===null)throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is declared, not inferred`,{column:s.meta.name,domain:e});if(pr(r)<0)throw new P("E_COLUMN_TYPE",`${r} is not a dtype inference widens to`,{column:s.meta.name,dtype:r});const a=r;if(pr(a)<pr(i))throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is ${i}; it cannot narrow to ${a}`,{column:s.meta.name,found:i,expected:a});a!==i&&(s.widenTo(a),this.widenings.push({column:s.meta.name,domain:e,from:i,to:a}),this.mutated())}writeCell(e,t,r,o){const s=this.resolveColumn(e,t,o);if(s===null)return;const i=s.write(r,this.checkReference(s.meta,o));i!==null&&this.widenings.push({column:s.meta.name,domain:e,from:i.from,to:i.to}),this.mutated()}setBulkColumn(e,t,r,o,s){const i=Jv(e,t,r,o,s,{node:this.staging.nodeBound,edge:this.staging.edgeBound}),a=this.columnsOf(e),c=this.columnIndex(a,r);Xr(a.filter(l=>l.meta.name!==r),i.meta,e),c>=0?a[c]=i:this.pushColumn(a,i),this.mutated()}extensionOf(e){const{extensions:t}=this.staging;if(!Number.isInteger(e)||e<0||e>=t.length)throw new P("E_INDEX_RANGE",`no extension table with handle ${e}`,{handle:e});return t[e]}copyColumn(e,t,r,o){const s=this.columnsOf(e),{name:i}=t.meta;let a=this.columnIndex(s,i);if(a<0){const u={...Sn(t.meta)};Xr(s,t.meta,e),a=this.pushColumn(s,jr(i,e,u,!1))}else{const u=s[a];if(!vf(u.meta,t.meta)){const d=Xv(Da(u.meta.dtype),Da(t.meta.dtype));if(u.meta.dtype!==d){const f=u.meta.dtype;u.widenTo(d),this.widenings.push({column:i,domain:e,from:f,to:d})}}}const c=s[a],l=Af(t.meta,o);for(let u=0;u<t.length;u++){if(!t.isSet(u))continue;let d=t.value(u);l!==null&&(d=Ef(d,l),d===void 0)||c.write(r[u],d)}}appendExtension(e,t,r){const{staging:o}=this,s=[...t];let i=o.extensions.find(l=>l.name===e);if(i===void 0){const l=s.map(d=>({...Sn(d.meta),name:d.meta.name})),u=this.addExtensionTable(e,l);i=o.extensions[u]}const a=i.columns,c=i.rowCount;for(const l of s){const u=a.find(d=>d.meta.name===l.meta.name);if(u===void 0)throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${l.meta.name}"`,{table:e,column:l.meta.name});Yv(u,l,c,Af(l.meta,r))}for(const l of a)l.ensureLength(c+t.rowCount);i.rowCount=c+t.rowCount}}function Yv(n,e,t,r){for(let o=0;o<e.length;o++){if(!e.isSet(o)){n.ensureLength(t+o+1);continue}let s=e.value(o);if(r!==null&&(s=Ef(s,r),s===void 0)){n.ensureLength(t+o+1);continue}n.write(t+o,s)}}function Xr(n,e,t){if(e.role===null)return;const r=n.find(o=>o.meta.name!==e.name&&o.meta.role===e.role);if(r!==void 0)throw new P("E_DUPLICATE_ROLE",`role "${e.role}" is already held by column "${r.meta.name}" in ${t}`,{role:e.role,column:e.name,holder:r.meta.name})}function Xv(n,e){return pr(n)>=pr(e)?n:e}function Af(n,e){switch(n.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ef(n,e){if(typeof n=="number")return n<e.length?e[n]:void 0;if(typeof n=="object"&&n!==null){const t=Array.from(n),r=t.filter(o=>o<e.length).map(o=>e[o]);return r.length===0&&t.length>0?void 0:r}throw new P("E_COLUMN_TYPE",`a refersTo cell holds a ${typeof n}, not an index or a list`,{found:typeof n,reason:"refersTo"})}function Qv(n,e,t){jr(n,"graph",t.dtype===void 0?{...t,dtype:Ra(e)}:t,t.dtype===void 0).write(0,e)}function Jv(n,e,t,r,o,s){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=jr(t,n,{nullable:!1,...o,dtype:a},!1),{components:u}=l.meta;let d;switch(a){case"bool":d=Math.ceil(e/32);break;case"dict":d=e;break;case"f32":case"f64":case"i32":case"u32":case"u8":d=e*u;break;default:throw new P("E_COLUMN_TYPE",`column "${t}": a ${String(a)} column cannot adopt a typed array`,{column:t,field:"dtype"})}if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});switch(l.ensureLength(e),a){case"bool":{const f=r;for(let h=0;h<e;h++)l.write(h,(f[h>>>5]>>>(h&31)&1)===1);break}case"dict":{const{dictionary:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no dictionary`,{column:t});for(let h=0;h<e;h++){const g=r[h];if(g>=f.size)throw new P("E_COLUMN_TYPE",`column "${t}": code ${g} at row ${h} is outside the ${f.size} declared options`,{column:t,row:h,code:g});l.write(h,f.values[g])}break}default:{const{typed:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no typed storage`,{column:t});const{refersTo:h}=l.meta,g=h==="node"?s.node:s.edge;for(let w=0;w<r.length;w++){const p=r[w];if(h!==null&&p!==x&&p>=g)throw new P("E_INDEX_RANGE",`column "${t}" refers to ${h} ${p} at row ${w}, which is not below ${g}`,{column:t,row:w,refersTo:h,found:p,bound:g});if(h!==null&&p===x&&l.validity===null)throw new P("E_COLUMN_TYPE",`column "${t}": row ${w} of a non-nullable refersTo column holds INVALID_INDEX`,{column:t,row:w,field:"nullable"});f.set(w,p)}if(l.validity!==null)for(let w=0;w<e;w++)l.validity.set(w,h===null||r[w]!==x);break}}return l}const Zv="id";function eA(n,e){if(e.directed!==void 0&&e.directed!==n)throw new P("E_DIRECTED",`options.directed (${String(e.directed)}) disagrees with the input's directed (${String(n)})`,{reason:"direction mismatch",directed:n,found:e.directed});return{builder:{directed:n,weighted:e.weighted,weightDtype:e.weightDtype,duplicateEdges:e.duplicateEdges,selfLoops:e.selfLoops,addMissingNodes:e.addMissingNodes,expectedNodes:e.expectedNodes,expectedEdges:e.expectedEdges},freeze:{label:e.label,prepare:e.prepare,arena:e.arena,release:e.release,profile:e.profile,checksum:e.checksum}}}function _f(n){return ArrayBuffer.isView(n)}function oc(n,e,t,r,o){const s=_f(o)?o:o.data,i=_f(o)?{}:o.decl;if(ArrayBuffer.isView(s)){e==="node"?n.setNodeColumn(r,s,i):n.setEdgeColumn(r,s,i);return}const a=xa(e,t,r,s,i),c={...Sn(a.meta),name:r,dtype:a.dtype},l=e==="node"?n.declareNodeColumn(c):n.declareEdgeColumn(c);for(let u=0;u<t;u++){if(!a.isSet(u))continue;const d=a.value(u);e==="node"?n.setNodeValue(l,u,d):n.setEdgeValue(l,u,d)}}function si(n,e,t){return new P("E_COLUMN_LENGTH",`${n} has ${t} entries, expected ${e}`,{field:n,expected:e,found:t})}function tA(n){const{nodeCount:e,ids:t}=n;if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new P("E_INDEX_RANGE",`nodeCount ${e} is not a non-negative integer`,{field:"nodeCount",found:e});if(t!==void 0){if(e!==void 0&&e!==t.length)throw si("ids",e,t.length);return t.length}if(e===void 0)throw new P("E_INDEX_RANGE","nodeCount is required when no ids are given",{field:"nodeCount"});return e}function nA(n,e){const t=n.addNodes(e);for(let r=0;r<t.length;r++)if(t[r]!==r){const o=e[r];throw new P("E_DUPLICATE_ID",`ids[${r}] repeats the id of index ${t[r]}`,{id:o,index:t[r],position:r})}}function rA(n){const{src:e,dst:t,weights:r,edgeIds:o}=n;if(t.length!==e.length)throw si("dst",e.length,t.length);if(r!==void 0&&r.length!==e.length)throw si("weights",e.length,r.length);if(o!==void 0&&o.length!==e.length)throw si("edgeIds",e.length,o.length)}function sc(n,e={}){const{src:t,dst:r,weights:o}=n;rA(n);const s=tA(n),i=t.length,a=eA(n.directed,e),c={...a.builder,weightDtype:e.weightDtype??(o instanceof Float64Array?"f64":void 0),expectedNodes:e.expectedNodes??s,expectedEdges:e.expectedEdges??i},l=new oi(c);if(n.ids===void 0?l.addAnonymousNodes(s):nA(l,n.ids),l.addEdges(t,r,o),n.nodeColumns!==void 0)for(const u of Object.keys(n.nodeColumns))oc(l,"node",s,u,n.nodeColumns[u]);if(n.edgeColumns!==void 0)for(const u of Object.keys(n.edgeColumns))oc(l,"edge",i,u,n.edgeColumns[u]);return n.edgeIds!==void 0&&oc(l,"edge",i,Zv,{data:n.edgeIds,decl:{role:"id",unique:!0}}),n.meta!==void 0&&l.setMeta(n.meta),l.freeze(a.freeze)}const at=new DataView(new ArrayBuffer(8));function Qt(n){return at.setFloat64(0,n,!0),at.getInt32(4,!0)}function If(n){return at.setFloat64(0,n,!0),at.getUint32(0,!0)}const Ir=.6931471803691238,kr=19082149292705877e-26,oA=0x40000000000000,sA=.6666666666666735,iA=.3999999999940942,aA=.2857142874366239,cA=.22222198432149784,lA=.1818357216161805,uA=.15313837699209373,dA=.14798198605116586;function Ge(n){let e=n,t=Qt(e);const r=If(e);let o=0;if(t<1048576){if((t&2147483647|r)===0)return-1/0;if(t<0)return Number.NaN;o-=54,e*=oA,t=Qt(e)}if(t>=2146435072)return e+e;o+=(t>>20)-1023,t&=1048575;const s=t+614244&1048576;return at.setFloat64(0,e,!0),at.setInt32(4,t|s^1072693248,!0),e=at.getFloat64(0,!0),o+=s>>20,fA(e-1,o,t)}function fA(n,e,t){if((1048575&2+t)<3){if(n===0)return e===0?0:e*Ir+e*kr;const l=n*n*(.5-.3333333333333333*n);return e===0?n-l:e*Ir-(l-e*kr-n)}const r=n/(2+n),o=r*r,s=o*o,i=s*(iA+s*(cA+s*uA)),c=o*(sA+s*(aA+s*(lA+s*dA)))+i;if((t-398458|440401-t)>0){const l=.5*n*n;return e===0?n-(l-r*(l+c)):e*Ir-(l-(r*(l+c)+e*kr)-n)}return e===0?n-r*(n-c):e*Ir-(r*(n-c)-e*kr-n)}const kf=-.16666666666666632,hA=.00833333333332249,gA=-.0001984126982985795,wA=27557313707070068e-22,pA=-25050760253406863e-24,mA=158969099521155e-24,yA=.0416666666666666,bA=-.001388888888887411,vA=2480158728947673e-20,AA=-27557314351390663e-23,EA=2087572321298175e-24,_A=-11359647557788195e-27;function rs(n,e,t){if((Qt(n)&2147483647)<1044381696&&Math.trunc(n)===0)return n;const r=n*n,o=r*n,s=hA+r*(gA+r*(wA+r*(pA+r*mA)));return t===0?n+o*(kf+r*s):n-(r*(.5*e-o*s)-e-o*kf)}function os(n,e){const t=Qt(n)&2147483647;if(t<1044381696&&Math.trunc(n)===0)return 1;const r=n*n,o=r*(yA+r*(bA+r*(vA+r*(AA+r*(EA+r*_A)))));if(t<1070805811)return 1-(.5*r-(r*o-n*e));let s;t>1072234496?s=.28125:(at.setInt32(4,t-2097152,!0),at.setUint32(0,0,!0),s=at.getFloat64(0,!0));const i=.5*r-s;return 1-s-(i-(r*o-n*e))}const IA=.6366197723675814,Sf=1.5707963267341256,ic=6077100506506192e-26,Pf=6077100506303966e-26,ac=20222662487959506e-37,kA=20222662487111665e-37,SA=84784276603689e-45,Oe=new Float64Array(2);function xf(n){const e=Qt(n),t=e&2147483647;if(t<1073928572){const d=e>0?1:-1;let f=n-d*Sf;return t===1073291771?(f-=d*Pf,Oe[0]=f-d*ac,Oe[1]=f-Oe[0]-d*ac):(Oe[0]=f-d*ic,Oe[1]=f-Oe[0]-d*ic),d}const r=Math.abs(n),o=Math.floor(r*IA+.5);let s=r-o*Sf,i=o*ic;const a=t>>20;let c=s-i,l=a-(Qt(c)>>20&2047);if(l>16){let d=s;i=o*Pf,s=d-i,i=o*ac-(d-s-i),c=s-i,l=a-(Qt(c)>>20&2047),l>49&&(d=s,i=o*kA,s=d-i,i=o*SA-(d-s-i),c=s-i)}const u=s-c-i;return e<0?(Oe[0]=-c,Oe[1]=-u,-o):(Oe[0]=c,Oe[1]=u,o)}const PA=6.283185307179586;function Cf(n,e){return e>1094263291?n%PA:n}function Jt(n){const e=Qt(n)&2147483647;if(e<=1072243195)return rs(n,0,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return rs(Oe[0],Oe[1],1);case 1:return os(Oe[0],Oe[1]);case 2:return-rs(Oe[0],Oe[1],1);default:return-os(Oe[0],Oe[1])}}function yn(n){const e=Qt(n)&2147483647;if(e<=1072243195)return os(n,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return os(Oe[0],Oe[1]);case 1:return-rs(Oe[0],Oe[1],1);case 2:return-os(Oe[0],Oe[1]);default:return rs(Oe[0],Oe[1],1)}}const Nf=3.141592653589793,Tf=1.5707963267948966,ii=6123233995736766e-32,xA=.16666666666666666,CA=-.3255658186224009,NA=.20121253213486293,TA=-.04005553450067941,OA=.0007915349942898145,$A=3479331075960212e-20,RA=-2.403394911734414,DA=2.0209457602335057,LA=-.6882839716054533,MA=.07703815055590194;function cc(n){const e=n*(xA+n*(CA+n*(NA+n*(TA+n*(OA+n*$A))))),t=1+n*(RA+n*(DA+n*(LA+n*MA)));return e/t}function Of(n){const e=Qt(n),t=e&2147483647;if(t>=1072693248)return(t-1072693248|If(n))===0?e>0?0:Nf+2*ii:Number.NaN;if(t<1071644672)return t<=1012924416?Tf+ii:Tf-(n-(ii-n*cc(n*n)));if(e<0){const c=(1+n)*.5,l=Math.sqrt(c),u=cc(c)*l-ii;return Nf-2*(l+u)}const r=(1-n)*.5,o=Math.sqrt(r);at.setFloat64(0,o,!0),at.setUint32(0,0,!0);const s=at.getFloat64(0,!0),i=(r-s*s)/(o+s),a=cc(r)*o+i;return 2*(s+a)}const UA=709.782712893384,FA=-745.1332191019411,BA=1.4426950408889634,zA=9332636185032189e-317,GA=.16666666666666602,WA=-.0027777777777015593,VA=6613756321437934e-20,jA=-16533902205465252e-22,qA=41381367970572385e-24;function $f(n,e){return at.setFloat64(0,n,!0),at.setInt32(4,at.getInt32(4,!0)+(e<<20),!0),at.getFloat64(0,!0)}function HA(n,e,t){return e>=2146435072?!t||Number.isNaN(n)?n+n:0:n>UA?1/0:n<FA?0:null}const Sr=new Float64Array(3);function KA(n,e,t){if(e<1072734898){Sr[0]=t?-1:1,Sr[1]=t?n+Ir:n-Ir,Sr[2]=t?-kr:kr;return}const r=Math.trunc(BA*n+(t?-.5:.5));Sr[0]=r,Sr[1]=n-r*Ir,Sr[2]=r*kr}function Qr(n){const e=Qt(n),t=e<0,r=e&2147483647,o=r>=1082535490?HA(n,r,t):null;if(o!==null)return o;if(r<1043333120)return 1+n;let s=0,i=0,a=0,c=n;r>1071001154&&(KA(n,r,t),[a,s,i]=Sr,c=s-i);const l=c*c,u=c-l*(GA+l*(WA+l*(VA+l*(jA+l*qA))));if(a===0)return 1-(c*u/(u-2)-c);const d=1-(i-c*u/(2-u)-s);return a>=-1021?$f(d,a):$f(d,a+1e3)*zA}function YA(...n){let e=0,t=!1;for(const s of n){const i=Math.abs(s);Number.isNaN(i)?t=!0:i>e&&(e=i)}if(e===1/0)return 1/0;if(t)return Number.NaN;if(e===0)return 0;let r=0,o=0;for(const s of n){const i=Math.abs(s)/e,a=i*i-o,c=r+a;o=c-r-a,r=c}return Math.sqrt(r)*e}function XA(n,e){let t=n,r=Math.abs(e),o=1;for(;r>0;)r%2===1&&(o*=t),t*=t,r=Math.floor(r/2);return e<0?1/o:o}function QA(n,e){return n===0?e>0?0:1/0:n===1/0?e>0?1/0:0:e===.5?Math.sqrt(n):Qr(e*Ge(n))}function JA(n,e){if(e===0)return 1;if(Number.isNaN(n)||Number.isNaN(e))return Number.NaN;const t=Number.isInteger(e);if(t&&Math.abs(e)<=1024)return XA(n,e);const r=Math.abs(n);if(!Number.isFinite(e))return r===1?Number.NaN:r>1==e>0?1/0:0;if(n<0&&!t&&r!==1/0)return Number.NaN;const o=QA(r,e);return(n<0||Object.is(n,-0))&&t&&e%2!==0?-o:o}function Rf(n){if(n.ids===void 0)throw new P("E_UNKNOWN_NODE","node ids cannot be resolved: this graph has no id map (pass a GraphSnapshot)",{reason:"no id map"});return n.ids}function xe(n,e){return typeof e=="number"?e:Rf(n).requireIndex(e.id)}function ss(n,e){return"mask"in e?(Qs(e.mask,n.nodeCount,"nodes"),sf(e.mask,n.nodeCount)):"ids"in e?Rf(n).indicesOf(e.ids,"throw"):e}function Df(n,e){if("mask"in e)return Qs(e.mask,n.nodeCount,"nodes"),e.mask;const t=ss(n,e),r=At(n.nodeCount);for(let o=0;o<t.length;o++){const s=t[o];if(!Number.isInteger(s)||s<0||s>=n.nodeCount)throw new P("E_INDEX_RANGE",`node index ${String(s)} is out of range for ${n.nodeCount} nodes`,{index:s,nodeCount:n.nodeCount});pn(r,s,!0)}return r}function Q(n,e){return Object.assign(n,{code:e})}function lc(n,e,t,r){const o=t===void 0?`${n}: ${String(e)} nodes need ${String(r)} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`${n}: ${String(e)} nodes exceeds maxNodes ${String(t)}; the result would allocate ${String(r)} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(Q(new RangeError(o),"E_TOO_LARGE"),{params:{nodeCount:e,maxNodes:t??null,bytes:r}})}function Lf(n,e,t,r,o){if(t!==void 0&&(e>t||Number.isNaN(t)))throw lc(n,e,t,r);try{return o()}catch(s){throw s instanceof RangeError?lc(n,e,void 0,r):s}}class Mf extends Error{constructor(e,t,r){super(`${e} did not converge in ${String(t)} iterations (tolerance ${String(r)}); raise maxIterations or tolerance`),this.algorithm=e,this.iterations=t,this.tolerance=r,this.name="ConvergenceError",this.code="E_NOT_CONVERGED"}}class uc extends Error{constructor(e,t,r){super(`cannot walk the shortest path from node ${String(e)} to node ${String(t)}: the predecessor array has a ${r}`),this.source=e,this.target=t,this.reason=r,this.name="PathWalkError",this.code="E_BAD_PATH"}}class ZA extends Error{constructor(e){super(`${e}: the accelerator's shortest-path counts overflowed, so its scores are wrong; run the CPU ${e} instead`),this.algorithm=e,this.name="PathCountOverflowError",this.code="E_PATH_COUNT_OVERFLOW"}}function Uf(n,e){let t=0,r=n.length-1;for(;t<r;){const o=t+r>>1;n[o+1]<=e?t=o+1:r=o}return t}class Yn{constructor(e,t=!1){this.size=0,this.tieBreakByIndex=t,this.heap=new Uint32Array(e),this.slot=new Uint32Array(e).fill(x),this.key=new Float64Array(e)}isEmpty(){return this.size===0}has(e){return this.slot[e]!==x}keyOf(e){return this.key[e]}peekKey(){return this.size===0?1/0:this.key[this.heap[0]]}push(e,t){if(!(e>=0&&e<this.slot.length))throw new RangeError(`Node index ${String(e)} is outside the heap's ${String(this.slot.length)} nodes`);this.key[e]=t,this.heap[this.size]=e,this.slot[e]=this.size,this.size++,this.siftUp(this.size-1)}pushOrDecrease(e,t){const r=this.slot[e];if(r===x){this.push(e,t);return}t<this.key[e]&&(this.key[e]=t,this.siftUp(r))}pop(){const e=this.heap[0];if(this.slot[e]=x,this.size--,this.size>0){const t=this.heap[this.size];this.heap[0]=t,this.slot[t]=0,this.siftDown(0)}return e}before(e,t){const r=this.key[e],o=this.key[t];return r<o||this.tieBreakByIndex&&r===o&&e<t}siftUp(e){let t=e;const r=this.heap[t];for(;t>0;){const o=t-1>>1,s=this.heap[o];if(!this.before(r,s))break;this.heap[t]=s,this.slot[s]=t,t=o}this.heap[t]=r,this.slot[r]=t}siftDown(e){let t=e;const r=this.heap[t];for(;;){const o=2*t+1;if(o>=this.size)break;const s=o+1,i=s<this.size&&this.before(this.heap[s],this.heap[o])?s:o,a=this.heap[i];if(!this.before(a,r))break;this.heap[t]=a,this.slot[a]=t,t=i}this.heap[t]=r,this.slot[r]=t}}function Ff(n,e,t,r){const o=[];let s=r;for(;s!==t;){if(o.length>=n.nodeCount-1)throw new uc(t,r,"cycle");const i=e[s];if(!(i<n.arcCount))throw new uc(t,r,"gap");o.push(i),s=Uf(n.rowPtr,i)}return o}function Jr(n,e,t,r){const o=xe(n,r);if(o===t)return Uint32Array.of(t);if(e[o]===x)return new Uint32Array(0);const s=[o,...Ff(n,e,t,o).map(a=>Uf(n.rowPtr,a))],i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Zr(n,e,t,r){const o=xe(n,r);if(o===t||e[o]===x)return new Uint32Array(0);const s=Ff(n,e,t,o).map(a=>n.arcToEdge[a]),i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Bf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=new Float64Array(o).fill(1/0),l=new Uint32Array(o).fill(x),u=new Yn(o),d=t.cutoff??1/0;for(c[r]=0,u.push(r,0);!u.isEmpty();){const f=u.pop(),h=c[f],g=s[f+1];for(let w=s[f];w<g;w++){const p=a===null?1:a[w],m=i[w],y=h+p;y<c[m]&&y<=d&&(c[m]=y,l[m]=w,u.pushOrDecrease(m,y))}}return{dist:c,predArc:l,pathTo:f=>Jr(n,l,r,f),pathEdges:f=>Zr(n,l,r,f)}}const zf=5792;function e3(n,e){if(e.weighted===!1)return{w:null,negative:!1};if(e.weights!==void 0&&e.weights.length!==n.arcCount)throw Q(new RangeError(`allPairsShortestPath: the weights override has ${String(e.weights.length)} entries; the snapshot has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");const t=e.weights??n.weights;if(t===null)return{w:null,negative:!1};let r=!0,o=!1;for(let s=0;s<n.arcCount;s++){const i=t[s];if(!Number.isFinite(i)){const a=e.weights===void 0&&!Number.isNaN(i)?"; a finite weight above the f32 range (3.4e38) becomes Infinity in the snapshot's f32 arc weights -- pass the exact f64 weights through the weights override":"";throw Q(new RangeError(`allPairsShortestPath: arc ${String(s)} has weight ${String(i)}; weights must be finite${a}`),"E_BAD_WEIGHT")}r&&(r=i===1),o||(o=i<0)}return{w:r?null:t,negative:o}}function t3(n,e,t,r,o){const{nodeCount:s,rowPtr:i,colIdx:a}=n;r.fill(1/0);for(let c=0;c<s;c++){const l=c*s;for(let u=i[c];u<i[c+1];u++){const d=a[u],f=e===null?1:e[u];d!==c&&f<r[l+d]&&(r[l+d]=f,o!==null&&(o[l+d]=u))}r[l+c]=0}for(let c=0;c<s;c++){const l=c*s,u=r.subarray(l,l+s);for(let d=0;d<s;d++){const f=d*s,h=r[f+c];if(h===1/0)continue;const g=r.subarray(f,f+s);if(o===null)for(let w=0;w<g.length;w++){const p=h+u[w];p<g[w]&&(g[w]=p)}else{const w=o.subarray(l,l+s),p=o.subarray(f,f+s);for(let m=0;m<g.length;m++){const y=h+u[m];y<g[m]&&(g[m]=y,p[m]=w[m])}}}if(t){for(let d=0;d<s;d++)if(r[d*s+d]<0)return!0}}return!1}function n3(n,e){for(let t=0;t<n.nodeCount;t++)for(let r=n.rowPtr[t];r<n.rowPtr[t+1];r++)if(e[r]<0&&(!n.directed||n.colIdx[r]===t))return!0;return!1}function r3(n,e,t){const{nodeCount:r,rowPtr:o,colIdx:s}=n,i=new Uint32Array(r);e.fill(1/0);for(let a=0;a<r;a++){const c=e.subarray(a*r,a*r+r),l=t?.subarray(a*r,a*r+r);c[a]=0,i[0]=a;let u=1;for(let d=0;d<u;d++){const f=i[d],h=c[f]+1;for(let g=o[f];g<o[f+1];g++){const w=s[g];c[w]===1/0&&(c[w]=h,l!==void 0&&(l[w]=g),i[u++]=w)}}}}function o3(n,e,t,r){const{nodeCount:o,rowPtr:s,colIdx:i}=n,a=new Yn(o);t.fill(1/0);for(let c=0;c<o;c++){const l=t.subarray(c*o,c*o+o),u=r?.subarray(c*o,c*o+o);for(l[c]=0,a.push(c,0);!a.isEmpty();){const d=a.pop(),f=l[d];for(let h=s[d];h<s[d+1];h++){const g=i[h],w=f+e[h];w<l[g]&&(l[g]=w,u!==void 0&&(u[g]=h),a.pushOrDecrease(g,w))}}}}function s3(n,e,t,r){if(r==="floyd-warshall")return"floyd-warshall";if(e===null)return"bfs";if(t){if(r==="per-source")throw Q(new Error('allPairsShortestPath: method "per-source" runs Dijkstra, which is incorrect with a negative weight; use "auto" or "floyd-warshall"'),"E_BAD_OPTION");return"floyd-warshall"}const o=n.nodeCount;return r==="per-source"||3*n.arcCount<o*o?"dijkstra":"floyd-warshall"}function Gf(n,e={}){const t=n.nodeCount,r=e.maxNodes??zf;if(!(t<=r))throw lc("allPairsShortestPath",t,r,(e.paths===!0?12:8)*t*t);const{w:o,negative:s}=e3(n,e),i=s3(n,o,s,e.method),a=new Float64Array(t*t),c=e.paths===!0?new Uint32Array(t*t).fill(x):null;let l=!1;i==="bfs"?r3(n,a,c):i==="dijkstra"&&o!==null?o3(n,o,a,c):l=s&&o!==null&&n3(n,o)||t3(n,o,s,a,c),l&&a.fill(Number.NaN);const u=(d,f)=>{const h=xe(n,d),g=xe(n,f);if(c===null)throw Q(new Error("allPairsShortestPath: pass paths: true to walk shortest paths"),"E_BAD_OPTION");if(l)throw new uc(h,g,"cycle");return c.subarray(h*t,h*t+t)};return{dist:a,n:t,hasNegativeCycle:l,method:i,predArc:c,pathTo:(d,f)=>Jr(n,u(d,f),xe(n,d),f),pathEdges:(d,f)=>Zr(n,u(d,f),xe(n,d),f)}}function Wf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=t.cutoff??1/0,l=new Float64Array(o).fill(1/0),u=new Uint32Array(o).fill(x);l[r]=0;const d=()=>{let g=!1;for(let w=0;w<o;w++){const p=l[w];if(p===1/0)continue;const m=s[w+1];for(let y=s[w];y<m;y++){const b=i[y],v=p+(a===null?1:a[y]);v<l[b]&&v<=c&&(l[b]=v,u[b]=y,g=!0)}}return g};let f=!1;for(let g=0;g<o-1&&!f;g++)f=!d();const h=!f&&d();return{dist:l,predArc:u,hasNegativeCycle:h,pathTo:g=>Jr(n,u,r,g),pathEdges:g=>Zr(n,u,r,g)}}const i3=2654435769;function a3(n,e){const t=Array.from({length:n},(o,s)=>s);let r=i3;for(let o=0;o<e;o++){r=r+1831565813>>>0;let s=Math.imul(r^r>>>15,r|1);s=s+Math.imul(s^s>>>7,s|61)^s;const i=((s^s>>>14)>>>0)/2**32,a=o+Math.floor(i*(n-o));[t[o],t[a]]=[t[a],t[o]]}return t.slice(0,e)}function is(n,e,t,r="betweenness"){const o=n.nodeCount,s=e===void 0?void 0:Array.from(ss(n,e));if(t!==void 0&&(!Number.isInteger(t)||t<0||t>o))throw Q(new RangeError(`${r}: k must be an integer in [0, ${o}], got ${t}`),"E_BAD_OPTION");if(s!==void 0){for(const i of s)if(!Number.isInteger(i)||i<0||i>=o)throw Q(new RangeError(`${r}: sources must be node indices in [0, ${o}), got ${i}`),"E_BAD_NODE");if(t!==void 0&&t!==s.length)throw Q(new RangeError(`${r}: k (${t}) must be absent or equal sources.length (${s.length})`),"E_BAD_OPTION");return s}return t===void 0?Array.from({length:o},(i,a)=>a):a3(o,t)}function Vf(n,e,t,r,o,s){const{nodeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Int32Array(i).fill(-1),d=new Float64Array(i),f=new Float64Array(i),h=new Uint32Array(i);for(const g of e){let w=0,p=0;for(u[g]=0,d[g]=1,h[p++]=g;w<p;){const m=h[w++],y=u[m]+1;let b=-1;for(let v=a[m],A=a[m+1];v<A;v++){const E=c[v];E===b||o!==null&&!_e(o,l[v])||(b=E,u[E]<0&&(u[E]=y,h[p++]=E),u[E]===y&&(d[E]+=d[m]))}}for(let m=p-1;m>=0;m--){const y=h[m],b=u[y]+1;let v=-1;for(let A=a[y],E=a[y+1];A<E;A++){const I=c[A];if(!(I===v||o!==null&&!_e(o,l[A]))&&(v=I,u[I]===b)){const k=d[y]/d[I]*(1+f[I]);f[y]+=k,r!==null&&(r[l[A]]+=k)}}t!==null&&y!==g&&(t[y]+=s?f[y]+1:f[y])}t!==null&&s&&(t[g]+=p-1);for(let m=0;m<p;m++){const y=h[m];u[y]=-1,d[y]=0,f[y]=0}}}function jf(n,e,t,r){const o=n.directed?1:2,s=t===!0&&r>0?r:o;for(let i=0;i<e.length;i++)e[i]/=s;return s}function qf(n,e={}){const t=n.nodeCount,r=is(n,e.sources,e.k),o=new Float64Array(t),s=e.endpoints===!0;Vf(n,r,o,null,null,s);const i=jf(n,o,e.normalized,s?t*(t-1):(t-1)*(t-2));return{scores:o,iterations:r.length,converged:!0,divisor:i}}function dc(n,e={}){const t=n.nodeCount,r=e.alive??null;if(r!==null&&r.length<Math.ceil(n.edgeCount/32))throw Q(new RangeError(`edgeBetweennessCentrality: alive covers fewer than ${n.edgeCount} edges`),"E_BAD_OPTION");const o=new Float64Array(n.edgeCount);Vf(n,is(n,e.sources,e.k),null,o,r,!1);const s=jf(n,o,e.normalized,(t-1)*(t-2));return{scores:o,divisor:s}}function fc(n,e,t){return{pathTo:r=>Jr(n,t,e,r),pathEdges:r=>Zr(n,t,e,r)}}function ai(n,e,t="start"){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`${t} node index ${String(r)} is out of range for ${String(n.nodeCount)} nodes`),"E_BAD_NODE");return r}function Hf(n,e){return e===void 0?x:ai(n,e,"target")}function ci(n,e){if(e===void 0)return null;const{rowPtr:t,nodeCount:r}=n;if(e.length!==n.arcCount)throw Q(new RangeError(`arcOrder has ${String(e.length)} entries, expected ${String(n.arcCount)}`),"E_BAD_OPTION");const o=new Uint8Array(e.length);for(let s=0;s<r;s++){const i=t[s],a=t[s+1];for(let c=i;c<a;c++){if(e[c]<i||e[c]>=a)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} is not an arc of node ${String(s)}`),"E_BAD_OPTION");if(o[e[c]]===1)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} repeats an arc of node ${String(s)}`),"E_BAD_OPTION");o[e[c]]=1}}return e}function Kf(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=ci(n,t.arcOrder),c=new Uint32Array(o).fill(x),l=new Uint32Array(o).fill(x),u=new Uint32Array(o).fill(x),d=new Uint32Array(o),f=t.maxDepth??x,h=Hf(n,t.target);let g=0,w=0;for(d[w++]=r,u[r]=0;g<w;){const p=d[g++];if(p===h)break;const m=u[p];if(m>=f)continue;const y=s[p+1];for(let b=s[p];b<y;b++){const v=a===null?b:a[b],A=i[v];u[A]===x&&(u[A]=m+1,c[A]=p,l[A]=v,d[w++]=A)}}return{order:d.subarray(0,w),parent:c,depth:u,visitedCount:w,predArc:l,...fc(n,r,l)}}function c3(n,e,t,r){const{rowPtr:o,colIdx:s,arcToEdge:i}=n;let a=o[t],c=o[t+1];for(;a<c;){const u=a+c>>>1;s[u]<r?a=u+1:c=u}const l=o[t+1];for(;a<l&&s[a]===r&&i[a]!==i[e];)a++;return a}function l3(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.alpha??1,c=t.beta??18;let l=null;const u=new Uint32Array(o).fill(x),d=new Uint32Array(o).fill(x),f=new Uint32Array(o).fill(x),h=new Uint32Array(o);h[0]=r,f[r]=0;let g=0,w=1;const p=n.inDegree();let m=n.arcCount-p[r],y=!1;for(let b=0;g<w;b++){const v=w-g;if(y)y=v>=o/c;else{let E=0;for(let I=g;I<w;I++)E+=s[h[I]+1]-s[h[I]];y=E>m/a}const A=w;if(y){l??(l=n.reverse());for(let E=0;E<o;E++){if(f[E]!==x)continue;const I=l.rowPtr[E+1];for(let k=l.rowPtr[E];k<I;k++){const N=l.colIdx[k];if(f[N]===b){u[E]=N,d[E]=n.directed?l.fwdArc[k]:c3(n,k,N,E),f[E]=b+1,h[w++]=E;break}}}}else{for(let E=g;E<A;E++){const I=h[E],k=s[I+1];for(let N=s[I];N<k;N++){const C=i[N];f[C]===x&&(u[C]=I,d[C]=N,f[C]=b+1,h[w++]=C)}}h.subarray(A,w).sort()}for(let E=A;E<w;E++)m-=p[h[E]];g=A}return{order:h.subarray(0,w),parent:u,depth:f,visitedCount:w,predArc:d,...fc(n,r,d)}}const hc=2;function Yf(n,e={}){const{nodeCount:t}=n,r=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n],o=new Uint8Array(t).fill(hc),s=new Uint32Array(t);for(let a=0;a<t;a++){if(o[a]!==hc)continue;o[a]=0;let c=0,l=0;for(s[l++]=a;c<l;){const u=s[c++];for(const{rowPtr:d,colIdx:f}of r){const h=d[u+1];for(let g=d[u];g<h;g++){const w=f[g];if(o[w]===hc)o[w]=o[u]^1,s[l++]=w;else if(o[w]===o[u])return{bipartite:!1,sides:null}}}}}const i=At(t);for(let a=0;a<t;a++)o[a]===1&&pn(i,a,!0);return{bipartite:!0,sides:i}}function gc(n,e,t){const{rowPtr:r,colIdx:o,weights:s}=e,i=new Float64Array(n).fill(1/0),a=new Uint32Array(n),c=s===null?null:new Yn(n),l=new Uint8Array(n);return{dist:i,reached:a,run(u){let d=0;if(i[u]=0,a[d++]=u,c===null||s===null){for(let f=0;f<d;f++){const h=a[f];if(!(i[h]>=t))for(let g=r[h],w=r[h+1];g<w;g++){const p=o[g];i[p]===1/0&&(i[p]=i[h]+1,a[d++]=p)}}return d}for(c.push(u,0);!c.isEmpty();){const f=c.pop();if(l[f]=1,!(i[f]>=t))for(let h=r[f],g=r[f+1];h<g;h++){const w=o[h];if(l[w]===1)continue;const p=i[f]+s[h];p<i[w]&&(i[w]===1/0&&(a[d++]=w),i[w]=p,c.pushOrDecrease(w,p))}}return d},clear(u){for(let d=0;d<u;d++)i[a[d]]=1/0,l[a[d]]=0}}}function Xf(n,e,t,r,o){return n.harmonic===!0?n.normalized===!0&&e>1?o/(e-1):o:r<=0?0:n.normalized===!0&&e>1?t/r/(e-1):1/r}function Qf(n,e,t,r){const o=n.run(r);let s=0,i=0;for(let a=1;a<o;a++){const c=n.dist[n.reached[a]];s+=c,i+=c>0?1/c:0}return n.clear(o),Xf(e,t,o-1,s,i)}function wc(n,e,t){const r=e.weighted===!0;if(!t||!n.directed)return{rowPtr:n.rowPtr,colIdx:n.colIdx,weights:r?e.weights??n.weights:null};const o=n.reverse(),s=e.weights;let i=null;return r&&(i=s===void 0?o.weights:Float64Array.from(o.fwdArc,a=>s[a])),{rowPtr:o.rowPtr,colIdx:o.colIdx,weights:i}}function Jf(n,e={}){const t=n.nodeCount,r=e.cutoff??1/0,o=new Float64Array(t);if(e.sources===void 0&&e.k===void 0){const u=gc(t,wc(n,e,!1),r);for(let d=0;d<t;d++)o[d]=Qf(u,e,t,d);return{scores:o,iterations:t,converged:!0,sourcesUsed:t}}const s=is(n,e.sources,e.k,"closenessCentrality"),i=gc(t,wc(n,e,!0),r),a=new Float64Array(t),c=new Float64Array(t),l=new Uint32Array(t);for(const u of s){const d=i.run(u);for(let f=1;f<d;f++){const h=i.reached[f],g=i.dist[h];a[h]+=g,c[h]+=g>0?1/g:0,l[h]+=1}i.clear(d)}for(let u=0;u<t;u++)o[u]=Xf(e,t,l[u],a[u],c[u]);return{scores:o,iterations:s.length,converged:!0,sourcesUsed:s.length}}function u3(n,e,t={}){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`nodeClosenessCentrality: node must be an index in [0, ${n.nodeCount}), got ${r}`),"E_BAD_NODE");const o=gc(n.nodeCount,wc(n,t,!1),t.cutoff??1/0);return Qf(o,t,n.nodeCount,r)}function Zf(n,e,t,r,o){let s=n.rowPtr[t];const i=n.rowPtr[t+1];let a=e.rowPtr[r];const c=e.rowPtr[r+1];let l=0;for(;s<i&&a<c;){const u=n.colIdx[s],d=e.colIdx[a];if(u===d)for(l+=o===void 0?1:o(u),s++,a++;a<c&&e.colIdx[a]===d;)a++;else u<d?s++:a++}return l}function d3(n,e,t,r={}){return Zf(n,r.directed===!0?n.reverse():n,e,t)}class eo{constructor(e){this.parent=new Uint32Array(e),this.rank=new Uint32Array(e);for(let t=0;t<e;t++)this.parent[t]=t}find(e){let t=e;for(;this.parent[t]!==t;)this.parent[t]=this.parent[this.parent[t]],t=this.parent[t];return t}union(e,t){const r=this.find(e),o=this.find(t);return r===o?!1:(this.rank[r]<this.rank[o]?this.parent[r]=o:this.rank[r]>this.rank[o]?this.parent[o]=r:(this.parent[o]=r,this.rank[r]++),!0)}toLabels(){const e=new Uint32Array(this.parent.length);for(let t=0;t<e.length;t++)e[t]=this.find(t);return Je(e)}}function We(n,e){let t=null;return{labels:n,count:e,groups(){if(t===null){const r=new Uint32Array(e);for(let i=0;i<n.length;i++)r[n[i]]++;const o=[];for(let i=0;i<e;i++)o.push(new Uint32Array(r[i]));const s=new Uint32Array(e);for(let i=0;i<n.length;i++){const a=n[i];o[a][s[a]++]=i}t=o}return t}}}function eh(n){const e=new eo(n.nodeCount),t=n.edgeList();for(let s=0;s<n.edgeCount;s++)e.union(t.src[s],t.dst[s]);const{labels:r,count:o}=e.toLabels();return We(r,o)}function th(n){if(n.directed)throw Q(new Error("Connected components requires an undirected graph. Use weaklyConnectedComponents, or pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");return eh(n)}function nh(n){return eh(n)}function rh(n,e){const{rowPtr:t,colIdx:r}=n;for(let o=0;o<n.nodeCount;o++){let s=-1;for(let i=t[o],a=t[o+1];i<a;i++)r[i]!==s&&(s=r[i],e[o]++)}}function f3(n,e={}){const t=new Float64Array(n.nodeCount),r=n.directed?e.mode??"total":"out";r!=="in"&&rh(n,t),r!=="out"&&rh(n.reverse(),t);const o=n.nodeCount-1;if(e.normalized===!0&&o>0)for(let s=0;s<t.length;s++)t[s]/=o;return t}function oh(n){const{src:e,dst:t}=n.edgeList(),r=new Uint32Array(n.nodeCount),o=new Uint32Array(n.nodeCount);for(let s=0;s<e.length;s++)o[e[s]]++,r[t[s]]++;return{inDegree:r,outDegree:o}}class sh{constructor(e){this.min=new Yn(e,!0)}isEmpty(){return this.min.isEmpty()}has(e){return this.min.has(e)}keyOf(e){return-this.min.keyOf(e)}push(e,t){this.min.push(e,-t)}pushOrIncrease(e,t){this.min.pushOrDecrease(e,-t)}pop(){return this.min.pop()}}function ih(n){const e=new Uint32Array(n.arcCount),t=n.rowPtr.slice(0,n.nodeCount),{src:r}=n.edgeList();for(let o=0;o<n.edgeCount;o++)e[t[r[o]]++]=n.edgeToArc[o];return e}function ah(n,e,t){const r=new Float64Array(n.nodeCount);for(let o=0;o<n.nodeCount;o++){let s=0;for(let i=n.rowPtr[o];i<n.rowPtr[o+1];i++)s+=t===null?1:t[e[i]];r[o]=s}return r}function pc(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t];if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function h3(n,e,t){if(n===void 0)return null;if(n.length!==e)throw Q(new RangeError(`${t} has ${String(n.length)} entries; the graph has ${String(e)} nodes`),"E_BAD_OPTION");const r=Float64Array.from(n);return pc(r),r}function ch(n,e){if(e===void 0)return n.weights;if(e.length!==n.arcCount)throw Q(new RangeError(`weights has ${String(e.length)} entries; the graph has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");return e}function g3(n){if(n<0||n>1)throw Q(new Error("Damping factor must be between 0 and 1"),"E_BAD_OPTION")}class w3{constructor(e,t={}){if(!e.directed)throw Q(new Error("DeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.active=new Uint8Array(e.nodeCount).fill(1)}compute(e={}){return this.run(e,!1)}update(e,t={}){const{s:r}=this,o=r.reverse(),s=new Uint8Array(r.nodeCount);for(let i=0;i<e.length;i++){const a=e[i];if(!(!Number.isInteger(a)||a<0||a>=r.nodeCount)){s[a]=1;for(let c=o.rowPtr[a];c<o.rowPtr[a+1];c++)s[o.colIdx[c]]=1;for(let c=r.rowPtr[a];c<r.rowPtr[a+1];c++)s[r.colIdx[c]]=1}}return this.active=s,this.run(t,e.length>0)}run(e,t){const r=e.dampingFactor??.85,o=e.tolerance??1e-6,s=e.maxIterations??100,i=e.deltaThreshold??o/10;g3(r);const{s:a,order:c,scores:l}=this,u=a.nodeCount;if(u===0)return new Float64Array(0);const d=h3(e.personalization,u,"personalization"),f=e.weighted===!0?this.weights:null,h=(1-r)/u;let g=this.active.reduce((w,p)=>w+p,0);for(let w=0;(g>0||w===0&&t)&&w<s;w++){const p=new Float64Array(u);let m=0;for(let b=0;b<u;b++)a.rowPtr[b]===a.rowPtr[b+1]&&(m+=l[b]+this.deltas[b]);if(m>0){const b=r*m/u;for(let v=0;v<u;v++)p[v]+=d===null?b:b*d[v]}for(let b=0;b<u;b++){const v=this.deltas[b];if(this.active[b]===0||Math.abs(v)<i)continue;l[b]+=v;const A=this.outW[b];if(A>0)for(let E=a.rowPtr[b];E<a.rowPtr[b+1];E++){const I=c[E];p[a.colIdx[I]]+=r*v*((f===null?1:f[I])/A)}}let y=0;g=0;for(let b=0;b<u;b++){p[b]+=d===null?h:(1-r)*d[b];const v=Math.abs(p[b]);y=Math.max(y,v),this.active[b]=v>=i?1:0,g+=this.active[b]}if(this.deltas=p,y<o)break}return pc(l),l.slice()}}class p3{constructor(e,t={}){if(!e.directed)throw Q(new Error("PriorityDeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.heap=new sh(e.nodeCount);for(let r=0;r<e.nodeCount;r++)this.heap.push(r,1/e.nodeCount)}computeWithPriority(e={}){const t=e.dampingFactor??.85,r=e.tolerance??1e-6,o=e.maxIterations??100,s=e.deltaThreshold??r/10,{s:i,order:a,scores:c,deltas:l,heap:u}=this,d=i.nodeCount,f=e.weighted===!0?this.weights:null;let h=0,g=0;for(;!u.isEmpty()&&h<o;){const w=u.pop(),p=l[w];if(Math.abs(p)<s)continue;c[w]+=p,l[w]=0;const m=f===null?i.rowPtr[w+1]-i.rowPtr[w]:this.outW[w];if(m>0)for(let y=i.rowPtr[w];y<i.rowPtr[w+1];y++){const b=a[y],v=i.colIdx[b],A=l[v]+t*p*((f===null?1:f[b])/m);l[v]=A,Math.abs(A)>=s&&u.pushOrIncrease(v,Math.abs(A))}if(g++,g%1e3===0){let y=0;for(let b=0;b<d;b++)y=Math.max(y,Math.abs(l[b]));if(y<r)break}h++}for(let w=0;w<d;w++)Math.abs(l[w])>=s&&(c[w]+=l[w]);return pc(c),c.slice()}}const mc=0,yc=1,m3=2;function bc(n){return{state:new Uint8Array(n),parent:new Uint32Array(n).fill(x),predArc:new Uint32Array(n).fill(x),depth:new Uint32Array(n).fill(x),cursor:new Uint32Array(n),stack:new Uint32Array(n),pre:new Uint32Array(n),post:new Uint32Array(n),preCount:0,postCount:0,backArc:!1}}function y3(n,e,t,r){const{rowPtr:o,colIdx:s}=n,{state:i,parent:a,predArc:c,depth:l,cursor:u,pre:d}=t,f=u[e]++,h=r===null?f:r[f],g=s[h];return i[g]===mc?(i[g]=yc,a[g]=e,c[g]=h,l[g]=l[e]+1,u[g]=o[g],d[t.preCount++]=g,g):(i[g]===yc&&(t.backArc=!0),x)}function vc(n,e,t,r,o){const{rowPtr:s}=n,{state:i,depth:a,cursor:c,stack:l,pre:u,post:d}=t;let f=0;if(i[e]=yc,a[e]=0,c[e]=s[e],u[t.preCount++]=e,l[f++]=e,e!==r)for(;f>0;){const h=l[f-1];if(c[h]<s[h+1]){const g=y3(n,h,t,o);if(g!==x&&(l[f++]=g,g===r))return}else i[h]=m3,d[t.postCount++]=h,f--}}function lh(n,e,t={}){const r=ai(n,e),o=ci(n,t.arcOrder),s=Hf(n,t.target),i=bc(n.nodeCount),a=t.order==="post";return vc(n,r,i,a?x:s,o),{order:a?i.post.subarray(0,i.postCount):i.pre.subarray(0,i.preCount),parent:i.parent,depth:i.depth,visitedCount:i.preCount,predArc:i.predArc,...fc(n,r,i.predArc)}}function b3(n){return n.directed?v3(n):A3(n)}function v3(n){const{nodeCount:e}=n,t=bc(e);for(let r=0;r<e&&!t.backArc;r++)t.state[r]===mc&&vc(n,r,t,x,null);return t.backArc}function A3(n){const{nodeCount:e,rowPtr:t,colIdx:r}=n,o=new eo(e);for(let s=0;s<e;s++){const i=t[s+1];for(let a=t[s];a<i;a++){const c=r[a];if(c===s||c>s&&(a===t[s]||r[a-1]!==c)&&!o.union(s,c))return!0}}return!1}function E3(n,e={}){if(!n.directed)throw Q(new Error("Topological sort requires a directed graph"),"E_NEEDS_DIRECTED");const t=ci(n,e.arcOrder),r=bc(n.nodeCount);for(let o=0;o<n.nodeCount&&!r.backArc;o++)r.state[o]===mc&&vc(n,o,r,x,t);return r.backArc?null:r.post.reverse()}function uh(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=e.startVector;if(s!==void 0&&s.length!==t)throw Q(new Error(`eigenvectorCentrality: startVector has ${String(s.length)} entries for ${String(t)} nodes`),"E_BAD_OPTION");let i=new Float64Array(t);if(t===0)return{scores:i,iterations:0,converged:!0};const a=_3(n,e.mode??"in");if(I3(a,t))return{scores:i,iterations:0,converged:!0};for(let d=0;d<t;d++)a.rowPtr[d+1]>a.rowPtr[d]&&(i[d]=s===void 0?1:s[d]);fh(i);let c=new Float64Array(t),l=0,u=!1;for(;l<r&&!u;l++){for(let f=0;f<t;f++){let h=i[f];const g=a.rowPtr[f+1];for(let w=a.rowPtr[f];w<g;w++)h+=i[a.colIdx[w]];c[f]=h}fh(c);let d=0;for(let f=0;f<t;f++)d+=Math.abs(c[f]-i[f]);[i,c]=[c,i],u=d<t*o}if(!u)throw new Mf("eigenvectorCentrality",r,o);return e.normalized!==!1&&dh(i),{scores:i,iterations:l,converged:u}}function dh(n){let e=1/0,t=0;for(const s of n)e=Math.min(e,s),t=Math.max(t,s);const r=t-e,o=t>0?1:0;for(let s=0;s<n.length;s++)n[s]=r>0?(n[s]-e)/r:o}function _3(n,e){const t=n.nodeCount,r=!n.directed||e==="out"?n:n.reverse(),o=n.directed&&e==="total",s=o?n.rowPtr:new Uint32Array(t+1),i=o?n.colIdx:new Uint32Array(0),a=new Uint32Array(t+1),c=new Uint32Array(r.colIdx.length+i.length);let l=0;for(let u=0;u<t;u++){let d=r.rowPtr[u];const f=r.rowPtr[u+1];let h=s[u];const g=s[u+1],w=l;for(;d<f||h<g;){const p=h>=g||d<f&&r.colIdx[d]<=i[h]?r.colIdx[d++]:i[h++];(l===w||c[l-1]!==p)&&(c[l++]=p)}a[u+1]=l}return{rowPtr:a,colIdx:c.subarray(0,l)}}function I3(n,e){const t=new Uint32Array(e);for(const s of n.colIdx)t[s]++;const r=new Uint32Array(e);let o=0;for(let s=0;s<e;s++)t[s]===0&&(r[o++]=s);for(let s=0;s<o;s++){const i=r[s];for(let a=n.rowPtr[i];a<n.rowPtr[i+1];a++)--t[n.colIdx[a]]===0&&(r[o++]=n.colIdx[a])}return o===e}function fh(n){let e=0;for(const t of n)e+=t*t;if(e=Math.sqrt(e),e>0)for(let t=0;t<n.length;t++)n[t]/=e}function to(n,e){const t=new Uint32Array(e),r=e>0&&_e(n,0);let o=!1;for(let s=0;s<e;s++)_e(n,s)!==r&&(t[s]=1,o=!0);return e===0?We(t,0):We(t,o?2:1)}function Ac(n,e){const t=n.edgeList(),r=new Float64Array(n.edgeCount);for(let o=0;o<n.edgeCount;o++)r[o]=e!==void 0?e[t.arc[o]]:t.weights?.[o]??1;return r}function Ec(n,e,t,r,o){const{src:s,dst:i}=n.edgeList(),a=[];for(let c=0;c<n.edgeCount;c++){const l=_e(e,s[c]);(t?l&&!_e(e,i[c]):l!==_e(e,i[c]))&&(!o||r[c]>0)&&a.push(c)}return Uint32Array.from(a)}function k3(n,e){const t=n.nodeCount,r=n.edgeCount,{src:o,dst:s}=n.edgeList(),i=new Uint32Array(2*r),a=new Uint32Array(2*r);i.set(o),i.set(s,r),a.set(s),a.set(o,r);const c=sc({directed:!0,nodeCount:t,src:i,dst:a}),{rowPtr:l,colIdx:u,arcToEdge:d,edgeToArc:f}=c,h=c.arcCount,g=new Float64Array(h),w=new Uint32Array(h),p=new Uint8Array(h);for(let E=0;E<t;E++)for(let I=l[E];I<l[E+1];I++){const k=I>l[E]&&u[I]===u[I-1]?w[I-1]:I;w[I]=k;const N=d[I];(N<r||!n.directed)&&(p[k]=1,g[k]+=Math.max(e[N<r?N:N-r],0))}const m=new Uint32Array(h);for(let E=0;E<h;E++)if(w[E]===E){const I=d[E];m[E]=w[f[I<r?I+r:I-r]]}const y=new Uint32Array(h),b=new Uint32Array(t),v=new Uint8Array(h),A=(E,I)=>{v[I]===0&&(v[I]=1,y[l[E]+b[E]++]=I)};for(let E=0;E<r;E++)A(o[E],w[f[E]]),n.directed||A(s[E],w[f[E+r]]);return{rowPtr:l,colIdx:u,arcToEdge:d,capacity:g,groupOf:w,twin:m,order:y,placed:b,inOrder:v,real:p}}function _c(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=n.nodeCount;if(!(Number.isInteger(o)&&o>=0&&o<i&&Number.isInteger(s)&&s>=0&&s<i))throw Q(new RangeError(`source ${String(o)} and sink ${String(s)} must be node indices below ${i}`),"E_BAD_NODE");if(o===s)throw Q(new RangeError(`source and sink are the same node (${o})`),"E_BAD_OPTION");const a=Ac(n,r.weights),c=k3(n,a),l=new Float64Array(c.colIdx.length),u=new Uint32Array(i),d=r.algorithm==="ford-fulkerson"?C3:x3;let f=0;for(;d(c,o,s,u);)f+=S3(c,o,s,u,l);const h=N3(c,o);return{...to(h,n.nodeCount),maxFlow:f,flow:P3(n,c,a,l),sourceSide:h,cutEdges:Ec(n,h,n.directed,a,!0)}}function S3(n,e,t,r,o){const{colIdx:s,twin:i}=n;let a=1/0;for(let c=t;c!==e;c=s[i[r[c]]])a=Math.min(a,n.capacity[r[c]]);for(let c=t;c!==e;){const l=r[c],u=i[l];n.capacity[l]-=a,n.capacity[u]+=a,n.inOrder[u]===0&&(n.inOrder[u]=1,n.order[n.rowPtr[c]+n.placed[c]++]=u),n.real[l]===1?o[l]+=a:o[u]-=a,c=s[u]}return a}function P3(n,e,t,r){const o=n.edgeCount,s=new Float64Array(o),{rowPtr:i,colIdx:a,arcToEdge:c,groupOf:l}=e;for(let u=0;u<n.nodeCount;u++)for(let d=i[u];d<i[u+1];d++){const f=a[d];if(l[d]!==d||f<=u)continue;const h=r[d]-r[e.twin[d]];if(h===0)continue;const g=h>0?d:e.twin[d],w=i[a[e.twin[g]]+1];let p=Math.abs(h),m=-1,y=1;for(let b=g;b<w&&l[b]===g;b++){const v=c[b];if(!(v>=o&&n.directed)){if(m>=0){const A=Math.min(p,Math.max(t[m],0));s[m]+=y*A,p-=A}m=v<o?v:v-o,y=v<o?1:-1}}m>=0&&(s[m]+=y*p)}return s}function hh(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=_c(n,o,s,{...r,algorithm:r.algorithm??"ford-fulkerson"});return{...to(i.sourceSide,n.nodeCount),cutValue:i.maxFlow,side:i.sourceSide,cutEdges:i.cutEdges}}function x3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n;r.fill(x);const l=new Uint32Array(r.length);let u=0,d=0;for(l[d++]=e;u<d;){const f=l[u++],h=o[f]+a[f];for(let g=o[f];g<h;g++){const w=i[g],p=s[w];if(c[w]>0&&p!==e&&r[p]===x){if(r[p]=w,p===t)return!0;l[d++]=p}}}return!1}function C3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n,l=r.length;r.fill(x);const u=new Uint8Array(l),d=new Uint32Array(l),f=new Uint32Array(l);let h=0;for(d[h++]=e,u[e]=1,f[e]=o[e];h>0;){const g=d[h-1],w=f[g]++;if(w>=o[g]+a[g]){h--;continue}const p=i[w],m=s[p];if(c[p]>0&&u[m]===0){if(r[m]=p,m===t)return!0;u[m]=1,f[m]=o[m],d[h++]=m}}return!1}function N3(n,e){const{rowPtr:t,colIdx:r,order:o,placed:s,capacity:i}=n,a=t.length-1,c=At(a),l=new Uint32Array(a);let u=0,d=0;for(l[d++]=e,pn(c,e,!0);u<d;){const f=l[u++],h=t[f]+s[f];for(let g=t[f];g<h;g++){const w=r[o[g]];i[o[g]]>0&&!_e(c,w)&&(pn(c,w,!0),l[d++]=w)}}return c}function no(n){let e=n>>>0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}const T3=2147483647;function O3(n,e){for(let t=0;t<n.nodeCount;t++){const r=n.rowPtr[t+1];for(let o=n.rowPtr[t];o<r;o++)if(n.colIdx[o]!==t&&(e===null||e[o]>0))return!0}return!1}function gh(n,e,t){for(let r=0;r<e.length;r++){if(t!==null&&t[r]===1)continue;const o=n.collect(r,e);if(o!==0&&n.voteOf(e[r])!==o)return!1}return!0}function Ic(n,e){if(e===null)return n.weights;const t=new Float64Array(n.arcCount);for(let r=0;r<t.length;r++)t[r]=e[n.arcToEdge[r]];return t}function li(n){const e=n.edges.byRole("weight");return e!==null&&e.dtype==="f64"?e.data:null}function kc(n,e){const t=e?Ic(n,li(n)):null;if(t!==null)for(let o=0;o<t.length;o++){const s=t[o];if(!(s>=0)||s===1/0)throw Q(new RangeError(`arc ${o} has weight ${s}; label propagation needs finite, non-negative weights`),"E_BAD_WEIGHT")}const r=n.directed?n.reverse():null;return{sides:r===null?1:2,rowPtrs:[n.rowPtr,r===null?n.rowPtr:r.rowPtr],colIdxs:[n.colIdx,r===null?n.colIdx:r.colIdx],arcWeights:[t,t===null||r===null?t:Ic(r,li(n))],weights:t}}function Sc(n,e,t){if(!Number.isInteger(e)||e<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${e}`),"E_BAD_OPTION");if(t!==null&&!Number.isInteger(t))throw Q(new RangeError(`randomSeed must be a finite integer, got ${t}`),"E_BAD_OPTION");if(e*n>Number.MAX_SAFE_INTEGER)throw Q(new RangeError(`maxIterations * nodeCount (${e} * ${n}) exceeds Number.MAX_SAFE_INTEGER`),"E_BAD_OPTION")}class Pc{constructor(e,t,r){this.rows=t,this.epoch=-1,this.count=0,this.acc=new Float64Array(e),this.stamp=new Int32Array(e).fill(-1),this.touched=new Uint32Array(e),this.seen=r?null:new Int32Array(e).fill(-1)}collect(e,t){++this.epoch===T3&&(this.stamp.fill(-1),this.seen?.fill(-1),this.epoch=0);const{acc:r,stamp:o,touched:s,seen:i,rows:a}=this,c=this.epoch;let l=0;for(let d=0;d<a.sides;d++){const f=a.rowPtrs[d],h=a.colIdxs[d],g=a.arcWeights[d],w=f[e+1];for(let p=f[e];p<w;p++){const m=h[p];if(m===e)continue;if(i!==null){if(i[m]===c)continue;i[m]=c}const y=t[m];if(y===x)continue;const b=g===null?1:g[p];o[y]!==c?(o[y]=c,r[y]=b,s[l++]=y):r[y]+=b}}this.count=l;let u=0;for(let d=0;d<l;d++)r[s[d]]>u&&(u=r[s[d]]);return u}voteOf(e){return this.stamp[e]===this.epoch?this.acc[e]:0}}function wh(n,e,t,r,o,s,i){const a=n.nodeCount,c=no(i),l=new Pc(a,e,t),u=a+1,d=new Uint32Array(u),f=new Uint8Array(a);let h=0;for(let v=0;v<a;v++)(o===null||o[v]===0)&&(d[h++]=v,f[v]=1);for(let v=h-1;v>=1;v--){const A=Math.floor(c()*(v+1)),E=d[v];d[v]=d[A],d[A]=E}let g=0,w=h;const p=s*a;let m=0;const{touched:y,acc:b}=l;for(;h>0&&m<p;){const v=d[g];g=g+1===u?0:g+1,h--,f[v]=0,m++;const A=l.collect(v,r);if(A===0)continue;let E=0,I=0;for(let k=0;k<l.count;k++){const N=y[k];b[N]===A&&(I++,(I===1||c()*I<1)&&(E=N))}if(E!==r[v]){r[v]=E;for(let k=0;k<e.sides;k++){const N=e.rowPtrs[k],C=e.colIdxs[k],O=N[v+1];for(let T=N[v];T<O;T++){const $=C[T];f[$]===0&&r[$]!==E&&(o===null||o[$]===0)&&(f[$]=1,d[w]=$,w=w+1===u?0:w+1,h++)}}}}return{visits:m,size:h}}function ph(n,e={}){const t=e.maxIterations??100,r=e.randomSeed??42,o=e.weighted??!0,s=n.nodeCount;Sc(s,t,r);const i=kc(n,o),a=new Uint32Array(s);for(let f=0;f<s;f++)a[f]=f;if(s===0||t===0){const{labels:f,count:h}=Je(a);return{...We(f,h),iterations:0,converged:!O3(n,i.weights)}}const{visits:c,size:l}=wh(n,i,o,a,null,t,r),{labels:u,count:d}=Je(a);return{...We(u,d),iterations:Math.ceil(c/s),converged:l===0}}function $3(n,e,t={}){const r=t.maxIterations??100,o=t.randomSeed??42,s=t.weighted??!0,i=n.nodeCount;if(e.length!==i)throw Q(new RangeError(`seeds has ${e.length} entries; the snapshot has ${i} nodes`),"E_BAD_OPTION");Sc(i,r,o);const a=kc(n,s),c=new Uint32Array(i),l=new Uint8Array(i),u=new Map;for(let p=0;p<i;p++){const m=e[p];if(m===x){c[p]=x;continue}let y=u.get(m);y===void 0&&(y=p,u.set(m,p)),c[p]=y,l[p]=1}const{visits:d,size:f}=wh(n,a,s,c,l,r,o),h=f===0||r===0&&gh(new Pc(i,a,s),c,l);R3(a,c);const{labels:g,count:w}=Je(c);return{...We(g,w),iterations:i===0?0:Math.ceil(d/i),converged:h}}function R3(n,e){const t=[];for(let r=0;r<e.length;r++)if(e[r]===x)for(e[r]=r,t.push(r);t.length>0;)D3(n,e,t.pop(),r,t)}function D3(n,e,t,r,o){for(let s=0;s<n.sides;s++){const i=n.rowPtrs[s],a=n.colIdxs[s],c=n.arcWeights[s],l=i[t+1];for(let u=i[t];u<l;u++){const d=a[u];e[d]===x&&(c===null||c[u]>0)&&(e[d]=r,o.push(d))}}}function mh(n,e={}){const t=e.maxIterations??100,r=e.weighted??!0,o=n.nodeCount;Sc(o,t,null);const s=kc(n,r),i=new Pc(o,s,r),{touched:a,acc:c}=i;let l=new Uint32Array(o),u=new Uint32Array(o),d=new Uint32Array(o).fill(x);const f=new Uint32Array(o);for(let b=0;b<o;b++)l[b]=b,f[b]=L3(b);let h=0,g=0,w=!1;for(;g<2&&h<t&&!w;){const b=h%2===0;h++;let v=!1;for(let A=0;A<o;A++){const E=l[A];u[A]=E;const I=i.collect(A,l);if(I===0||i.voteOf(E)===I)continue;let k=x;for(let N=0;N<i.count;N++){const C=a[N];c[C]===I&&(k===x||f[C]<f[k])&&(k=C)}(b?f[k]>f[E]:f[k]<f[E])&&(u[A]=k,v=!0)}w=v&&M3(u,d),[d,l,u]=[l,u,d],g=v?0:g+1}const p=g>=2||gh(i,l,null),{labels:m,count:y}=Je(l);return{...We(m,y),iterations:h,converged:p}}function L3(n){return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function M3(n,e){for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function xc(n,e,t={}){const r=t.resolution??1,o=t.weights??n.weights;if(e.length!==n.nodeCount)throw Q(new RangeError(`labels has ${e.length} entries; the snapshot has ${n.nodeCount} nodes`),"E_BAD_OPTION");if(o!==null&&o.length!==n.arcCount)throw Q(new RangeError(`weights has ${o.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const s=new Map,i=new Map,a=(u,d,f)=>{d!==x&&u.set(d,(u.get(d)??0)+f)};let c=0;for(let u=0;u<n.nodeCount;u++){const d=n.rowPtr[u+1];for(let f=n.rowPtr[u];f<d;f++){const h=n.colIdx[f],g=o===null?1:o[f],w=n.directed||h===u?2*g:g;c+=w,n.directed?(a(s,e[u],g),a(s,e[h],g)):a(s,e[u],w),e[u]===e[h]&&a(i,e[u],w)}}if(c===0)return 0;let l=0;for(const[u,d]of s){const f=d/c;l+=(i.get(u)??0)/c-r*f*f}return l}const U3=1e-10;function F3(n,e){const t=new eo(n.nodeCount),r=n.edgeList();for(let o=0;o<n.edgeCount;o++)_e(e,o)&&t.union(r.src[o],r.dst[o]);return t.toLabels()}function yh(n,e={}){if(n.directed)throw Q(new Error("Girvan-Newman requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.maxCommunities??0,r=e.minCommunitySize??1,o=e.maxIterations??100,{nodeCount:s,edgeCount:i}=n,a=Ic(n,li(n)),c=At(i,!0),l=[],u=[],d=[],f=()=>{const{labels:g,count:w}=F3(n,c);l.push(g),d.push(w),u.push(xc(n,g,a===null?{}:{weights:a}));const p=new Uint32Array(w);for(let m=0;m<s;m++)p[g[m]]++;return p.filter(m=>m>=r).length};f();for(let g=0;g<o&&z2(c,i)>0;g++){const w=dc(n,{alive:c}).scores;let p=-1/0;for(let y=0;y<i;y++)_e(c,y)&&w[y]>p&&(p=w[y]);for(let y=0;y<i;y++)_e(c,y)&&Math.abs(w[y]-p)<U3&&pn(c,y,!1);const m=f();if(t>0&&m>=t||m===s)break}let h=0;for(let g=1;g<u.length;g++)(u[g]>u[h]||Number.isNaN(u[h])&&!Number.isNaN(u[g]))&&(h=g);return{...We(l[h],d[h]),bestLevel:h,levels:l,modularity:Float64Array.from(u)}}function B3(n,e={}){const{maxDepth:t=10,minClusterSize:r=2,tolerance:o=1e-6,maxIterations:s=100,seed:i=42,weighted:a=!0}=e,c=n.nodeCount;if(c===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const l=no(i),u=a?n.weights:null;if(u!==null)for(let M=0;M<u.length;M++){const R=u[M];if(!(R>=0)||R===1/0)throw Q(new RangeError(`arc ${String(M)} has weight ${String(R)}; grsbm needs finite, non-negative weights`),"E_BAD_WEIGHT")}const d=a?n.weightedDegree():n.degree(),f=a?n.totalWeight():n.edgeCount,h=n.directed?1:2,g=!n.directed||!a,{rowPtr:w,colIdx:p}=n,m=new Int32Array(c).fill(-1),y=M=>{let R=0,D=0;for(let U=0;U<M.length;U++){const B=M[U];D+=d[B];for(let V=w[B];V<w[B+1];V++){const W=p[V];if(m[W]===m[B]){const q=u===null?1:u[V];R+=W===B?h*q:q}}}return g&&(R/=2),(R-D*D/(4*f))/f},b=M=>{if(f===0)return 0;let R=0;M.forEach((D,U)=>{for(let B=0;B<D.length;B++)m[D[B]]=U});for(const D of M)D.length>0&&(R+=y(D));for(const D of M)for(let U=0;U<D.length;U++)m[D[U]]=-1;return R},v=new Uint32Array(c);for(let M=0;M<c;M++)v[M]=M;const A=b([v]),E=[{serial:0,members:v,depth:0,modularity:A,spectralScore:0,left:x,right:x,split:null}],I=[A];let k=A;const N=new Int32Array(c).fill(-1);let C=1;for(let M=0;M<E.length;M++){const R=E[M],{members:D}=R,U=D.length;if(R.depth>=t||U<r*2||U<4)continue;const B=z3(D,N,n,u,l,o,s),V=Array.from({length:U},(ue,we)=>we).sort((ue,we)=>B[ue]-B[we]),W=Uint32Array.from(V,ue=>D[ue]);let q=Math.floor(U/2),K=-1/0;for(let ue=Math.floor(U*.2);ue<=Math.floor(U*.8);ue++){const we=b([W.subarray(0,ue),W.subarray(ue)]);we>K&&(K=we,q=ue)}const X=W.slice(0,q),H=W.slice(q),Y=Array.from(B).sort((ue,we)=>Math.abs(we)-Math.abs(ue)),ee=Math.abs(Y[Math.floor(U*.1)]),Z=[];for(let ue=0;ue<U&&Z.length<5;ue++)Math.abs(B[ue])>=ee&&Z.push(D[ue]);const J=Math.abs(Y[0]-Y[U-1]),ce=C++,de=C++,ne=K-b([D]);if(ne<=0)continue;k+=ne;const ve=(ue,we)=>({serial:ue,members:we,depth:R.depth+1,modularity:k,spectralScore:J,left:x,right:x,split:null});R.left=E.length,R.right=E.length+1,R.split={improvement:ne,bisectionModularity:k,keyNodes:Uint32Array.from(Z),spectralValues:B},E.push(ve(ce,X),ve(de,H)),I.push(k)}const O=new Uint32Array(c);let T=0;const $=[0];for(;$.length>0;){const M=E[$.pop()??0];if(M.left===x){for(const R of M.members)O[R]=T;T++}else $.push(M.right,M.left)}const{labels:L,count:F}=Je(O);return{...We(L,F),clusters:E,modularityScores:Float64Array.from(I)}}function z3(n,e,t,r,o,s,i){const a=n.length;for(let y=0;y<a;y++)e[n[y]]=y;const c=new Uint32Array(a+1),l=[],u=[],d=new Map;let f=0;for(let y=0;y<a;y++){const b=n[y];d.clear();let v=0;for(let A=t.rowPtr[b];A<t.rowPtr[b+1];A++){const E=e[t.colIdx[A]];if(E>=0&&E!==y){const I=r===null?1:r[A];d.set(E,(d.get(E)??0)-I),v+=I}}d.set(y,v),f=Math.max(f,v);for(const A of[...d.keys()].sort((E,I)=>E-I))l.push(A),u.push(d.get(A)??0);c[y+1]=l.length}for(let y=0;y<a;y++)e[n[y]]=-1;let h=new Float64Array(a);for(let y=0;y<a;y++)h[y]=o()-.5;const g=y=>{let b=0;for(const A of y)b+=A;const v=b/a;for(let A=0;A<a;A++)y[A]-=v},w=y=>{let b=0;for(const v of y)b+=v*v;return Math.sqrt(b)};g(h);const p=w(h);if(p>0)for(let y=0;y<a;y++)h[y]/=p;const m=2*f;for(let y=0;y<i;y++){const b=new Float64Array(a);for(let E=0;E<a;E++){let I=0;for(let k=c[E];k<c[E+1];k++)I+=u[k]*h[l[k]];b[E]=m*h[E]-I}g(b);const v=w(b);if(v<s)break;let A=0;for(let E=0;E<a;E++)b[E]/=v,A+=Math.abs(b[E]-h[E]);if(h=b,A<s)break}return h}function G3(n,e){const t=n.nodeCount;e.fill(x);const r=new Uint32Array(t);for(let o=0;o<t;o++){const s=o*t;e[s+o]=0,r[0]=o;let i=0,a=1;for(;i<a;){const c=r[i++],l=e[s+c]+1,u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++){const f=n.colIdx[d];e[s+f]===x&&(e[s+f]=l,r[a++]=f)}}}}function W3(n){const e=Math.max(0,2*n-1),t=Array.from({length:e},(s,i)=>i<n?`leaf-${i}`:`cluster-${i}`),r=Array.from({length:e},(s,i)=>i).sort((s,i)=>+(t[s]>t[i])-+(t[s]<t[i])),o=new Uint32Array(e);return r.forEach((s,i)=>o[s]=i),o}function V3(n,e={}){const t=e.linkage??"single";if(!["single","complete","average","ward"].includes(t))throw Q(new RangeError(`unknown linkage "${t}"`),"E_BAD_OPTION");const r=n.nodeCount,{hops:o,min:s,max:i,sum:a,count:c}=Lf("hierarchicalClustering",r,e.maxNodes,28*r*r,()=>({hops:new Uint32Array(r*r),min:new Uint32Array(r*r),max:new Uint32Array(r*r),sum:new Float64Array(r*r),count:new Float64Array(r*r)}));G3(n,o);for(let T=0;T<r*r;T++){const $=o[T];$!==x&&(s[T]=$,i[T]=$,a[T]=$,c[T]=1)}const l=Math.max(0,2*r-1),u=W3(r),d=new Uint32Array(l),f=new Float64Array(l),h=new Uint32Array(l);for(let T=0;T<r;T++)d[T]=T,f[T]=1;const g=[],w=[],p=[],m=(T,$)=>{const L=d[T]*r+d[$],F=c[L];if(F===0)return 1/0;switch(t){case"single":return s[L];case"complete":return i[L];case"average":return a[L]/F;default:return a[L]/F*(f[T]*f[$]/(f[T]+f[$]))}},y=(T,$)=>{const[L,F]=T<$?[T,$]:[$,T];return F<r?m(L,F):m(F,L)};let b=Array.from({length:r},(T,$)=>$);for(;b.length>1;){let T=1/0,$=-1,L=-1;for(const D of b)for(const U of b){if(u[D]>=u[U])continue;const B=y(D,U);B<T&&(T=B,$=D,L=U)}if($<0)break;const F=r+g.length;g.push($),w.push(L),p.push(T),h[F]=Math.max(h[$],h[L])+1,f[F]=f[$]+f[L];const M=d[$],R=d[L];for(const D of b){if(D===$||D===L)continue;const U=d[D];for(const[B,V,W]of[[M*r+U,M*r+U,R*r+U],[U*r+M,U*r+M,U*r+R]]){const q=c[V],K=c[W];if(q===0||K===0){const X=q===0?W:V;s[B]=s[X],i[B]=i[X]}else s[B]=Math.min(s[V],s[W]),i[B]=Math.max(i[V],i[W]);a[B]=a[V]+a[W],c[B]=q+K}}d[F]=M,b=b.filter(D=>D!==$&&D!==L),b.push(F)}const v=g.length,A=Uint32Array.from(g),E=Uint32Array.from(w),I=T=>{if(!(T>=0&&T<r+v))throw Q(new RangeError(`cluster ${T} is not in [0, ${r+v})`),"E_BAD_OPTION");const $=[],L=[T];for(;L.length>0;){const F=L.pop();F<r?$.push(F):L.push(E[F-r],A[F-r])}return Uint32Array.from($)},k=Uint32Array.from(b),N=Float64Array.from(p),C=new Uint32Array(v);for(let T=0;T<v;T++)C[T]=A[T]<r?A[T]:C[A[T]-r];const O=T=>T<r?T:C[T-r];return{nodeCount:r,left:A,right:E,distance:N,height:h.slice(0,r+v),roots:k,members:I,cut(T){const $=[],L=F=>{F<r||h[F]<=T?$.push(I(F)):(L(A[F-r]),L(E[F-r]))};return k.forEach(L),$},cutAt(T){let $=0;if("clusters"in T){const R=T.clusters;if(!Number.isInteger(R)||R<k.length||R>r)throw Q(new RangeError(`clusters must be an integer in [${k.length}, ${r}], got ${R}`),"E_BAD_OPTION");$=r-R}else{if(Number.isNaN(T.distance))throw Q(new RangeError("distance must not be NaN"),"E_BAD_OPTION");for(;$<v&&N[$]<=T.distance;)$++}const L=new eo(r);for(let R=0;R<$;R++)L.union(O(A[R]),O(E[R]));const{labels:F,count:M}=L.toLabels();return We(F,M)}}}function bh(n){let e=0;for(let r=0;r<n.length;r++)e+=n[r]*n[r];const t=Math.sqrt(e);if(t>0)for(let r=0;r<n.length;r++)n[r]/=t}function vh(n){let e=0;for(let t=0;t<n.length;t++)n[t]>e&&(e=n[t]);if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function Ah(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.reverse(),i=e.weighted===!0?n.weights:null,a=e.weighted===!0?s.weights:null;let c=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),l=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),u=new Float64Array(t),d=new Float64Array(t),f=0,h=!1;for(;f<r&&!h;f++){for(let w=0;w<t;w++){let p=0;const m=s.rowPtr[w+1];for(let v=s.rowPtr[w];v<m;v++)p+=c[s.colIdx[v]]*(a===null?1:a[v]);d[w]=p;let y=0;const b=n.rowPtr[w+1];for(let v=n.rowPtr[w];v<b;v++)y+=l[n.colIdx[v]]*(i===null?1:i[v]);u[w]=y}bh(d),bh(u);let g=0;for(let w=0;w<t;w++){const p=Math.abs(u[w]-c[w]);p>g&&(g=p);const m=Math.abs(d[w]-l[w]);m>g&&(g=m)}[c,u]=[u,c],[l,d]=[d,l],h=g<o}return e.normalized===!1&&(vh(c),vh(l)),{hubs:c,authorities:l,iterations:f,converged:h}}function Eh(n,e){let t=0,r=!1,o=x;for(let s=n.rowPtr[e];s<n.rowPtr[e+1];s++){const i=n.colIdx[s];i!==o&&(o=i,i===e?r=!0:t++)}return{degree:t,loop:r}}function _h(n){const e=new Float64Array(n.nodeCount),t=n.directed?n.reverse():null;for(let r=0;r<n.nodeCount;r++){const o=Eh(n,r),s=t===null?0:Eh(t,r).degree;e[r]=(o.degree*67108864+s)*2+(o.loop?1:0)}return e}function j3(n,e){const t=new Uint32Array(e),r=new Uint32Array(e).fill(x),o=new Uint8Array(e),s=new Uint8Array(e);let i=0;for(let a=0;a<e;a++){if(s[a]===1)continue;s[a]=1;let c=i;for(t[i++]=a;c<i;)i=q3(n,t[c++],{order:t,parent:r,parentView:o},s,i)}return{order:t,parent:r,parentView:o}}function q3(n,e,t,r,o){const{order:s,parent:i,parentView:a}=t;for(let c=0;c<n.length;c++){const{rowPtr:l,colIdx:u}=n[c];for(let d=l[e];d<l[e+1];d++){const f=u[d];r[f]===0&&(r[f]=1,i[f]=e,a[f]=c,s[o++]=f)}}return o}function Ih(n,e,t,r){const o=n.nodeCount;if(n.directed!==e.directed||o!==e.nodeCount)return;const s=_h(n),i=_h(e),a=s.slice().sort(),c=i.slice().sort();if(a.some((O,T)=>O!==c[T]))return;const l=n.directed?[n,n.reverse()]:[n],u=e.directed?[e,e.reverse()]:[e],{order:d,parent:f,parentView:h}=j3(l,o),g=new Uint32Array(o).fill(x),w=new Uint32Array(o).fill(x),p=u.map(()=>new Uint32Array(o)),m=u.map(()=>new Uint32Array(o));let y=0;const{nodeMatch:b,edgeMatch:v}=t,A=(O,T)=>{if(s[O]!==i[T]||b!==void 0&&!b(O,T,n,e))return!1;if(v!==void 0&&s[O]%2===1){const $=n.arcToEdge[n.findArc(O,O)],L=e.arcToEdge[e.findArc(T,T)];if(!v($,L,n,e))return!1}y++;for(let $=0;$<l.length;$++){const L=l[$],F=u[$];let M=0,R=x;for(let U=F.rowPtr[T];U<F.rowPtr[T+1];U++){const B=F.colIdx[U];B===R||B===T||(R=B,p[$][B]=y,m[$][B]=U,w[B]!==x&&M++)}let D=0;R=x;for(let U=L.rowPtr[O];U<L.rowPtr[O+1];U++){const B=L.colIdx[U];if(B===R||B===O)continue;R=B;const V=g[B];if(V!==x&&(p[$][V]!==y||(D++,v!==void 0&&!v(L.arcToEdge[U],F.arcToEdge[m[$][V]],n,e))))return!1}if(D!==M)return!1}return!0},E=new Uint32Array(o+1);let I=0,k=!1;const N=O=>{const T=f[d[O]];if(T===x)return{view:null,from:0,to:o};const $=u[h[d[O]]],L=g[T];return{view:$,from:$.rowPtr[L],to:$.rowPtr[L+1]}};if(o===0){r(g);return}let C=N(0);for(E[0]=C.from;!k;){const O=d[I];let T=!1;for(;E[I]<C.to;){const L=E[I]++,F=C.view===null?L:C.view.colIdx[L];if(!(C.view!==null&&L>C.from&&C.view.colIdx[L-1]===F)&&!(w[F]!==x||!A(O,F))){if(g[O]=F,w[F]=O,I===o-1){if(k=r(g),g[O]=x,w[F]=x,k)break;continue}I++,C=N(I),E[I]=C.from,T=!0;break}}if(k||T)continue;if(I===0)return;I--;const $=d[I];w[g[$]]=x,g[$]=x,C=N(I)}}function H3(n,e,t={}){let r=null;return Ih(n,e,t,o=>(r=o.slice(),!0)),{isomorphic:r!==null,mapping:r}}function K3(n,e,t={}){const r=[];return Ih(n,e,t,o=>(r.push(o.slice()),!1)),r}function kh(n){if(n.directed)throw Q(new Error("k-core requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const e=n.nodeCount,{rowPtr:t,colIdx:r}=n,o=new Uint32Array(e);let s=0;for(let f=0;f<e;f++){let h=0,g=-1;const w=t[f+1];for(let p=t[f];p<w;p++){const m=r[p];m!==f&&m!==g&&h++,g=m}o[f]=h,h>s&&(s=h)}const i=new Uint32Array(s+1);for(let f=0;f<e;f++)i[o[f]]++;let a=0;for(let f=0;f<=s;f++){const h=i[f];i[f]=a,a+=h}const c=new Uint32Array(e),l=new Uint32Array(e);for(let f=0;f<e;f++)l[f]=i[o[f]],c[l[f]]=f,i[o[f]]++;for(let f=s;f>0;f--)i[f]=i[f-1];i[0]=0;let u=0;for(let f=0;f<e;f++){const h=c[f],g=o[h];g>u&&(u=g);const w=t[h+1];let p=-1;for(let m=t[h];m<w;m++){const y=r[m],b=y===h||y===p;if(p=y,b)continue;const v=o[y];if(v>g){const A=l[y],E=i[v],I=c[E];y!==I&&(c[A]=I,c[E]=y,l[y]=E,l[I]=A),i[v]++,o[y]=v-1}}}let d=null;return{coreness:o,maxCore:u,cores(){if(d===null){const f=new Uint32Array(u+1);for(let w=0;w<e;w++)f[o[w]]++;const h=[];for(let w=0;w<=u;w++)h.push(new Uint32Array(f[w]));const g=new Uint32Array(u+1);for(let w=0;w<e;w++){const p=o[w];h[p][g[p]++]=w}d=h}return d}}}function Sh(n,e={}){const t=n.nodeCount,r=e.alpha??.1,o=e.beta??1,s=e.maxIterations??100,i=e.tolerance??1e-6,a=n.reverse(),c=e.weighted===!0?a.weights:null;let l=new Float64Array(t).fill(o),u=new Float64Array(t),d=0,f=!1;for(;d<s&&!f;d++){let h=0;for(let g=0;g<t;g++){let w=0;const p=a.rowPtr[g+1];for(let y=a.rowPtr[g];y<p;y++)w+=l[a.colIdx[y]]*(c===null?1:c[y]);u[g]=r*w+o;const m=Math.abs(u[g]-l[g]);m>h&&(h=m)}[l,u]=[u,l],f=h<i}if(e.normalized!==!1){let h=1/0,g=-1/0;for(let p=0;p<t;p++)l[p]<h&&(h=l[p]),l[p]>g&&(g=l[p]);const w=g-h;if(w>0)for(let p=0;p<t;p++)l[p]=(l[p]-h)/w}return{scores:l,iterations:d,converged:f}}const Y3=.01,X3=3;function Ph(n,e){const{nodeCount:t,rowPtr:r,colIdx:o,arcToEdge:s}=n,i=new Float64Array(n.arcCount),a=new Float64Array(t);for(let c=0;c<t;c++)for(let l=r[c],u=r[c+1];l<u;l++){const d=e[s[l]];i[l]=d,a[c]+=o[l]===c?2*d:d}return{s:n,edgeW:e,arcW:i,deg:a}}function xh(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=r;for(let r=n-1;r>=1;r--){const o=Math.floor(e()*(r+1)),s=t[r];t[r]=t[o],t[o]=s}return t}function Q3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c),f=new Uint32Array(c);for(let I=0;I<c;I++)d[e[I]]+=a[I],f[e[I]]++;const h=[];for(let I=c-1;I>=0;I--)f[I]===0&&h.push(I);const g=new Float64Array(c),w=new Int32Array(c).fill(-1),p=new Uint32Array(c),m=c+1,y=new Uint32Array(m);y.set(xh(c,t));const b=new Uint8Array(c).fill(1);let v=0,A=c,E=0;for(;v!==A;){const I=y[v];v=v+1===m?0:v+1,b[I]=0,E++;const k=e[I],N=a[I];d[k]-=N,f[k]--;let C=0;for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];if(F===I)continue;const M=e[F];w[M]!==E&&(w[M]=E,g[M]=0,p[C++]=M),g[M]+=i[$]}let O=k,T=(w[k]===E?g[k]:0)-r*N*d[k]/o;for(let $=0;$<C;$++){const L=p[$],F=g[L]-r*N*d[L]/o;L!==k&&F>T&&(T=F,O=L)}if(f[k]>0&&T<0&&(O=h[h.length-1]),O!==k&&f[O]===0&&h.pop(),d[O]+=N,f[O]++,O!==k){e[I]=O,f[k]===0&&h.push(k);for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];b[F]===0&&e[F]!==O&&(b[F]=1,y[A]=F,A=A+1===m?0:A+1)}}}}function J3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c);for(let v=0;v<c;v++)d[e[v]]+=a[v];const f=new Uint32Array(c),h=new Float64Array(c),g=new Uint32Array(c),w=new Float64Array(c);for(let v=0;v<c;v++){f[v]=v,h[v]=a[v],g[v]=1;for(let A=l[v],E=l[v+1];A<E;A++){const I=u[A];I!==v&&e[I]===e[v]&&(w[v]+=i[A])}}const p=new Float64Array(c),m=new Int32Array(c).fill(-1),y=new Uint32Array(c),b=xh(c,t);for(let v=0;v<c;v++){const A=b[v],E=e[A],I=a[A];if(g[A]!==1||w[A]<r*I*(d[E]-I)/o)continue;let k=0;for(let M=l[A],R=l[A+1];M<R;M++){const D=u[M];if(D===A||e[D]!==E)continue;const U=f[D];m[U]!==A&&(m[U]=A,p[U]=0,y[k++]=U),p[U]+=i[M]}const N=M=>p[M]-r*I*h[M]/o;let C=-1/0,O=0;for(let M=0;M<k;M++){const R=y[M],D=N(R);D>=0&&w[R]>=r*h[R]*(d[E]-h[R])/o&&(y[O++]=R,C=Math.max(C,D))}if(O===0)continue;const T=M=>Qr((N(M)-C)*2/o/Y3);let $=0;for(let M=0;M<O;M++)$+=T(y[M]);let L=t()*$,F=y[O-1];for(let M=0;M<O-1;M++)if(L-=T(y[M]),L<0){F=y[M];break}f[A]=F,g[A]=0,g[F]++,h[F]+=I,w[F]+=w[A]-2*p[F]}return f}function Z3(n,e,t,r,o){const s=n.s.nodeCount,i=new Uint32Array(s);for(let d=0;d<s;d++)i[d]=d;let a=n,c=e.slice(),l=0;for(;;){Q3(a,c,t,r,o),l++;const d=Je(c);if(d.count===a.s.nodeCount)break;let f=J3(a,d.labels,t,r,o);Je(f).count===a.s.nodeCount&&(f=d.labels);const h=a.s.contract(f),{nodeRemap:g,edgeRemap:w}=h,p=h.snapshot,m=new Float64Array(p.edgeCount);for(let b=0;b<a.edgeW.length;b++)m[w===null?b:w[b]]+=a.edgeW[b];const y=new Uint32Array(p.nodeCount);for(let b=0;b<a.s.nodeCount;b++)y[g===null?b:g[b]]=d.labels[b];if(g!==null)for(let b=0;b<s;b++)i[b]=g[i[b]];c=Je(y).labels,a=Ph(p,m)}const u=new Uint32Array(s);for(let d=0;d<s;d++)u[d]=c[i[d]];return{comm:u,levels:l}}function eE(n){const e=li(n)??n.edgeList().weights,t=e===null?new Float64Array(n.edgeCount).fill(1):Float64Array.from(e);for(let r=0;r<t.length;r++){const o=t[r];if(!(o>=0)||o===1/0)throw Q(new RangeError(`edge ${r} has weight ${o}; Leiden needs finite, non-negative weights`),"E_BAD_WEIGHT")}return t}function Ch(n,e={}){if(n.directed)throw Q(new Error("Leiden requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.randomSeed??42,o=e.maxIterations??100,s=e.threshold??1e-7;if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const i=n.nodeCount,a=Ph(n,eE(n));let c=0;for(let w=0;w<i;w++)c+=a.deg[w];let l=new Uint32Array(i);for(let w=0;w<i;w++)l[w]=w;if(c===0)return{...We(l,i),modularity:0,iterations:0};const u=w=>xc(n,w,{resolution:t,weights:a.arcW}),d=no(r);let f=u(l),h=0,g=0;for(let w=0;w<o&&g<X3;w++){const{comm:p,levels:m}=Z3(a,l,d,t,c);h+=m;const y=Je(p).labels,b=u(y);b>f?(g=b-f<=s?g+1:0,l=y,f=b):g++}return{...We(l,Je(l).count),modularity:f,iterations:h}}const Nh=2**36;function tE(n){return n>1?Math.round(Nh/Ge(n))/Nh:n===1?1:0}function Th(n,e){const t=n.rowPtr[e],r=n.rowPtr[e+1];let o=0;for(let s=t;s<r;s++)(s===t||n.colIdx[s]!==n.colIdx[s-1])&&o++;return o}function Oh(n,e){const t=n.directed&&!e?n.reverse():void 0;return r=>tE(Th(n,r)+(t===void 0?0:Th(t,r)))}function ro(n,e,t){const r=e.directed===!0?n.reverse():n,o=n.nodeCount;return(s,i)=>s<o&&i<o?Zf(n,r,s,i,t):0}function ui(n,e){const t=Oh(n,e.directed===!0),r=Float64Array.from({length:n.nodeCount},(o,s)=>t(s));return ro(n,e,o=>r[o])}function $h(n,e,t,r){const o=Array.from(t,(s,i)=>i).sort((s,i)=>t[i]-t[s]).slice(0,r);return{sources:Uint32Array.from(o,s=>n[s]),targets:Uint32Array.from(o,s=>e[s]),scores:Float64Array.from(o,s=>t[s])}}function nE(n,e,t,r,o,s,i){n.push(r),e.push(o),t.push(s),i&&(n.push(o),e.push(r),t.push(s))}function Rh(n,e,t){const r=[],o=[],s=[],i=e.directed!==!0&&e.uniquePairs!==!0;for(let c=0;c<n.nodeCount;c++)for(let l=c+1;l<n.nodeCount;l++){if(e.includeExisting!==!0&&n.hasArc(c,l))continue;const u=t(c,l);u>0&&nE(r,o,s,c,l,u,i)}const{topK:a}=e;return $h(r,o,s,a!==void 0&&a>0?a:s.length)}function oo(n,e){return Float64Array.from(n.sources,(t,r)=>e(t,n.targets[r]))}function Dh(n,e,t,r){const o=n.nodeCount,s=[],i=[],a=[];if(e<o){const c=t.candidates===void 0?Array.from({length:o},(l,u)=>u):ss(n,t.candidates);for(let l=0;l<c.length;l++){const u=c[l];if(u===e||t.includeExisting!==!0&&u<o&&n.hasArc(e,u))continue;const d=r(e,u);d>0&&(s.push(e),i.push(u),a.push(d))}}return $h(s,i,a,t.topK??10)}function Lh(n,e){const t=[...n,...e],r=Array.from(t,(u,d)=>d).sort((u,d)=>t[d]-t[u]);let o=0,s=0,i=0,a=0,c=0,l=0;for(const u of r){u<n.length?o++:(l+=o,s++);const d=o/(o+s),f=o/n.length,h=d+f>0?2*(d*f)/(d+f):0;h>i&&(i=h,a=d,c=f)}return l=o>0&&s>0?l/(o*s):.5,{precision:a,recall:c,f1Score:i,auc:l}}function Mh(n,e={}){return Rh(n,e,ro(n,e))}function rE(n,e,t={}){return oo(e,ro(n,t))}function oE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ro(n,t))}function Uh(n,e,t,r={}){const o=ro(n,r);return Lh(oo(e,o),oo(t,o))}function sE(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);return ro(n,r,Oh(n,r.directed===!0))(o,s)}function Fh(n,e={}){return Rh(n,e,ui(n,e))}function iE(n,e,t={}){return oo(e,ui(n,t))}function aE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ui(n,t))}function Bh(n,e,t,r={}){const o=ui(n,r);return Lh(oo(e,o),oo(t,o))}function cE(n){const e=n.nodeCount,t=new Uint32Array(e+1);for(let r=0;r<e;r++){let o=0;const s=n.rowPtr[r+1];for(let i=n.rowPtr[r];i<s;i++)n.colIdx[i]!==r&&o++;t[r+1]=t[r]+o}return t}function lE(n){const e=n.nodeCount,t=cE(n),r=t[e],o=new Uint32Array(r),s=new Float64Array(r),i=new Float64Array(e),a=new Float64Array(e);let c=0;for(let l=0;l<e;l++){let u=0;const d=n.rowPtr[l+1];for(let f=n.rowPtr[l];f<d;f++){const h=n.colIdx[f],g=n.weights===null?1:n.weights[f];h===l?i[l]+=g:(o[c]=h,s[c]=g,c++,u+=g)}a[l]=u+2*i[l]}return{n:e,rowPtr:t,colIdx:o,w:s,loop:i,deg:a}}function zh(n,e,t,r,o){const s=new Float64Array(t),i=new Float64Array(t);for(let c=0;c<n.n;c++){const l=e[c];i[l]+=n.deg[c],s[l]+=2*n.loop[c];const u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++)e[n.colIdx[d]]===l&&(s[l]+=n.w[d])}let a=0;for(let c=0;c<t;c++){const l=i[c]/o;a+=s[c]/o-r*l*l}return a}function uE(n,e,t,r,o){const{n:s}=n,i=new Float64Array(s);for(let b=0;b<s;b++)e[b]=b,i[b]=n.deg[b];const a=new Float64Array(s),c=new Int32Array(s).fill(-1),l=new Uint32Array(s),u=s+1,d=new Uint32Array(u),f=new Uint8Array(s);let h=0,g=s;for(let b=0;b<s;b++)d[b]=b,f[b]=1;let w=0,p=0;const m=o*s;let y=!1;for(;h!==g&&p<m;){const b=d[h];h=h+1===u?0:h+1,f[b]=0,p++;const v=e[b],A=n.deg[b];i[v]-=A,w++;let E=0;const I=n.rowPtr[b+1];for(let C=n.rowPtr[b];C<I;C++){const O=e[n.colIdx[C]];c[O]!==w&&(c[O]=w,a[O]=0,l[E++]=O),a[O]+=n.w[C]}let k=v,N=(c[v]===w?a[v]:0)-t*A*i[v]/r;for(let C=0;C<E;C++){const O=l[C];if(O===v)continue;const T=a[O]-t*A*i[O]/r;T>N&&(N=T,k=O)}if(i[k]+=A,k!==v){e[b]=k,y=!0;for(let C=n.rowPtr[b];C<I;C++){const O=n.colIdx[C];f[O]===0&&e[O]!==k&&(f[O]=1,d[g]=O,g=g+1===u?0:g+1)}}}return y}function dE(n,e,t){const r=new Uint32Array(t+1);for(let i=0;i<n;i++)r[e[i]+1]++;for(let i=0;i<t;i++)r[i+1]+=r[i];const o=new Uint32Array(n),s=r.slice(0,t);for(let i=0;i<n;i++)o[s[e[i]]++]=i;return{start:r,members:o}}function fE(n,e,t,r,o,s){let i=0;for(let a=0;a<e;a++){const c=n[a];r[s+a]=c,o[s+a]=t[c],i+=t[c]}return i}function hE(n,e,t){const{start:r,members:o}=dE(n.n,e,t),s=new Uint32Array(t+1),i=new Uint32Array(n.colIdx.length),a=new Float64Array(n.colIdx.length),c=new Float64Array(t),l=new Float64Array(t),u=new Float64Array(t),d=new Int32Array(t).fill(-1),f=new Uint32Array(t);let h=0;for(let g=0;g<t;g++){s[g]=h;let w=0,p=0;for(let y=r[g];y<r[g+1];y++){const b=o[y];c[g]+=n.loop[b];const v=n.rowPtr[b+1];for(let A=n.rowPtr[b];A<v;A++){const E=e[n.colIdx[A]];if(E===g){w+=n.w[A];continue}d[E]!==g&&(d[E]=g,u[E]=0,f[p++]=E),u[E]+=n.w[A]}}c[g]+=w/2;const m=fE(f,p,u,i,a,h);h+=p,l[g]=m+2*c[g]}return s[t]=h,{n:t,rowPtr:s,colIdx:i.subarray(0,h),w:a.subarray(0,h),loop:c,deg:l}}function Gh(n,e={}){if(n.directed)throw Q(new Error("Louvain requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.nodeCount,i=new Uint32Array(s);for(let f=0;f<s;f++)i[f]=f;let a=lE(n),c=0;for(let f=0;f<s;f++)c+=a.deg[f];if(c===0)return{...We(i,s),modularity:0,iterations:0};let l=zh(a,i,s,t,c),u=0;for(let f=0;f<r;f++){const h=new Uint32Array(a.n);if(!uE(a,h,t,c,r))break;const g=Je(h),{count:w}=g,p=g.labels,m=zh(a,p,w,t,c);for(let b=0;b<s;b++)i[b]=p[i[b]];u=f+1;const y=m-l;if(l=m,y<o||w===a.n)break;a=hE(a,p,w)}const d=Je(i);return{...We(d.labels,d.count),modularity:l,iterations:u}}function Cc(n){for(let e=0;e+1<n.ptr.length;e++){let t=0;for(let r=n.ptr[e];r<n.ptr[e+1];r++)t+=n.val[r];if(t>0)for(let r=n.ptr[e];r<n.ptr[e+1];r++)n.val[r]/=t}}function gE(n,e,t,r){const o=t.length,s=new Uint32Array(o+1),i=[],a=[],c=[];for(let l=0;l<o;l++){c.length=0;for(let u=e.ptr[l];u<e.ptr[l+1];u++){const d=e.row[u],f=e.val[u];for(let h=n.ptr[d];h<n.ptr[d+1];h++){const g=n.row[h];r[g]===0&&(r[g]=1,c.push(g)),t[g]+=n.val[h]*f}}c.sort((u,d)=>u-d);for(const u of c)i.push(u),a.push(t[u]),t[u]=0,r[u]=0;s[l+1]=i.length}return{ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)}}function wE(n,e,t){const r={ptr:n.ptr,row:n.row,val:n.val.map(l=>JA(l,e))};Cc(r);const o=n.ptr.length-1,s=new Uint32Array(o+1),i=[],a=[];for(let l=0;l<o;l++){for(let u=r.ptr[l];u<r.ptr[l+1];u++)r.val[u]>=t&&(i.push(r.row[u]),a.push(r.val[u]));s[l+1]=i.length}const c={ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)};return Cc(c),c}function pE(n,e,t){for(let r=0;r+1<n.ptr.length;r++){let o=n.ptr[r],s=e.ptr[r];const i=n.ptr[r+1],a=e.ptr[r+1];for(;o<i||s<a;){let c;if(s>=a||o<i&&n.row[o]<e.row[s]?c=n.val[o++]:o>=i||e.row[s]<n.row[o]?c=e.val[s++]:c=n.val[o++]-e.val[s++],Math.abs(c)>t)return!1}}return!0}function mE(n,e){const t=n===null?1:n[e];if(!(t>=0)||t===1/0)throw Q(new RangeError(`arc ${e} has weight ${t}; Markov clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");return t}function yE(n,e,t){const r=n.nodeCount,o=new Uint32Array(r+1);for(let h=0;h<n.arcCount;h++)o[n.colIdx[h]+1]++;if(t)for(let h=0;h<r;h++)o[h+1]++;for(let h=0;h<r;h++)o[h+1]+=o[h];const s=o.slice(0,r),i=new Uint32Array(o[r]),a=new Float64Array(o[r]),c=(h,g,w,p)=>{const m=s[g]-1;m>=o[g]&&i[m]===h?a[m]=p?w:a[m]+w:(i[s[g]]=h,a[s[g]++]=w)};for(let h=0;h<r;h++){for(let g=n.rowPtr[h];g<n.rowPtr[h+1];g++){const w=n.colIdx[g];c(h,w,mE(e,g),!1)}t&&c(h,h,1,!0)}const l=new Uint32Array(r+1),u=[],d=[];for(let h=0;h<r;h++){for(let g=o[h];g<s[h];g++)u.push(i[g]),d.push(a[g]);l[h+1]=u.length}const f={ptr:l,row:Uint32Array.from(u),val:Float64Array.from(d)};return Cc(f),f}function bE(n,e={}){const t=e.expansion??2,r=e.inflation??2,o=e.maxIterations??100,s=e.tolerance??1e-6,i=e.pruningThreshold??1e-5;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`expansion must be an integer of at least 1, got ${t}`),"E_BAD_OPTION");if(!(r>0)||r===1/0)throw Q(new RangeError(`inflation must be finite and above 0, got ${r}`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${o}`),"E_BAD_OPTION");if(!(s>=0)||!(i>=0))throw Q(new RangeError("tolerance and pruningThreshold must be non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;let l=yE(n,a,e.selfLoops??!0);const u=new Float64Array(c),d=new Uint8Array(c);let f=c===0,h=0;for(;!f&&h<o;){let b=l;for(let A=1;A<t;A++)b=gE(b,l,u,d);const v=wE(b,r,i);h++,f=pE(l,v,s),l=v}const g=[],w=new Int32Array(c).fill(-1);for(let b=0;b<c;b++){let v=0;for(let A=l.ptr[b];A<l.ptr[b+1];A++)l.row[A]===b&&l.val[A]>0&&g.push(b),l.val[A]>v&&(v=l.val[A],w[b]=l.row[A])}const p=new Uint32Array(c),m=new Map;for(let b=0;b<c;b++){const v=w[b];if(v>=0){let A=m.get(v);A===void 0&&(A=m.size,m.set(v,A)),p[b]=A}}let y=m.size;for(let b=0;b<c;b++)w[b]<0&&(p[b]=y++);return{...We(p,y),attractors:Uint32Array.from(g),iterations:h,converged:f}}function Wh(n,e){return e instanceof Uint32Array?e:Df(n,e)}function Vh(n,e){const t=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n];if(e.left!==void 0&&e.right!==void 0)return{left:Wh(n,e.left),right:Wh(n,e.right),views:t};const{sides:r}=Yf(n,{arcs:e.arcs});if(r===null)throw Q(new Error("Graph is not bipartite"),"E_NOT_BIPARTITE");const o=At(n.nodeCount);for(let i=0;i<o.length;i++)o[i]=~r[i];const s=n.nodeCount%32;return s!==0&&(o[o.length-1]&=(1<<s)-1),{left:o,right:r,views:t}}function vE(n,e,t){const r=new Uint32Array(e+1),o=new Uint32Array(t+1);for(const{rowPtr:u,arcToEdge:d}of n){for(let f=0;f<e;f++)r[f+1]+=u[f+1]-u[f];for(const f of d)o[f+1]++}for(let u=0;u<e;u++)r[u+1]+=r[u];for(let u=0;u<t;u++)o[u+1]+=o[u];const s=r[e],i=new Uint32Array(s),a=new Uint32Array(s);for(const{rowPtr:u,colIdx:d,arcToEdge:f}of n)for(let h=0;h<e;h++)for(let g=u[h];g<u[h+1];g++){const w=o[f[g]]++;i[w]=h,a[w]=d[g]}const c=r.slice(0,e),l=new Uint32Array(s);for(let u=0;u<s;u++)l[c[i[u]]++]=a[u];return{start:r,nbr:l}}function jh(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,{start:i,nbr:a}=vE(o,s,n.edgeCount),c=new Uint32Array(s),l=new Uint8Array(s);let u=0;for(let y=0;y<s;y++){if(l[y]===1)continue;l[y]=1;let b=u;for(c[u++]=y;b<u;){const v=c[b++];for(let A=i[v];A<i[v+1];A++)l[a[A]]===0&&(l[a[A]]=1,c[u++]=a[A])}}const d=new Uint32Array(s).fill(x),f=new Uint32Array(s).fill(x),h=new Uint32Array(s),g=new Uint32Array(s),w=new Uint32Array(s),p=new Uint32Array(s);let m=0;for(let y=0;y<s;y++){const b=c[y];if(!_e(t,b))continue;const v=y+1;let A=0;g[A++]=b,w[b]=i[b];let E=x;e:for(;A>0;){const I=g[A-1];for(;w[I]<i[I+1];){const k=a[w[I]++];if(h[k]===v||!_e(r,k))continue;h[k]=v;const N=f[k];if(N===x){E=k;break e}p[I]=k,g[A++]=N,w[N]=i[N];continue e}A--}if(E!==x){for(let I=A-1;I>=0;I--){const k=g[I],N=I===A-1?E:p[k];d[k]=N,f[N]=k}m++}}return{matching:d,size:m}}function AE(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,i=new Uint32Array(s).fill(x),a=new Uint8Array(s);let c=0;for(let l=0;l<s;l++)if(_e(t,l))e:for(const{rowPtr:u,colIdx:d}of o){const f=u[l+1];for(let h=u[l];h<f;h++){const g=d[h];if(a[g]===0&&_e(r,g)){a[g]=1,i[l]=g,c++;break e}}}return{matching:i,size:c}}function qh(n,e={}){const t=n.nodeCount,r=Ac(n,e.weights);if(t<2){const y=At(t,!0);return{...to(y,t),cutValue:0,side:y,cutEdges:new Uint32Array(0)}}const{src:o,dst:s}=n.edgeList(),i=new Uint32Array(t+1);for(let y=0;y<n.edgeCount;y++)i[o[y]+1]++,i[s[y]+1]++;for(let y=0;y<t;y++)i[y+1]+=i[y];const a=i.slice(0,t),c=new Uint32Array(i[t]),l=new Float64Array(i[t]);for(let y=0;y<n.edgeCount;y++)c[a[o[y]]]=s[y],l[a[o[y]]++]=r[y],c[a[s[y]]]=o[y],l[a[s[y]]++]=r[y];const u=new Uint32Array(t),d=new Uint32Array(t).fill(x),f=new Uint32Array(t);for(let y=0;y<t;y++)u[y]=y,f[y]=y;const h=new Float64Array(t),g=new Uint8Array(t),w=new sh(t);let p=1/0,m=At(t);for(let y=t;y>1;y--){let b=x;for(let E=0;E<t;E++)u[E]===E&&(g[E]=0,h[E]=0,b===x?b=E:w.push(E,0));let v=x,A=b;for(;;){g[A]=1;for(let E=A;E!==x;E=d[E])for(let I=i[E];I<i[E+1];I++){const k=u[c[I]];g[k]===0&&(h[k]+=l[I],w.pushOrIncrease(k,h[k]))}if(w.isEmpty())break;v=A,A=w.pop()}if(h[A]<p){p=h[A],m=At(t);for(let E=A;E!==x;E=d[E])pn(m,E,!0)}for(let E=A;E!==x;E=d[E])u[E]=v;d[f[v]]=A,f[v]=f[A]}return{...to(m,t),cutValue:p,side:m,cutEdges:Ec(n,m,!1,r,!1)}}function Hh(n,e={}){const t=e.iterations??100,r=e.randomSeed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`iterations must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const o=n.nodeCount,s=Ac(n,e.weights);if(o<2){const f=At(o);return{...to(f,o),cutValue:0,side:f,cutEdges:new Uint32Array(0)}}const{src:i,dst:a}=n.edgeList(),c=no(r),l=new Uint32Array(n.edgeCount);let u=1/0,d=At(o);for(let f=0;f<t;f++){for(let m=0;m<l.length;m++)l[m]=m;for(let m=l.length-1;m>0;m--){const y=Math.floor(c()*(m+1)),b=l[m];l[m]=l[y],l[y]=b}const h=new eo(o);let g=o;for(let m=0;m<l.length&&g>2;m++)h.union(i[l[m]],a[l[m]])&&g--;const w=h.find(0);let p=0;for(let m=0;m<n.edgeCount;m++)h.find(i[m])===w!=(h.find(a[m])===w)&&(p+=s[m]);if(p<u){u=p,d=At(o);for(let m=0;m<o;m++)pn(d,m,h.find(m)===w)}}return{...to(d,o),cutValue:u,side:d,cutEdges:Ec(n,d,!1,s,!1)}}function Kh(n,e={}){const t=n.edgeList(),r=n.edgeCount,o=new Float64Array(r);if(e.weights!==void 0)for(let u=0;u<r;u++)o[u]=e.weights[t.arc[u]];else if(t.weights!==null)for(let u=0;u<r;u++)o[u]=t.weights[u];else o.fill(1);const s=new Array(r);for(let u=0;u<r;u++)s[u]=u;s.sort((u,d)=>o[u]-o[d]||u-d);const i=new eo(n.nodeCount),a=new Uint32Array(Math.max(n.nodeCount-1,0));let c=0,l=0;for(const u of s)i.union(t.src[u],t.dst[u])&&(a[c++]=u,l+=o[u]);return{edges:a.subarray(0,c),totalWeight:l}}function Yh(n,e={}){if(n.directed)throw Q(new Error("Prim's algorithm requires an undirected graph"),"E_NEEDS_UNDIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=e.weights??n.weights,i=new Float64Array(t).fill(1/0),a=new Uint32Array(t).fill(x),c=new Uint8Array(t),l=new Yn(t),u=new Uint32Array(Math.max(t-1,0));let d=0,f=0;const h=g=>{for(l.push(g,0);!l.isEmpty();){const w=l.pop();c[w]=1,a[w]!==x&&(u[d++]=n.arcToEdge[a[w]],f+=i[w]);for(let p=r[w];p<r[w+1];p++){const m=o[p],y=s===null?1:s[p];c[m]===0&&y<i[m]&&(i[m]=y,a[m]=p,l.pushOrDecrease(m,y))}}};if(t>0&&h(e.start===void 0?0:xe(n,e.start)),e.forest===!0)for(let g=0;g<t;g++)c[g]===0&&h(g);else if(d<t-1)throw Q(new Error("Graph is not connected"),"E_NOT_CONNECTED");return{edges:u.subarray(0,d),totalWeight:f,predArc:a}}function Xh(n,e={}){return Jh(n,null,e)}function Qh(n,e,t={}){return Jh(n,eg(e,n.nodeCount,"personalization"),t)}function Jh(n,e,t){const r=n.nodeCount,o=t.dampingFactor??.85,s=t.maxIterations??100,i=t.tolerance??1e-6,a=t.convergenceNorm==="max";if(r===0)return{scores:new Float64Array(0),iterations:0,converged:!0};const c=n.reverse(),l=t.weighted===!0&&c.weights!==null,u=l?n.edges.byRole("weight"):null,d=u?.dtype==="f64"?u.data:null;let f=l?c.weights:null,h=l?n.weightedOutDegree():n.outDegree();d!==null&&(f=Zh(d,c.arcToEdge),h=EE(n,Zh(d,n.arcToEdge)));let g=(t.initialRanks===void 0?null:eg(t.initialRanks,r,"initialRanks"))??new Float64Array(r).fill(t.initialRanks===void 0?1/r:0),w=new Float64Array(r),p=0,m=!1;for(;p<s&&!m;p++){let y=0;for(let A=0;A<r;A++)h[A]===0&&(y+=g[A]);const b=1-o+o*y*(e===null?1:1/r);let v=0;for(let A=0;A<r;A++){let E=0;const I=c.rowPtr[A+1];for(let N=c.rowPtr[A];N<I;N++){const C=c.colIdx[N],O=h[C];O>0&&(E+=g[C]*(f===null?1:f[N])/O)}w[A]=b*(e===null?1/r:e[A])+o*E;const k=Math.abs(w[A]-g[A]);v=a?Math.max(v,k):v+k}[g,w]=[w,g],m=v<i}return{scores:g,iterations:p,converged:m}}function Zh(n,e){const t=new Float64Array(e.length);for(let r=0;r<t.length;r++)t[r]=n[e[r]];return t}function EE(n,e){const t=new Float64Array(n.nodeCount);for(let r=0;r<n.nodeCount;r++)for(let o=n.rowPtr[r];o<n.rowPtr[r+1];o++)t[r]+=e[o];return t}function eg(n,e,t){if(n.length!==e)throw Q(new Error(`PageRank: ${t} has ${String(n.length)} entries for ${String(e)} nodes`),"E_BAD_OPTION");let r=0;for(const s of n){if(!Number.isFinite(s)||s<0)throw Q(new Error(`PageRank: ${t} must be finite and non-negative, got ${String(s)}`),"E_BAD_OPTION");r+=s}if(r===0)return null;const o=new Float64Array(e);for(let s=0;s<e;s++)o[s]=n[s]/r;return o}const tg={distance:1/0,path:new Uint32Array(0),edges:new Uint32Array(0)};function _E(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);if(o===s)return{distance:0,path:Uint32Array.of(o),edges:new Uint32Array(0)};const i=n.nodeCount,a=r.weights??n.weights;if(a?.some(C=>C<0)===!0)throw Q(new Error("Bidirectional Dijkstra does not support negative edge weights"),"E_BAD_WEIGHT");const c=n.reverse(),l=C=>a===null?1:a[C],u=new Float64Array(i).fill(1/0),d=new Float64Array(i).fill(1/0),f=new Uint32Array(i).fill(x),h=new Uint32Array(i).fill(x),g=new Uint32Array(i).fill(x),w=new Yn(i),p=new Yn(i);u[o]=0,d[s]=0,w.push(o,0),p.push(s,0);let m=1/0,y=x,b=x,v=x,A=0;for(;w.peekKey()+p.peekKey()<m;)if(w.peekKey()<=p.peekKey()){const C=w.pop();for(let O=n.rowPtr[C];O<n.rowPtr[C+1];O++){const T=n.colIdx[O],$=l(O),L=u[C]+$;L<u[T]&&(u[T]=L,f[T]=O,w.pushOrDecrease(T,L)),L+d[T]<m&&(m=L+d[T],[y,b,v,A]=[C,T,n.arcToEdge[O],$])}}else{const C=p.pop();for(let O=c.rowPtr[C];O<c.rowPtr[C+1];O++){const T=c.colIdx[O],$=l(c.fwdArc[O]),L=d[C]+$;L<d[T]&&(d[T]=L,h[T]=O,g[T]=C,p.pushOrDecrease(T,L)),u[T]+L<m&&(m=u[T]+L,[y,b,v,A]=[T,C,c.arcToEdge[O],$])}}if(y===x)return tg;const E=[],I=[],k=[];for(let C=y;C!==o;C=n.arcSource(f[C]))E.push(C),I.push(n.arcToEdge[f[C]]),k.push(l(f[C]));E.push(o),E.reverse(),I.reverse(),k.reverse(),I.push(v),k.push(A),E.push(b);for(let C=b;C!==s;C=g[C])I.push(c.arcToEdge[h[C]]),k.push(l(c.fwdArc[h[C]])),E.push(g[C]);let N=0;for(const C of k)N+=C;return{distance:N,path:Uint32Array.from(E),edges:Uint32Array.from(I)}}function IE(n,e,t,r,o){const{gScore:s,fScore:i,predArc:a,closed:c,heap:l}=o;for(let u=n.rowPtr[e];u<n.rowPtr[e+1];u++){const d=n.colIdx[u];if(c[d]===1)continue;const f=s[e]+(t===null?1:t[u]);f<s[d]&&(s[d]=f,i[d]=f+r(d),a[d]=u,l.pushOrDecrease(d,i[d]))}}function kE(n,e,t,r,o={}){const s=xe(n,e),i=xe(n,t),a=n.nodeCount;if(!(i>=0&&i<a))throw Q(new RangeError(`Target index ${String(i)} is outside the graph's ${String(a)} nodes`),"E_BAD_NODE");const c=o.weights??n.weights,l=new Float64Array(a).fill(1/0),u=new Float64Array(a).fill(1/0),d=new Uint32Array(a).fill(x),f=new Uint8Array(a),h=[],g=new Yn(a);for(l[s]=0,u[s]=r(s,i),g.push(s,u[s]);!g.isEmpty();){const m=g.pop();if(m===i)break;f[m]=1,h.push(m),IE(n,m,c,y=>r(y,i),{gScore:l,fScore:u,predArc:d,closed:f,heap:g})}const w={gScore:l,fScore:u,visited:Uint32Array.from(h)};if(l[i]===1/0)return{...tg,...w};const p=Jr(n,d,s,i);return{distance:l[i],path:p,edges:Zr(n,d,s,i),...w}}function Nc(n,e={}){const{labels:t,count:r}=SE(n,e);return We(t,r)}function SE(n,e={}){if(!n.directed)throw Q(new Error("Strongly connected components require a directed graph. Use connectedComponents for an undirected one."),"E_NEEDS_DIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=ci(n,e.arcOrder),i=new Uint32Array(t).fill(x),a=new Uint32Array(t),c=new Uint32Array(t),l=new Uint8Array(t),u=new Uint32Array(t),d=new Uint32Array(t),f=new Uint32Array(t),h=new Uint32Array(t);let g=0,w=0,p=0,m=0,y=0;const b=v=>{i[v]=w,a[v]=w,w++,c[v]=r[v],d[m++]=v,l[v]=1,u[y++]=v};for(let v=0;v<t;v++)if(i[v]===x)for(b(v);y>0;){const A=u[y-1];if(c[A]<r[A+1]){const E=c[A]++,I=o[s===null?E:s[E]];i[I]===x?b(I):l[I]===1&&i[I]<a[A]&&(a[A]=i[I]);continue}if(y--,a[A]===i[A]){let E;do E=d[--m],l[E]=0,f[E]=p,h[g++]=E;while(E!==A);p++}y>0&&a[A]<a[u[y-1]]&&(a[u[y-1]]=a[A])}return{labels:f,count:p,popped:h}}function PE(n,e={}){const t=Nc(n,e),r=n.contract(t.labels,{selfLoops:"drop",parallel:"merge",weights:"first"});return{components:t,condensed:r}}const xE=1e-11,ng=3e3;function CE(n,e){const t=n.nodeCount,r=[{view:n,arcOf:l=>l}];if(n.directed){const l=n.reverse();r.push({view:l,arcOf:u=>l.fwdArc[u]})}const o=new Uint32Array(t+1);for(let l=0;l<t;l++){let u=0;for(const{view:d}of r)for(let f=d.rowPtr[l];f<d.rowPtr[l+1];f++)u+=d.colIdx[f]===l?0:1;o[l+1]=o[l]+u}const s=new Uint32Array(o[t]),i=new Float64Array(o[t]),a=new Float64Array(t);let c=0;for(let l=0;l<t;l++)for(const{view:u,arcOf:d}of r)for(let f=u.rowPtr[l];f<u.rowPtr[l+1];f++){const h=e===null?1:e[d(f)];if(!(h>=0)||h===1/0)throw Q(new RangeError(`an arc has weight ${h}; spectral clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");u.colIdx[f]!==l&&(s[c]=u.colIdx[f],i[c++]=h,a[l]+=h)}return{rowPtr:o,colIdx:s,w:i,degree:a}}function rg(n,e){for(let t=0;t<n.length;t++){const r=n[t];for(let o=0;;o++){for(let i=0;i<2;i++)for(let a=0;a<t;a++){const c=n[a];let l=0;for(let u=0;u<r.length;u++)l+=c[u]*r[u];for(let u=0;u<r.length;u++)r[u]-=l*c[u]}let s=0;for(let i=0;i<r.length;i++)s+=r[i]*r[i];if(s=Math.sqrt(s),s>1e-10||o===3){for(let i=0;i<r.length;i++)r[i]=s>0?r[i]/s:0;break}for(let i=0;i<r.length;i++)r[i]=e()-.5}}}function NE(n,e){const t=new Float64Array(e*e);for(let r=0;r<e;r++)t[r*e+r]=1;for(let r=0;r<100;r++){let o=0;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)o+=n[s*e+i]*n[s*e+i];if(o<1e-30)break;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++){const a=n[s*e+i];if(a===0)continue;const c=(n[i*e+i]-n[s*e+s])/(2*a),l=Math.sign(c||1)/(Math.abs(c)+Math.sqrt(c*c+1)),u=1/Math.sqrt(l*l+1),d=l*u;for(let f=0;f<e;f++){const h=n[f*e+s],g=n[f*e+i];n[f*e+s]=u*h-d*g,n[f*e+i]=d*h+u*g}for(let f=0;f<e;f++){const h=n[s*e+f],g=n[i*e+f];n[s*e+f]=u*h-d*g,n[i*e+f]=d*h+u*g}for(let f=0;f<e;f++){const h=t[f*e+s],g=t[f*e+i];t[f*e+s]=u*h-d*g,t[f*e+i]=d*h+u*g}}}return{values:Float64Array.from({length:e},(r,o)=>n[o*e+o]),vectors:t}}function TE(n,e,t){const r=n.length,o=new Float64Array(r*r);for(let s=0;s<r;s++)for(let i=s;i<r;i++){let a=0;for(let c=0;c<t;c++)a+=n[s][c]*e[i][c];o[s*r+i]=a,o[i*r+s]=a}return o}function OE(n,e,t,r,o){const s=Math.min(e,t+Math.max(t,8));let i=Array.from({length:s},()=>Float64Array.from({length:e},()=>o()-.5));rg(i,o);const a=new Float64Array(e),c=w=>(n(w,a),w.map((p,m)=>r*p-a[m]));let l=new Float64Array(s),u=[],d=new Float64Array(s*s),f=!1;for(let w=0;w<ng;w++){const p=i.map(c);if({values:l,vectors:d}=NE(TE(i,p,e),s),u=Array.from({length:s},(y,b)=>b).sort((y,b)=>l[b]-l[y]),f=u.slice(0,t).every(y=>{let b=0;for(let v=0;v<e;v++){let A=0;for(let E=0;E<s;E++)A+=d[E*s+y]*(p[E][v]-l[y]*i[E][v]);b+=A*A}return Math.sqrt(b)<=xE*r}),f||w===ng-1)break;i=p,rg(i,o)}const h=new Float64Array(t),g=[];for(let w=0;w<t;w++){const p=u[w];h[w]=Math.max(0,r-l[p]);const m=new Float64Array(e);for(let y=0;y<s;y++){const b=d[y*s+p];for(let v=0;v<e;v++)m[v]+=b*i[y][v]}g.push(m)}return{values:h,vectors:g,converged:f}}const $E=10;function RE(n,e,t,r,o){const s=new Float64Array(o*r),i=new Float64Array(o);for(let c=0;c<t;c++){i[e[c]]++;for(let l=0;l<r;l++)s[e[c]*r+l]+=n[c*r+l]}let a=0;for(let c=0;c<t;c++){const l=e[c];for(let u=0;u<r;u++){const d=n[c*r+u]-s[l*r+u]/i[l];a+=d*d}}return a}function DE(n,e,t,r,o,s,i){const a=(f,h,g)=>{let w=0;for(let p=0;p<t;p++){const m=n[f*t+p]-h[g*t+p];w+=m*m}return w},c=new Float64Array(r*t),l=new Float64Array(e).fill(1/0);let u=Math.floor(i()*e);for(let f=0;f<r;f++){c.set(n.subarray(u*t,u*t+t),f*t);let h=0;for(let w=0;w<e;w++)l[w]=Math.min(l[w],a(w,c,f)),h+=l[w];let g=i()*h;u=0;for(let w=0;w<e&&h>0;w++)if(g-=l[w],g<0){u=w;break}}const d=new Uint32Array(e);for(let f=0;f<o;f++){let h=f===0;for(let m=0;m<e;m++){let y=0,b=1/0;for(let v=0;v<r;v++){const A=a(m,c,v);A<b&&(b=A,y=v)}h||(h=d[m]!==y),d[m]=y}if(!h)break;const g=new Float64Array(r*t),w=new Float64Array(r);for(let m=0;m<e;m++){w[d[m]]++;for(let y=0;y<t;y++)g[d[m]*t+y]+=n[m*t+y]}let p=0;for(let m=0;m<r;m++){if(w[m]===0)continue;let y=0;for(let b=0;b<t;b++){const v=g[m*t+b]/w[m],A=v-c[m*t+b];y+=A*A,c[m*t+b]=v}p=Math.max(p,Math.sqrt(y))}if(p<s)break}return d}function LE(n,e){const{k:t}=e,r=e.laplacianType??"normalized",o=e.maxIterations??100,s=e.tolerance??1e-4,i=e.seed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`k must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!["unnormalized","normalized","randomWalk"].includes(r))throw Q(new RangeError(`unknown laplacianType "${r}"`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0||!(s>=0)||!Number.isInteger(i))throw Q(new RangeError("maxIterations and seed must be integers, maxIterations and tolerance non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;if(t>=c){const A=Uint32Array.from({length:c},(E,I)=>I);return{...We(A,c),eigenvalues:new Float64Array(0),eigenvectors:[],converged:!0}}const l=CE(n,a),u=l.degree.map(A=>A>0?1/Math.sqrt(A):0),d=r!=="unnormalized",f=(A,E)=>{for(let I=0;I<c;I++){let k=0;for(let N=l.rowPtr[I];N<l.rowPtr[I+1];N++){const C=l.colIdx[N];k+=d?l.w[N]*u[C]*A[C]:l.w[N]*A[C]}d?E[I]=l.degree[I]>0?A[I]-u[I]*k:0:E[I]=l.degree[I]*A[I]-k}};let h=2;if(!d){h=1;for(let A=0;A<c;A++)for(let E=l.rowPtr[A];E<l.rowPtr[A+1];E++)h=Math.max(h,l.degree[A]+l.degree[l.colIdx[E]])}const g=no(i),w=OE(f,c,t,h,g);if(r==="randomWalk")for(const A of w.vectors)for(let E=0;E<c;E++)A[E]*=l.degree[E]>0?u[E]:1;const p=new Float64Array(c*t);for(let A=0;A<t;A++)for(let E=0;E<c;E++)p[E*t+A]=w.vectors[A][E];if(r==="normalized")for(let A=0;A<c;A++){const E=p.subarray(A*t,A*t+t),I=YA(...E);I>0&&E.forEach((k,N)=>E[N]=k/I)}let m=new Uint32Array(c),y=1/0;for(let A=0;A<$E;A++){const E=DE(p,c,t,t,o,s,g),I=RE(p,E,c,t,t);I<y&&(y=I,m=E)}const{labels:b,count:v}=Je(m);return{...We(b,v),eigenvalues:w.values,eigenvectors:w.vectors,converged:w.converged}}const ME=10;function di(n,e,t,r,o){let s=0;for(let i=0;i<o;i++){const a=n[e*o+i]-t[r*o+i];s+=a*a}return Math.sqrt(s)}function UE(n,e,t){const r=n.nodeCount,o=new Float64Array(r*t),s=n.directed?n.degree():n.outDegree();for(let i=0;i<r;i++){const a=s[i]/Math.max(1,r-1);for(let c=0;c<t;c++)o[i*t+c]=(e()-.5)*.1+a*.1}return o}function FE(n,e){let t=1/0;for(let r=0;r<n.centreCount;r++)t=Math.min(t,di(n.emb,e,n.centres,r,n.dim));return t}function BE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n;for(let a=0;a<r;a++)if(t-=e[a],t<=0){i.set(s.subarray(a*o,(a+1)*o),n.centreCount*o),n.centreCount++;return}}function zE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n,a=Math.floor(t()*r);i.set(s.subarray(a*o,(a+1)*o),0),n.centreCount=1;const c=new Float64Array(r);for(let l=1;l<e;l++){let u=0;for(let d=0;d<r;d++){const f=FE(n,d);c[d]=f*f,u+=f*f}BE(n,c,t()*u)}}function og(n){const{n:e,dim:t,emb:r,centres:o,centreCount:s,labels:i}=n;for(let a=0;a<e;a++){let c=0,l=1/0;for(let u=0;u<s;u++){const d=di(r,a,o,u,t);d<l&&(l=d,c=u)}i[a]=c}}function GE(n,e,t,r){const{n:o,dim:s,rowPtr:i,colIdx:a,emb:c}=n;e.fill(0);for(let l=0;l<o;l++){const u=l*s;for(let d=i[l];d<i[l+1];d++){const f=a[d]*s;for(let h=0;h<s;h++)e[u+h]+=t*(c[u+h]-c[f+h])}}for(let l=0;l<o;l++){const u=i[l+1]-i[l],d=t===0||u===0?0:r/(t*u);for(let f=l*s;f<(l+1)*s;f++)c[f]-=d*e[f]}}function WE(n,e,t){const{n:r,dim:o,emb:s,centres:i,centreCount:a,labels:c}=n;e.fill(0),t.fill(0);for(let l=0;l<r;l++){const u=c[l];for(let d=0;d<o;d++)e[u*o+d]+=s[l*o+d];t[u]++}for(let l=0;l<a;l++)if(t[l]>0)for(let u=0;u<o;u++)i[l*o+u]=e[l*o+u]/t[l]}function VE(n,e){const{n:t,dim:r,rowPtr:o,colIdx:s,emb:i,centres:a,labels:c}=n;let l=0,u=0,d=0;for(let f=0;f<t;f++){const h=di(i,f,a,c[f],r);l+=h*h}for(let f=0;f<t;f++)for(let h=o[f];h<o[f+1];h++){const g=di(i,f,i,s[h],r);u+=g*g}for(const f of i)d+=f*f;return l+e*u+e*d}function jE(n,e){return n.every((t,r)=>t===e[r])}function qE(n,e){const{numClusters:t,maxIterations:r=1e3,tolerance:o=1e-6,seed:s=42,learningRate:i=.5,lambda:a=.1}=e,c=n.nodeCount;if(c===0)return{...We(new Uint32Array(0),t),embeddings:new Float64Array(0),dimensions:0,loss:0,previousLoss:1/0,iterations:0,converged:!0};if(!Number.isInteger(t)||t<=0||t>c)throw Q(new Error(`Invalid number of clusters: ${String(t)}. Must be between 1 and ${String(c)}`),"E_BAD_OPTION");const l=no(s),u=Math.min(64,c),d={n:c,dim:u,rowPtr:n.rowPtr,colIdx:n.colIdx,emb:UE(n,l,u),centres:new Float64Array(t*u),centreCount:0,labels:new Uint32Array(c)};zE(d,t,l);const f=new Float64Array(c*u),h=new Float64Array(t*u),g=new Uint32Array(t);let w=1/0,p=1/0,m=0,y=!1;const b=new Uint32Array(c);let v=0;for(;m<r;)if(m++,og(d),v=m>1&&jE(d.labels,b)?v+1:0,b.set(d.labels),GE(d,f,a,i),WE(d,h,g),m>1&&(w=p),p=VE(d,a),Math.abs(w-p)<o||v>=ME){y=!0;break}return og(d),{...We(d.labels,t),embeddings:d.emb,dimensions:u,loss:p,previousLoss:w,iterations:m,converged:y}}const HE=100;function KE(n,e,t){const r=n.nodeCount;if(!e){for(let s=0;s<r;s++)for(let i=s+1;i<r;i++)t[s*r+i]=t[i*r+s]=n.hasArc(s,i)?1:2;return}t.fill(1/0);const o=new Uint32Array(r);for(let s=0;s<r;s++)YE(n,s,t,o)}function YE(n,e,t,r){const o=e*n.nodeCount;t[o+e]=0,r[0]=e;let s=0,i=1;for(;s<i;){const a=r[s++],c=t[o+a]+1;for(let l=n.rowPtr[a];l<n.rowPtr[a+1];l++){const u=n.colIdx[l];t[o+u]===1/0&&(t[o+u]=c,r[i++]=u)}}}function XE(n,e={}){const{linkage:t="average",numClusters:r,distanceThreshold:o,useGraphDistance:s=!0}=e;if(r!==void 0&&(r<1||!Number.isInteger(r)))throw Q(new Error("numClusters must be a positive integer"),"E_BAD_OPTION");const i=n.nodeCount;if(i===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const a=Lf("teraHAC",i,e.maxNodes,8*i*i,()=>new Float64Array(i*i));if(KE(n,s,a),t==="ward")for(let D=0;D<a.length;D++)a[D]*=a[D];const l={single:Math.min,complete:Math.max,average:null,ward:null}[t],u=Math.max(0,i-1),d=new Uint32Array(u),f=new Uint32Array(u),h=new Float64Array(u),g=new Uint32Array(u),w=new Uint32Array(i),p=new Uint32Array(i).fill(1),m=new Uint8Array(i).fill(1);for(let D=0;D<i;D++)w[D]=D;const y=(D,U)=>{const B=w[D],V=w[U];return B<i&&V<i?B<V:B>V},b=(D,U)=>{const[B,V]=y(D,U)?[D,U]:[U,D];let W=a[B*i+V];return w[B]<i&&w[V]<i?W=t==="ward"?Math.sqrt(W):W:l||(W/=p[B]*p[V]),W===1/0?HE:W},v=(D,U)=>{const B=w[D],V=w[U],W=Math.min(B,V),q=Math.max(B,V);return q<i?W*i+q:i*i+q*2*i+W},A=new Int32Array(i).fill(-1),E=new Float64Array(i),I=new Float64Array(i),k=(D,U)=>{const B=b(D,U),V=v(D,U);(A[D]===-1||B<E[D]||B===E[D]&&V<I[D])&&(A[D]=U,E[D]=B,I[D]=V)},N=D=>{A[D]=-1;for(let U=0;U<i;U++)m[U]&&U!==D&&k(D,U)};for(let D=0;D<i;D++)N(D);let C=i,O=0;for(;C>1&&(r===void 0||C>r);){let D=-1;for(let W=0;W<i;W++)m[W]&&(D===-1||E[W]<E[D]||E[W]===E[D]&&I[W]<I[D])&&(D=W);const U=E[D];if(o!==void 0&&U>o)break;const[B,V]=y(D,A[D])?[D,A[D]]:[A[D],D];d[O]=w[B],f[O]=w[V],h[O]=U,g[O]=p[B]+p[V];for(let W=0;W<i;W++)if(m[W]&&W!==B&&W!==V){const q=B*i+W,K=V*i+W,X=W*i+B,H=W*i+V;a[q]=l?l(a[q],a[K]):a[q]+a[K],a[X]=l?l(a[X],a[H]):a[X]+a[H]}w[B]=i+O,p[B]=g[O],m[V]=0,O++,C--,N(B);for(let W=0;W<i;W++)m[W]&&W!==B&&(A[W]===B||A[W]===V?N(W):k(W,B))}const T=Array.from(w.filter((D,U)=>m[U]===1)).sort((D,U)=>D-U);let $=T[0];const L=D=>D<i?1:g[D-i];for(let D=1;D<T.length;D++){const U=O+D-1;d[U]=$,f[U]=T[D],h[U]=1/0,g[U]=L($)+L(T[D]),$=i+U}const F=QE(i,d,f,$,r??C),{labels:M,count:R}=Je(F);return{...We(M,R),left:d,right:f,distance:h,size:g,merges:O,root:$}}function QE(n,e,t,r,o){const s=[],i=[r];let a=0;for(;a<i.length&&s.length<o;){const l=i[a++];l<n||o===1||s.length+(i.length-a)+1>=o?s.push(l):i.push(e[l-n],t[l-n])}const c=new Uint32Array(n);return s.forEach((l,u)=>{const d=[l];for(;d.length>0;){const f=d.pop()??0;f<n?c[f]=u:d.push(e[f-n],t[f-n])}}),c}function JE(n,e,t){let r=e;for(let o=e;o<t;o++)(o===e||n[o]!==n[o-1])&&(n[r++]=n[o]);return r}function sg(n){const e=n.nodeCount,t=n.directed?[n,n.reverse()]:[n],r=new Uint32Array(e+1),o=new Uint32Array(t.reduce((i,a)=>i+a.colIdx.length,0));let s=0;for(let i=0;i<e;i++){r[i]=s;const a=s;for(const l of t)for(let u=l.rowPtr[i];u<l.rowPtr[i+1];u++)l.colIdx[u]!==i&&(o[s++]=l.colIdx[u]);const c=o.subarray(a,s);t.length>1&&c.sort(),s=JE(o,a,s)}return r[e]=s,{rowPtr:r,colIdx:o.slice(0,s)}}function ig(n,e,t){const r=n.length,o=new Float64Array(r);let s=0;for(let i=0;i<r;i++){const a=t[i+1]-t[i],c=a*(a-1)/2;s+=c,o[i]=c>0?n[i]/c:0}return{coefficient:o,transitivity:s>0?3*e/s:0}}function ZE(n,e,t,r,o){let s=0,i=e[t],a=e[r];const c=e[t+1],l=e[r+1];for(;i<c&&a<l;)n[i]<n[a]?i++:(n[i]>n[a]||(o[t]++,o[r]++,o[n[i]]++,s++,i++),a++);return s}function ag(n){const e=n.nodeCount,{rowPtr:t,colIdx:r}=sg(n),o=(u,d)=>{const f=t[u+1]-t[u],h=t[d+1]-t[d];return h>f||h===f&&d>u},s=new Uint32Array(e+1),i=new Uint32Array(r.length/2);let a=0;for(let u=0;u<e;u++){s[u]=a;for(let d=t[u];d<t[u+1];d++)o(u,r[d])&&(i[a++]=r[d])}s[e]=a;const c=new Uint32Array(e);let l=0;for(let u=0;u<e;u++){const d=s[u+1];for(let f=s[u];f<d;f++)l+=ZE(i,s,u,i[f],c)}return{perNode:c,total:l,...ig(c,l,t)}}function $t(n){return new Promise(e=>{e(n())})}function cg(n,e){if(n.sigmaOverflow===!0)throw new ZA(e);return n}function lg(n,e){return{normalized:e?.normalized,sources:is(n,e?.sources,e?.k)}}function e_(n,e,t){const r=t?.sources!==void 0||t?.k!==void 0,o=t?.harmonic===!0;return(!r||!e.directed)&&(!o||n.harmonicCloseness===!0&&!r)&&t?.normalized!==!0&&t?.cutoff===void 0&&t?.weights===void 0}function t_(n,e){const t=e?.weighted===!0;return e?.sources===void 0&&e?.k===void 0?e?.harmonic===!0?{weighted:t,harmonic:!0}:{weighted:t}:{weighted:t,sources:is(n,e.sources,e.k,"closenessCentrality")}}function n_(n,e){return e?.weights===void 0&&(e?.method??"auto")==="auto"&&e?.maxNodes===void 0&&e?.paths!==!0&&e?.weighted!==!1&&n.nodeCount<=zf&&n.flags.nonNegativeWeights&&n.flags.finiteWeights}function ug(n){return n?.initialRanks!==void 0||n?.convergenceNorm==="max"}function dg(n){return{dampingFactor:n?.dampingFactor,maxIterations:n?.maxIterations,tolerance:n?.tolerance,weighted:n?.weighted===!0}}function r_(n,e,t){const r=t?.weighted===!0&&n.weights!==null?n.weightedOutDegree():n.outDegree();return ug(t)||!e.some(o=>o>0)||r.includes(0)}function o_(n,e){return e?.startVector===void 0&&!n.directed&&!n.flags.multigraph&&!s_(n)}function s_(n){const e=n.nodeCount,t=new Int8Array(e).fill(-1),r=new Uint32Array(e);for(let o=0;o<e;o++){if(t[o]!==-1||n.rowPtr[o]===n.rowPtr[o+1])continue;t[o]=0;let s=0;r[s++]=o;let i=!1;for(let a=0;a<s;a++){const c=r[a];for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];t[u]===-1?(t[u]=1-t[c],r[s++]=u):t[u]===t[c]&&(i=!0)}}if(!i)return!0}return!1}function i_(n,e){if(!n.converged)throw new Mf("eigenvectorCentrality",e?.maxIterations??100,e?.tolerance??1e-6);if(e?.normalized===!1)return n;const t=Float64Array.from(n.scores);return dh(t),{scores:t,iterations:n.iterations,converged:!0}}function a_(n,e){if(e?.normalized===!1||e?.alpha===0)return!1;const t=n.reverse(),r=e?.weighted===!0?t.weights:null,o=new Float64Array(n.nodeCount);let s,i=!1;for(let l=0;l<n.nodeCount;l++){let u=0;for(let d=t.rowPtr[l];d<t.rowPtr[l+1];d++)u+=r===null?1:r[d],o[l]+=r===null?1:Math.abs(r[d]);s??(s=u),i||(i=u!==s)}if(!i)return!1;let a=0;for(let l=0;l<n.nodeCount;l++)for(let u=t.rowPtr[l];u<t.rowPtr[l+1];u++)a=Math.max(a,o[l]*o[t.colIdx[u]]);const c=e?.alpha??.1;return c*c*a<1}function c_(n){let e=1/0,t=-1/0;for(const o of n)e=Math.min(e,o),t=Math.max(t,o);const r=t-e;if(r>0)for(let o=0;o<n.length;o++)n[o]=(n[o]-e)/r}function l_(n){const e=Float64Array.from(n.scores);return c_(e),{scores:e,iterations:n.iterations,converged:n.converged}}function fg(n,e){let t=0;for(const r of n)t=e==="l2"?t+r*r:Math.max(t,r);if(t=e==="l2"?Math.sqrt(t):t,t>0)for(let r=0;r<n.length;r++)n[r]/=t}function u_(n,e){const t=e?.normalized===!1?"max":"l2",r=Float64Array.from(n.hubs),o=Float64Array.from(n.authorities);return fg(r,t),fg(o,t),{hubs:r,authorities:o,iterations:n.iterations,converged:n.converged}}function hg(n,e,t){const{predArc:r}=t;return{dist:t.dist,predArc:r,pathTo:o=>Jr(n,r,e,o),pathEdges:o=>Zr(n,r,e,o)}}function d_(n,e){const{perNode:t,total:r,coefficient:o,transitivity:s}=e;return o!==void 0&&s!==void 0?{perNode:t,total:r,coefficient:o,transitivity:s}:{perNode:t,total:r,...ig(t,r,sg(n).rowPtr)}}function f_(n){return{accelerator:n??null,pageRank:(e,t)=>n?.pageRank!==void 0&&!ug(t)?n.pageRank(e,dg(t)):Promise.resolve(Xh(e,t)),personalizedPageRank:(e,t,r)=>n?.personalizedPageRank!==void 0&&!r_(e,t,r)?n.personalizedPageRank(e,t,dg(r)):Promise.resolve(Qh(e,t,r)),eigenvectorCentrality:(e,t)=>n?.eigenvectorCentrality!==void 0&&o_(e,t)?n.eigenvectorCentrality(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:!1}).then(r=>i_(r,t)):new Promise(r=>{r(uh(e,t))}),sssp:(e,t,r)=>{const o=xe(e,t);return n?.sssp!==void 0?n.sssp(e,o,r).then(s=>hg(e,o,s)):Promise.resolve(Bf(e,o,r))},bellmanFord:(e,t,r)=>{const o=xe(e,t);return n?.bellmanFord!==void 0&&(r?.weights===void 0||r.weights instanceof Float32Array)?n.bellmanFord(e,o,r).then(s=>({...hg(e,o,s),hasNegativeCycle:s.hasNegativeCycle})):Promise.resolve(Wf(e,o,r))},breadthFirstSearch:(e,t,r)=>{const o=xe(e,t);return n?.breadthFirstSearch!==void 0&&r?.target===void 0&&r?.arcOrder===void 0?n.breadthFirstSearch(e,o,r):Promise.resolve(Kf(e,o,r))},connectedComponents:e=>n?.connectedComponents!==void 0?n.connectedComponents(e):Promise.resolve(th(e)),weaklyConnectedComponents:e=>n?.weaklyConnectedComponents!==void 0?n.weaklyConnectedComponents(e):Promise.resolve(nh(e)),minimumSpanningTree:(e,t)=>n?.minimumSpanningTree!==void 0&&t?.weights===void 0?n.minimumSpanningTree(e):Promise.resolve(Kh(e,t)),kCoreDecomposition:e=>n?.kCoreDecomposition!==void 0?n.kCoreDecomposition(e):Promise.resolve(kh(e)),katzCentrality:(e,t)=>n?.katzCentrality!==void 0&&a_(e,t)?n.katzCentrality(e,{alpha:t?.alpha,beta:t?.beta,maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(l_):Promise.resolve(Sh(e,t)),hits:(e,t)=>n?.hits!==void 0?n.hits(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(r=>u_(r,t)):Promise.resolve(Ah(e,t)),louvain:(e,t)=>n?.louvain!==void 0?n.louvain(e,t):Promise.resolve(Gh(e,t)),allPairsShortestPath:(e,t)=>n?.allPairsShortestPath!==void 0&&n_(e,t)?n.allPairsShortestPath(e).then(({dist:r,n:o})=>({dist:r,n:o,hasNegativeCycle:!1})):Promise.resolve(Gf(e,t)),betweennessCentrality:(e,t)=>n?.betweennessCentrality!==void 0&&!e.flags.multigraph&&t?.endpoints!==!0?n.betweennessCentrality(e,lg(e,t)).then(r=>cg(r,"betweennessCentrality")):Promise.resolve(qf(e,t)),edgeBetweennessCentrality:(e,t)=>n?.edgeBetweennessCentrality!==void 0&&!e.flags.multigraph&&t?.alive===void 0?n.edgeBetweennessCentrality(e,lg(e,t)).then(r=>cg(r,"edgeBetweennessCentrality")):Promise.resolve(dc(e,t)),closenessCentrality:(e,t)=>n?.closenessCentrality!==void 0&&e_(n,e,t)?n.closenessCentrality(e,t_(e,t)):Promise.resolve(Jf(e,t)),labelPropagation:(e,t)=>n?.labelPropagation!==void 0&&t?.randomSeed===void 0?n.labelPropagation(e,t):Promise.resolve(ph(e,t)),labelPropagationSynchronous:(e,t)=>n?.labelPropagation!==void 0?n.labelPropagation(e,{maxIterations:t?.maxIterations,weighted:t?.weighted}):Promise.resolve(mh(e,t)),triangleCount:e=>n?.triangleCount!==void 0?n.triangleCount(e).then(t=>d_(e,t)):Promise.resolve(ag(e)),depthFirstSearch:(e,t,r)=>$t(()=>lh(e,t,r)),degrees:e=>$t(()=>oh(e)),stronglyConnectedComponents:(e,t)=>$t(()=>Nc(e,t)),leiden:(e,t)=>$t(()=>Ch(e,t)),girvanNewman:(e,t)=>$t(()=>yh(e,t)),maxFlow:(e,t,r,o)=>$t(()=>_c(e,t,r,o)),minSTCut:(e,t,r,o)=>$t(()=>hh(e,t,r,o)),stoerWagner:(e,t)=>$t(()=>qh(e,t)),kargerMinCut:(e,t)=>$t(()=>Hh(e,t)),commonNeighborsPrediction:(e,t)=>$t(()=>Mh(e,t)),adamicAdarPrediction:(e,t)=>$t(()=>Fh(e,t)),primMST:(e,t)=>$t(()=>Yh(e,t)),maximumBipartiteMatching:(e,t)=>$t(()=>jh(e,t))}}const h_={graphtyAStar:["directed","goal","gpu","heuristic","root","weight"],graphtyAdamicAdarForPairs:["directed","gpu","pairs"],graphtyAdamicAdarPrediction:["directed","gpu","includeExisting","topK"],graphtyAdamicAdarScore:["directed","gpu","source","target"],graphtyAllPairsShortestPath:["directed","gpu","maxNodes","method","paths","weight"],graphtyBellmanFord:["cutoff","directed","field","gpu","root","weight"],graphtyBetweennessCentrality:["directed","endpoints","field","gpu","k","normalized","sources"],graphtyBidirectionalDijkstra:["directed","goal","gpu","root","weight"],graphtyBreadthFirstSearch:["directed","field","goal","gpu","maxDepth","root"],graphtyClosenessCentrality:["cutoff","directed","field","gpu","harmonic","k","normalized","sources","weight"],graphtyCommonNeighborsForPairs:["directed","gpu","pairs"],graphtyCommonNeighborsPrediction:["directed","gpu","includeExisting","topK"],graphtyCommonNeighborsScore:["directed","gpu","source","target"],graphtyCompareAdamicAdarWithCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyCondensation:["directed","field","gpu"],graphtyConnectedComponents:["directed","field","gpu"],graphtyDegreeCentrality:["directed","field","gpu","mode","normalized"],graphtyDegrees:["directed","gpu"],graphtyDeltaPageRank:["dampingFactor","deltaThreshold","directed","field","gpu","maxIterations","personalization","priority","tolerance","weight"],graphtyDepthFirstSearch:["directed","field","goal","gpu","order","root"],graphtyDijkstra:["cutoff","directed","field","gpu","root","weight"],graphtyDirectionOptimizedBfs:["alpha","beta","directed","field","gpu","root"],graphtyEdgeBetweennessCentrality:["directed","field","gpu","k","normalized","sources"],graphtyEigenvectorCentrality:["directed","field","gpu","maxIterations","mode","normalized","startVector","tolerance"],graphtyEvaluateAdamicAdar:["directed","edges","gpu","nonEdges"],graphtyEvaluateCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyFindAllIsomorphisms:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyGirvanNewman:["directed","field","gpu","maxCommunities","maxIterations","minCommunitySize","weight"],graphtyGreedyBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyGrsbm:["directed","field","gpu","maxDepth","maxIterations","minClusterSize","seed","tolerance","weight"],graphtyHasCycle:["directed","gpu"],graphtyHierarchicalClustering:["directed","gpu","linkage","maxNodes"],graphtyHits:["directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyIsBipartite:["arcs","directed","field","gpu"],graphtyIsGraphIsomorphic:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyKCoreDecomposition:["directed","field","gpu"],graphtyKargerMinCut:["directed","field","gpu","iterations","randomSeed","weight"],graphtyKatzCentrality:["alpha","beta","directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyKruskalMST:["directed","gpu","weight"],graphtyLabelPropagation:["directed","field","gpu","maxIterations","randomSeed","weight"],graphtyLabelPropagationSemiSupervised:["directed","field","gpu","maxIterations","randomSeed","seeds","weight"],graphtyLabelPropagationSynchronous:["directed","field","gpu","maxIterations","weight"],graphtyLeiden:["directed","field","gpu","maxIterations","randomSeed","resolution","threshold","weight"],graphtyLouvain:["directed","field","gpu","maxIterations","resolution","tolerance","weight"],graphtyMarkovClustering:["directed","expansion","field","gpu","inflation","maxIterations","pruningThreshold","selfLoops","tolerance","weight"],graphtyMaxFlow:["algorithm","directed","field","gpu","sink","source","weight"],graphtyMaximumBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyMinSTCut:["algorithm","directed","field","gpu","sink","source","weight"],graphtyModularity:["clusters","directed","gpu","resolution","weight"],graphtyNodeClosenessCentrality:["cutoff","directed","gpu","harmonic","normalized","root","weight"],graphtyPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","tolerance","weight"],graphtyPersonalizedPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","personalization","tolerance","weight"],graphtyPrimMST:["directed","forest","gpu","root","weight"],graphtySpectralClustering:["directed","field","gpu","k","laplacianType","maxIterations","seed","tolerance","weight"],graphtyStoerWagner:["directed","field","gpu","weight"],graphtyStronglyConnectedComponents:["directed","field","gpu"],graphtySyncClustering:["directed","field","gpu","lambda","learningRate","maxIterations","numClusters","seed","tolerance"],graphtyTeraHAC:["directed","distanceThreshold","field","gpu","linkage","maxNodes","numClusters","useGraphDistance"],graphtyTopAdamicAdarCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopologicalSort:["directed","gpu"],graphtyTriangleCount:["directed","field","gpu"],graphtyWeaklyConnectedComponents:["directed","field","gpu"]},g_={ak:["k"],"balanced-tree":["branching","height","seed","weights"],"barabasi-albert":["m","n","seed","triadProbability","weights"],barbell:["cliqueSize","pathLength","seed","weights"],"bianconi-barabasi":["fitness","m","n","seed","weights"],"bipartite-configuration-model":["leftDegrees","multiEdges","rightDegrees","seed","weights"],caveman:["cliques","seed","size","weights"],"chung-lu":["expectedDegrees","seed","weights"],"circular-ladder":["n","seed","weights"],complete:["n","seed","weights"],"complete-bipartite":["a","b","seed","weights"],"complete-multipartite":["seed","sizes","weights"],"configuration-model":["degrees","multiEdges","seed","selfLoops","weights"],"connected-caveman":["cliques","seed","size","weights"],cycle:["n","seed","weights"],"degree-corrected-sbm":["expectedDegrees","mixing","seed","sizes","weights"],"directed-configuration-model":["inDegrees","multiEdges","outDegrees","seed","selfLoops","weights"],"duplication-divergence":["n","retention","seed","weights"],empty:["n","seed","weights"],"erdos-renyi":["directed","n","p","seed","weights"],"erdos-renyi-gnm":["m","n","seed","weights"],"forest-fire":["backward","forward","maxBurn","n","seed","weights"],genrmf:["a","b","c1","c2","seed"],grid:["cols","diagonals","directed","obstacles","periodic","positions","rows","seed","weights"],"grid-3d":["cols","diagonals","directed","layers","obstacles","periodic","positions","rows","seed","weights"],"grid-flow-network":["cols","maxCapacity","minCapacity","rows","seed"],"hexagonal-lattice":["cols","positions","rows","seed","weights"],hyperbolic:["averageDegree","exponent","n","seed","temperature","weights"],hypercube:["dimension","seed","weights"],knn:["clusters","dimension","directed","k","n","seed","spread","weights"],kronecker:["directed","edges","initiator","multiEdges","permute","power","seed","selfLoops","weights"],ladder:["n","seed","weights"],"layered-flow-network":["layers","maxCapacity","minCapacity","p","seed"],lfr:["communityExponent","degreeExponent","maxCommunity","maxDegree","minCommunity","minDegree","mixing","n","seed","weights"],lollipop:["cliqueSize","pathLength","seed","weights"],"mobius-ladder":["n","seed","weights"],named:["name","seed","weights"],"newman-watts":["k","n","p","seed","weights"],path:["n","seed","weights"],petersen:["seed","weights"],"planted-partition":["groupSize","groups","pIn","pOut","seed","weights"],price:["attractiveness","citations","n","seed","weights"],"random-apollonian":["n","seed","weights"],"random-bipartite":["n1","n2","p","perfectMatching","seed","weights"],"random-dag":["layers","p","seed","weights"],"random-geometric":["dimension","n","periodic","radius","seed","weights"],"random-order-dag":["n","p","seed","weights"],"random-recursive-tree":["n","seed","weights"],"random-regular":["d","n","seed","weights"],"random-tree":["n","seed","weights"],"ring-of-cliques":["cliques","seed","size","weights"],rmat:["a","b","c","d","directed","edgeFactor","multiEdges","permute","scale","seed","selfLoops","weights"],star:["n","seed","weights"],"stochastic-block-model":["probabilities","seed","sizes","weights"],"triangular-lattice":["cols","positions","rows","seed","weights"],"watts-strogatz":["beta","k","n","seed","weights"],waxman:["alpha","beta","n","seed","weights"],wheel:["n","seed","weights"],"wilson-maze":["cols","rows","seed","weights"]},gg=5e3;function as(n,e){const t=setTimeout(()=>{console.warn(`graphty: ${e} has waited ${String(gg/1e3)} s for part of @graphty/cytoscape-extensions to load. If a module awaits ${e} at its top level, a Vite 6 or 7 production build never loads it: call it inside an async function, or with .then(), instead. On a slow network the call carries on.`)},gg),r=()=>{clearTimeout(t)};return n.then(r,r),n}const wg=new WeakMap,so=new Map,Tc=new Map;function fi(n){return n.cy()}function pg(n){let e=wg.get(n);if(e===void 0){const t={version:0,entries:[],dropListeners:new Set};n.on("add remove data move",()=>{t.version++,mg(t,t.entries),t.entries=[]}),wg.set(n,t),e=t}return e}function mg(n,e){const t=[];for(const{value:r}of e)so.has(r.snapshot)?Tc.set(r.snapshot,n):t.push(r.snapshot);yg(n,t)}function yg(n,e){if(e.length>0)for(const t of n.dropListeners)t(e)}function bg(n){so.set(n,(so.get(n)??0)+1);let e=!0;return()=>{if(!e)return;e=!1;const t=(so.get(n)??1)-1;if(t>0){so.set(n,t);return}so.delete(n);const r=Tc.get(n);r!==void 0&&(Tc.delete(n),yg(r,[n]))}}function w_(n,e){const t=pg(n);return t.dropListeners.add(e),()=>{t.dropListeners.delete(e)}}function hi(n,e={}){const t=e.directed??!1,r=n;if(typeof e.weight=="function")return vg(r,t,e.weight);const o=`${String(t)}|${e.weight??""}`,s=pg(fi(n)),i=s.entries.find(c=>c.key===o&&c.version===s.version&&p_(c.eles,r));if(i!==void 0)return i.value;const a=vg(r,t,e.weight);return mg(s,s.entries.filter(c=>c.key===o)),s.entries=[...s.entries.filter(c=>c.key!==o),{key:o,eles:r,version:s.version,value:a}],a}function p_(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function vg(n,e,t){const r=n.nodes(),o=[],s=new Map;r.forEach((d,f)=>{o.push(d.id()),s.set(d.id(),f)});const i=n.edges().filter(d=>s.has(d.source().id())&&s.has(d.target().id())),a=new Uint32Array(i.length),c=new Uint32Array(i.length),l=t===void 0?void 0:new Float64Array(i.length);return i.forEach((d,f)=>{if(a[f]=s.get(d.source().id())??0,c[f]=s.get(d.target().id())??0,l!==void 0&&t!==void 0){const h=typeof t=="function"?t(d):d.data(t);l[f]=typeof h=="number"&&Number.isFinite(h)?h:1}}),{snapshot:sc({directed:e,ids:o,src:a,dst:c,weights:l}),nodes:r,edges:i}}function io(n,e,t){fi(n).batch(()=>{n.forEach((r,o)=>{r.data(t,e[o])})})}function Gt(n,e){return(typeof e=="string"?n.nodes.filter(e):n.nodes.intersection(e)).map(r=>n.snapshot.ids.requireIndex(r.id()))}function ao(n,e,t){if(e===void 0)return;const[r]=Gt(n,e);if(r===void 0)throw new Error(`${t} matches no node of the collection`);return r}class Oc extends Error{constructor(e,t,r=null){super(t),this.name="GpuUnavailableError",this.code=e,this.fix=r}}function cs(){return Object.assign(new Error("graphty: the Cytoscape core was destroyed"),{code:"E_CORE_DESTROYED"})}const m_=["auto","off","require"];function $c(n,e){if(e!==void 0&&!m_.includes(e)){const r=e===null||typeof e=="number"||typeof e=="boolean"?String(e):`a value of type ${typeof e}`,o=typeof e=="string"?JSON.stringify(e):r;throw new TypeError(`${n}: gpu must be "auto", "off" or "require"; got ${o}`)}}const Ag=5e3;let Eg={},y_,Pr=null,Xn=null,Rc=!1;const _g=new WeakMap;function b_(n={}){Eg={...n},Pr=null,Xn=null,Rc=!1}function Ig(){const n=globalThis.navigator;return n?.gpu!==void 0&&n.gpu!==null?null:globalThis.process?.versions?.node===void 0?"this runtime has no WebGPU (navigator.gpu is undefined)":null}function v_(){if(Pr===null){const n=Ig();if(n!==null)Xn={reason:n??"WebGPU was disabled",fix:null},Pr=Promise.resolve(Xn);else{const e=as(Promise.resolve().then(()=>jO),"an ...Async method or a simulation layout").then(t=>t.gpuProvider(Eg),t=>({reason:`@graphty/webgpu-graph-algorithms did not load: ${Sg(t)}`,fix:"check that @graphty/webgpu-graph-algorithms is installed and that your bundler serves its chunk"}));Pr=e,e.then(t=>{Pr===e&&(Xn=t)})}}return Pr}function kg(n){return"acquire"in n}function Sg(n){return n instanceof Error?n.message:String(n)}function Pg(n){n?.then(e=>e.gpu?.accelerator.dispose(),()=>{})}function A_(n){let e=_g.get(n);if(e===void 0){const t={decision:null,by:null,destroyed:!1};n.one("destroy",()=>{t.destroyed=!0,Pg(t.decision),t.decision=null}),_g.set(n,t),e=t}return e}async function E_(n,e,t){let r;try{r=await t.acquire()}catch(i){const a=i instanceof Oc?i.fix:null;return{gpu:null,reason:`no usable WebGPU device: ${Sg(i)}`,fix:a}}if(e.destroyed)return r.accelerator.dispose(),{gpu:null,reason:"the core was destroyed"};const o=w_(n,i=>{for(const a of i)r.accelerator.release(a)}),s=e.decision;return r.lost.then(()=>{o(),e.decision===s&&(e.decision=null)}),{gpu:r,reason:null}}function xg(n="auto"){if(n==="off")return{gpu:null,reason:'gpu: "off" was requested',fix:null};if(Pr===null&&y_===void 0){const e=Ig();if(e!==null)return{gpu:null,reason:e,fix:null}}return Xn===null||kg(Xn)?null:{gpu:null,...Xn}}async function Cg(n,e="auto"){let t=xg(e);if(t===null){const r=A_(n),o=v_(),s=Xn??await o;if(!kg(s))t={gpu:null,...s};else{if(r.destroyed)throw cs();(r.decision===null||r.by!==s)&&(Pg(r.decision),r.decision=Promise.resolve().then(()=>E_(n,r,s)),r.by=s),t=await r.decision}}if(e==="require"&&t.gpu===null)throw new Error(`graphty: gpu: "require" but ${t.reason??"no device"}`);return t}function Dc(n,e){Rc||n.gpu!==null||n.fix===void 0||n.fix===null||e<Ag||(Rc=!0,console.warn(`graphty: a ${e.toLocaleString("en-US")}-node graph ran on the CPU because ${n.reason??"no GPU"}. To use the GPU: ${n.fix}. Pass gpu: "off" to run on the CPU without this warning.`))}function __(n){let e=!1;return{accelerator:new Proxy(n,{get(r,o,s){const i=Reflect.get(r,o,s);return typeof i!="function"||o==="release"||o==="dispose"?i:(...a)=>(e=!0,i.apply(r,a))}}),used:()=>e}}function Lc(n,e,t){return n.gpu===null?{ran:"cpu",reason:n.reason,device:null}:e?{ran:"gpu",reason:null,device:n.gpu.device}:{ran:"cpu",reason:t,device:n.gpu.device}}const I_={breadthFirstSearch:Kf,sssp:Bf,bellmanFord:Wf,allPairsShortestPath:Gf,pageRank:Xh,personalizedPageRank:Qh,eigenvectorCentrality:uh,katzCentrality:Sh,hits:Ah,closenessCentrality:Jf,betweennessCentrality:qf,edgeBetweennessCentrality:dc,connectedComponents:th,weaklyConnectedComponents:nh,triangleCount:ag,labelPropagation:ph,labelPropagationSynchronous:mh};function ct(n,e){return n instanceof Promise?n.then(e):e(n)}const k_=new Set(["gpu","directed","weight","field","root","goal","target","source","sink","heuristic","personalization","seeds","left","right","clusters","pairs","edges","nonEdges","nodeMatch","edgeMatch","priority","candidates","sources","alive","startVector","initialRanks"]),S_=new Set(["breadthFirstSearch","directionOptimizedBfs","depthFirstSearch","hasCycle","topologicalSort","degreeCentrality","degrees","eigenvectorCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","stronglyConnectedComponents","condensation","kCoreDecomposition","triangleCount","isBipartite","isGraphIsomorphic","findAllIsomorphisms","hierarchicalClustering","teraHAC","syncClustering","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),P_=new Set(["hasCycle","topologicalSort","bidirectionalDijkstra","aStar","allPairsShortestPath","degrees","nodeClosenessCentrality","isGraphIsomorphic","findAllIsomorphisms","modularity","hierarchicalClustering","kruskalMST","primMST","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),gi={maxIterations:100,tolerance:1e-6},Mc={...gi,dampingFactor:.85},x_={pageRank:Mc,personalizedPageRank:Mc,deltaPageRank:Mc,eigenvectorCentrality:gi,hits:gi,katzCentrality:{...gi,alpha:.1,beta:1},labelPropagation:{maxIterations:100},labelPropagationSynchronous:{maxIterations:100},labelPropagationSemiSupervised:{maxIterations:100},allPairsShortestPath:{paths:!0},maxFlow:{algorithm:"edmonds-karp"},minSTCut:{algorithm:"ford-fulkerson"}},Ng=new Set(["topologicalSort","stronglyConnectedComponents","condensation","deltaPageRank"]);function ls(n,e){return n.cy.collection(e)}function Uc(n){if(n.s.weights?.some(e=>e<0)===!0)throw Object.assign(new Error(`${n.name}: a weight is negative; use graphtyBellmanFord`),{code:"E_BAD_WEIGHT"})}function Be(n,e,t){const r=ao(n.cs,e,`${n.name}: ${t}`);if(r===void 0)throw new Error(`${n.name}: the ${t} option is required`);return r}function bn(n,e,t=!1){const r=t?n.cs.edges:n.cs.nodes,s=(typeof e=="string"?r.filter(e):e)[0];if(s===void 0)return;if(!t){const a=n.s.ids.indexOf(s.id());return a===x?void 0:a}const i=n.cs.edges.toArray().indexOf(s);return i<0?void 0:i}function Et(n,e,t=!1){return r=>{const o=bn(n,r,t);return o===void 0?void 0:e[o]}}function us(n,e){return ls(n,Array.from(e,t=>n.cs.nodes[t]))}function Fc(n,e){return ls(n,Array.from(e,t=>n.cs.edges[t]))}function wi(n,e,t){const r=[];for(let o=0;o<e.length;o++)o>0&&r.push(n.cs.edges[t[o-1]]),r.push(n.cs.nodes[e[o]]);return ls(n,r)}function Qn(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);return{sources:e.map(r=>Be(n,r[0],t)),targets:e.map(r=>Be(n,r[1],t))}}function pi(n,e){if(e===void 0)return;const t=At(n.s.nodeCount);for(const r of Gt(n.cs,e))pn(t,r,!0);return t}function Zt(n,e,t,r=!1){return n.field!==void 0&&io(r?n.cs.edges:n.cs.nodes,e,n.field),{score:Et(n,e,r),...t}}function lt(n,e,t){const r=[];for(let s=0;s<e.length;s++){const i=e[s];if(i!==x){const a=r[i]??[];a.push(s),r[i]=a}}n.field!==void 0&&io(n.cs.nodes,e,n.field);const o=Array.from(r,s=>us(n,s??[]));return Object.assign(o,t,{cluster:s=>{const i=bn(n,s);return i===void 0||e[i]===x?void 0:e[i]}})}function Bc(n,e,t){const r=[];for(let s=0;s<e.visitedCount;s++){const i=e.order[s],a=e.parent[i];if(a!==x){const c=n.cs.nodes[a],l=n.cs.nodes[i],d=(n.s.directed?c.edgesTo(l):c.edgesWith(l)).intersection(n.cs.edges)[0];d!==void 0&&r.push(d)}r.push(n.cs.nodes[i])}const o=t!==void 0&&e.depth[t]!==x;return n.field!==void 0&&io(n.cs.nodes,Array.from(e.depth,s=>s===x?Number.NaN:s),n.field),{path:ls(n,r),found:ls(n,o?[n.cs.nodes[t]]:[]),depth:s=>{const i=bn(n,s);return i===void 0||e.depth[i]===x?void 0:e.depth[i]},parent:s=>{const i=bn(n,s);return i===void 0||e.parent[i]===x?void 0:n.cs.nodes[e.parent[i]]}}}function Tg(n,e){return n.field!==void 0&&io(n.cs.nodes,e.dist,n.field),{distanceTo:t=>{const r=bn(n,t);return r===void 0?1/0:e.dist[r]},pathTo:t=>{const r=bn(n,t);return r===void 0?n.cy.collection():wi(n,e.pathTo(r),e.pathEdges(r))}}}function zc(n,e,t,r){const o=[],s=[];for(let i=0;i<n.s.nodeCount;i++)(_e(e,i)?o:s).push(i);return n.field!==void 0&&io(n.cs.nodes,Array.from({length:n.s.nodeCount},(i,a)=>_e(e,a)?0:1),n.field),{value:r,cut:Fc(n,t),partitionFirst:us(n,o),partitionSecond:us(n,s)}}function Gc(n,e){return zc(n,e.side,e.cutEdges,e.cutValue)}function mi(n,e){return Array.from(e.scores,(t,r)=>({source:n.cs.nodes[e.sources[r]],target:n.cs.nodes[e.targets[r]],score:t}))}function Og(n,e,t){return r=>{const o=bn(n,r);return o===void 0?void 0:e.nodes[t[o]]}}function $g(n,e,t){const{nodeMatch:r,edgeMatch:o}=t;return{...n.rest,nodeMatch:r&&((s,i)=>r(n.cs.nodes[s],e.nodes[i])),edgeMatch:o&&((s,i)=>o(n.cs.edges[s],e.edges[i]))}}function Rg(n,e){const t=e.other;if(t===void 0)throw new Error(`${n.name}: the other option (the collection to compare with) is required`);let r=t;if(typeof t=="string"?r=n.cy.$(t):Array.isArray(t)&&(r=n.cy.collection(t)),typeof r?.nodes!="function")throw new TypeError(`${n.name}: the other option must be a Cytoscape collection, a selector or an array of elements`);return hi(r,{directed:n.s.directed})}function yi(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);if(typeof e=="function")return Float64Array.from(n.cs.nodes.toArray(),o=>e(o));const r=new Float64Array(n.s.nodeCount);for(const o of Gt(n.cs,e))r[o]=1;return r}function Dg(n,e){const t=yi(n,e,"personalization");if(!t.some(r=>r>0))throw new Error(`${n.name}: personalization ${typeof e=="function"?"gives no node a positive weight":"matches no node"}`);return t}function Lg(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);const r=new Uint32Array(n.s.nodeCount).fill(x);if(typeof e=="string"){const o=new Map;n.cs.nodes.forEach((s,i)=>{const a=s.data(e);a!==void 0&&(r[i]=o.get(a)??o.set(a,o.size).size-1)})}else e.forEach((o,s)=>{for(const i of Gt(n.cs,o))r[i]=s});if(r.every(o=>o===x))throw new Error(typeof e=="string"?`${n.name}: ${t} names the data field "${e}", which no node has`:`${n.name}: ${t} matches no node`);return r}function C_(n,e){const t=(r,o)=>{const s=bn(n,r),i=bn(n,o);return s===void 0||i===void 0?void 0:[s,i]};return{hasNegativeWeightCycle:e.hasNegativeCycle,distance:(r,o)=>{const s=t(r,o);return s===void 0?1/0:e.dist[s[0]*e.n+s[1]]},path:(r,o)=>{const{pathTo:s,pathEdges:i}=e;if(s===void 0||i===void 0)throw new Error("allPairsShortestPath: pass paths: true to walk shortest paths");const a=t(r,o);return a===void 0?n.cy.collection():wi(n,s(a[0],a[1]),i(a[0],a[1]))}}}function Mg(n,e){return Zt(n,e.scores,{rank:Et(n,e.scores),iterations:e.iterations,converged:e.converged})}function Ug(n,e){return lt(n,e.labels,{iterations:e.iterations,converged:e.converged})}function Fg(n){return n.topK!==void 0&&n.topK<=0?1/0:n.topK}function Bg(n,e){const t=new Uint32Array(n.s.nodeCount).fill(x);return e.matching.forEach((r,o)=>{r!==x&&(t[o]=r,t[r]=o)}),{size:e.size,mate:r=>{const o=bn(n,r);return o===void 0||t[o]===x?void 0:n.cs.nodes[t[o]]}}}function N_(n){let e=0;for(let t=1;t<n.length;t++)n[t]>n[e]&&(e=t);return e}const Wc={breadthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);return ct(n.call("breadthFirstSearch",n.s,Be(n,e.root,"root"),{...n.rest,target:t}),r=>Bc(n,r,t))},directionOptimizedBfs:(n,e)=>Bc(n,l3(n.s,Be(n,e.root,"root"),n.rest),void 0),depthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);if(t!==void 0&&e.order==="post")throw new Error(`${n.name}: goal stops only a pre-order walk; leave it out with order "post"`);return Bc(n,lh(n.s,Be(n,e.root,"root"),{...n.rest,target:t}),t)},hasCycle:(n,e={})=>b3(n.s),topologicalSort:(n,e={})=>{const t=E3(n.s);return t===null?null:us(n,t)},dijkstra:(n,e)=>(Uc(n),ct(n.call("sssp",n.s,Be(n,e.root,"root"),n.rest),t=>Tg(n,t))),bellmanFord:(n,e)=>ct(n.call("bellmanFord",n.s,Be(n,e.root,"root"),n.rest),t=>({...Tg(n,t),hasNegativeWeightCycle:t.hasNegativeCycle})),bidirectionalDijkstra:(n,e)=>{Uc(n);const t=_E(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),n.rest);return{found:t.path.length>0,distance:t.distance,path:wi(n,t.path,t.edges)}},aStar:(n,e)=>{const t=e.heuristic;Uc(n);const r=kE(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),t===void 0?()=>0:o=>t(n.cs.nodes[o]),n.rest);return{found:r.path.length>0,distance:r.distance,path:wi(n,r.path,r.edges)}},allPairsShortestPath:(n,e={})=>ct(n.call("allPairsShortestPath",n.s,n.rest),t=>C_(n,t)),degreeCentrality:(n,e={})=>{const t=f3(n.s,n.rest);return Zt(n,t,{degree:Et(n,t)})},degrees:(n,e={})=>{const t=oh(n.s);if(!n.s.directed){const r=Float64Array.from(t.inDegree,(o,s)=>o+t.outDegree[s]);return{indegree:Et(n,r),outdegree:Et(n,r)}}return{indegree:Et(n,t.inDegree),outdegree:Et(n,t.outDegree)}},pageRank:(n,e={})=>{const t=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("pageRank",n.s,{...n.rest,initialRanks:t,weighted:n.weighted}),r=>Mg(n,r))},personalizedPageRank:(n,e)=>{const t=Dg(n,e.personalization),r=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("personalizedPageRank",n.s,t,{...n.rest,initialRanks:r,weighted:n.weighted}),o=>Mg(n,o))},deltaPageRank:(n,e={})=>{const t=e.personalization===void 0?void 0:Dg(n,e.personalization),r=e.priority===!0&&e.maxIterations===void 0?{maxIterations:1/0}:{},o={...n.rest,...r,personalization:t,weighted:n.weighted},s=e.priority===!0?new p3(n.s).computeWithPriority(o):new w3(n.s).compute(o);if(s.some(i=>!Number.isFinite(i)))throw new RangeError(`${n.name}: the ranks overflowed (maxIterations ${String(n.rest.maxIterations)} is too high for this graph); lower maxIterations, or pass priority: true`);return Zt(n,s,{rank:Et(n,s)})},eigenvectorCentrality:(n,e={})=>{const t=e.startVector&&yi(n,e.startVector,"startVector");return ct(n.call("eigenvectorCentrality",n.s,{...n.rest,startVector:t}),r=>Zt(n,r.scores,{iterations:r.iterations,converged:r.converged}))},katzCentrality:(n,e={})=>ct(n.call("katzCentrality",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.scores,{iterations:t.iterations,converged:t.converged})),hits:(n,e={})=>ct(n.call("hits",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.authorities,{hub:Et(n,t.hubs),authority:Et(n,t.authorities),iterations:t.iterations,converged:t.converged})),closenessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("closenessCentrality",n.s,{...n.rest,sources:t,weighted:n.weighted}),r=>Zt(n,r.scores,{closeness:Et(n,r.scores)}))},nodeClosenessCentrality:(n,e)=>u3(n.s,Be(n,e.root,"root"),{...n.rest,weighted:n.weighted}),betweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("betweennessCentrality",n.s,{...n.rest,sources:t}),r=>{const o=n.s.nodeCount,s=e.endpoints===!0?o*(o-1):(o-1)*(o-2),i=n.s.directed?1:2,a=e.normalized===!0&&s>0?s:i,c=Float64Array.from(r.scores,u=>u*a),l=c.reduce((u,d)=>Math.max(u,d),0);return Zt(n,r.scores,{betweenness:Et(n,c),betweennessNormalized:Et(n,c.map(u=>l===0?0:u/l))})})},edgeBetweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("edgeBetweennessCentrality",n.s,{...n.rest,sources:t}),r=>Zt(n,r.scores,{},!0))},connectedComponents:(n,e={})=>ct(n.call("connectedComponents",n.s),t=>lt(n,t.labels,{})),weaklyConnectedComponents:(n,e={})=>ct(n.call("weaklyConnectedComponents",n.s),t=>lt(n,t.labels,{})),stronglyConnectedComponents:(n,e={})=>lt(n,Nc(n.s).labels,{}),condensation:(n,e={})=>{const t=PE(n.s);return lt(n,t.components.labels,{condensed:t.condensed})},kCoreDecomposition:(n,e={})=>{const t=kh(n.s),r=o=>us(n,Array.from(t.coreness.keys()).filter(s=>t.coreness[s]>=o));return Zt(n,t.coreness,{maxCore:t.maxCore,core:r})},triangleCount:(n,e={})=>ct(n.call("triangleCount",n.s),t=>Zt(n,t.perNode,{coefficient:Et(n,t.coefficient),total:t.total,transitivity:t.transitivity})),isBipartite:(n,e={})=>{const t=Yf(n.s,n.rest);if(t.sides===null){const s=n.cy.collection();return{bipartite:!1,partitionFirst:s,partitionSecond:s}}const{partitionFirst:r,partitionSecond:o}=zc(n,t.sides,[],0);return{bipartite:!0,partitionFirst:r,partitionSecond:o}},isGraphIsomorphic:(n,e)=>{const t=Rg(n,e),r=H3(n.s,t.snapshot,$g(n,t,e)),o=r.mapping;return{isomorphic:r.isomorphic,mapping:o===null?()=>{}:Og(n,t,o)}},findAllIsomorphisms:(n,e)=>{const t=Rg(n,e);return K3(n.s,t.snapshot,$g(n,t,e)).map(r=>Og(n,t,r))},modularity:(n,e)=>xc(n.s,Lg(n,e.clusters,"clusters"),n.rest),louvain:(n,e={})=>{const t=Gh(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},leiden:(n,e={})=>{const t=Ch(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},labelPropagation:(n,e={})=>ct(n.call("labelPropagation",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSynchronous:(n,e={})=>ct(n.call("labelPropagationSynchronous",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSemiSupervised:(n,e)=>{const t=$3(n.s,Lg(n,e.seeds,"seeds"),{...n.rest,weighted:n.weighted});return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},girvanNewman:(n,e={})=>{const t=yh(n.s,n.rest),r={...n,field:void 0},o=i=>lt(r,t.levels[i]??[],{}),s=N_(t.modularity);return lt(n,t.levels[s]??[],{modularity:t.modularity[s]??Number.NaN,levels:t.levels.length,level:o,modularities:Array.from(t.modularity)})},markovClustering:(n,e={})=>{const t=bE(n.s,n.rest);return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},spectralClustering:(n,e)=>{if(e.k===void 0)throw new Error(`${n.name}: the k option is required`);const t=LE(n.s,n.rest);return lt(n,t.labels,{converged:t.converged,eigenvalues:t.eigenvalues})},hierarchicalClustering:(n,e={})=>{const t=V3(n.s,n.rest),r={...n,field:void 0},o=i=>{const a=new Uint32Array(n.s.nodeCount).fill(x);return t.cut(i).forEach((c,l)=>{for(const u of c)a[u]=l}),lt(r,a,{})},s=i=>lt(r,t.cutAt(i).labels,{});return{merges:t.left.length,cut:o,cutAt:s}},teraHAC:(n,e={})=>{const t=XE(n.s,n.rest);return lt(n,t.labels,{merges:t.merges})},grsbm:(n,e={})=>lt(n,B3(n.s,{...n.rest,weighted:n.weighted}).labels,{}),syncClustering:(n,e)=>{if(e.numClusters===void 0)throw new Error(`${n.name}: the numClusters option is required`);const t=qE(n.s,n.rest);return lt(n,t.labels,{loss:t.loss,iterations:t.iterations,converged:t.converged})},kruskalMST:(n,e={})=>{const t=Kh(n.s);return Object.assign(n.cs.nodes.union(Fc(n,t.edges)),{totalWeight:t.totalWeight})},primMST:(n,e={})=>{const t=ao(n.cs,e.root,`${n.name}: root`),r=Yh(n.s,{...n.rest,start:t});return Object.assign(n.cs.nodes.union(Fc(n,r.edges)),{totalWeight:r.totalWeight})},maxFlow:(n,e)=>{const t=_c(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest);return{...zc(n,t.sourceSide,t.cutEdges,t.maxFlow),flow:Et(n,t.flow,!0)}},minSTCut:(n,e)=>Gc(n,hh(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest)),stoerWagner:(n,e={})=>Gc(n,qh(n.s)),kargerMinCut:(n,e={})=>Gc(n,Hh(n.s,n.rest)),maximumBipartiteMatching:(n,e={})=>Bg(n,jh(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),greedyBipartiteMatching:(n,e={})=>Bg(n,AE(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),commonNeighborsScore:(n,e)=>d3(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),adamicAdarScore:(n,e)=>sE(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),commonNeighborsPrediction:(n,e={})=>mi(n,Mh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),adamicAdarPrediction:(n,e={})=>mi(n,Fh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),commonNeighborsForPairs:(n,e)=>Array.from(rE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),adamicAdarForPairs:(n,e)=>Array.from(iE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),topCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,oE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},topAdamicAdarCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,aE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},evaluateCommonNeighbors:(n,e)=>Uh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),evaluateAdamicAdar:(n,e)=>Bh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),compareAdamicAdarWithCommonNeighbors:(n,e)=>{const t=Qn(n,e.edges,"edges"),r=Qn(n,e.nonEdges,"nonEdges"),o={directed:n.s.directed};return{adamicAdar:Bh(n.s,t,r,o),commonNeighbors:Uh(n.s,t,r,o)}}};function $n(n){return`graphty${n.charAt(0).toUpperCase()}${n.slice(1)}`}const T_=Object.keys(Wc).map($n),Vc=["breadthFirstSearch","dijkstra","bellmanFord","allPairsShortestPath","pageRank","personalizedPageRank","eigenvectorCentrality","katzCentrality","hits","closenessCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","triangleCount","labelPropagation","labelPropagationSynchronous"],O_=Vc.map(n=>`${$n(n)}Async`);function zg(n,e,t,r){const o=$n(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${o}: takes one options object; pass a weight function as { weight: fn }`);if(t.weight!==void 0&&S_.has(e))throw new Error(`${o}: this algorithm reads no edge weights; remove the weight option`);if(t.field!==void 0&&P_.has(e))throw new Error(`${o}: this algorithm has no per-element value to write; remove the field option`);const s=h_[o]??[];for(const[h,g]of Object.entries(t))if(g!==void 0&&!s.includes(h))throw new Error(`${o}: unknown option ${h}; the options are ${s.join(", ")}`);const i=t.directed??Ng.has(e),{mode:a}=t;if((a==="in"||a==="out")&&!i)throw new Error(`${o}: mode: "${a}" needs directed: true`);const c=hi(n,{directed:i,weight:t.weight}),l={...x_[e],...Object.fromEntries(Object.entries(t).filter(([h,g])=>!k_.has(h)&&g!==void 0))},u={name:o,cy:fi(n),cs:c,s:c.snapshot,field:t.field,weighted:t.weight!==void 0,rest:l,call:(h,...g)=>r[h](...g)},d=h=>{throw $_(h,e)};let f;try{f=Wc[e](u,t)}catch(h){d(h)}return{result:f instanceof Promise?f.catch(d):f,snapshot:c.snapshot}}function $_(n,e){if(!(n instanceof Error))return n;const t=$n(e),{code:r}=n;if(r==="E_NEEDS_UNDIRECTED"){const o=e==="connectedComponents"?", or call graphtyWeaklyConnectedComponents":"";n.message=`${t}: needs an undirected graph; leave out directed: true${o}`}else r==="E_NEEDS_DIRECTED"?n.message=`${t}: needs a directed graph; ${Ng.has(e)?"leave out directed: false":"pass directed: true"}`:n.message.startsWith(`${t}:`)||(n.message=`${t}: ${n.message}`);return n}function Gg(n,e,t={}){if($c($n(e),t?.gpu),t.gpu==="require"){const r=$n(e);throw new Error(Vc.includes(e)?`${r}: runs on the CPU; call ${r}Async for the GPU`:`${r}: has no GPU implementation and runs only on the CPU; leave out gpu: "require"`)}return zg(n,e,t,I_).result}async function Wg(n,e,t={}){$c(`${$n(e)}Async`,t?.gpu);const r=fi(n),o=await Cg(r,t.gpu);if(r.destroyed())throw cs();const s=o.gpu===null?null:__(o.gpu.accelerator);Dc(o,n.nodes().length);const{result:i,snapshot:a}=zg(n,e,t,f_(s?.accelerator??null)),c=bg(a);let l;try{l=await i}catch(d){throw r.destroyed()?cs():d}finally{c(),o.gpu!==null&&typeof t.weight=="function"&&o.gpu.accelerator.release(a)}const u=Lc(o,s?.used()??!1,"the options or the graph need the CPU implementation");return Object.assign(l,{backend:u})}function R_(n){for(const e of Object.keys(Wc)){const t=$n(e);n("collection",t,function(r){return Gg(this,e,r)}),n("core",t,function(r){return Gg(this.elements(),e,r)})}for(const e of Vc){const t=`${$n(e)}Async`;n("collection",t,function(r){return Wg(this,e,r)}),n("core",t,function(r){return Wg(this.elements(),e,r)})}}class D_ extends Error{constructor(e){super(`graphty: the core already has an element with id "${e}", so the new graph would merge into it; remove the existing elements (cy.elements().remove()) or add the graph to an empty core`),this.code="E_ID_TAKEN",this.name="IdTakenError",this.id=e}}function jc(n,e){if(n.destroyed())throw cs();for(const t of e)if(t.group==="nodes"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty())throw new D_(t.data.id);for(const t of e)t.group==="edges"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty()&&delete t.data.id;return n.add(e)}function L_(n){const e=new Set(n.elements("[graphty_import]").map(r=>String(r.data("graphty_import"))));let t=e.size+1;for(;e.has(String(t));)t++;return String(t)}function M_(n,e,t){let r=0;e.forEach((o,s)=>{const i=n[r];if(i?.id()!==o.data.id)return;r++;const a=t[s];a!=null&&i.style(a)})}function U_(n){n("core","graphtyGenerate",async function(t,r){const{generateElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyGenerate"),s=o(t,r);return{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyDataset",async function(t,r){const{datasetElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyDataset"),s=await o(t,r);return r?.signal?.throwIfAborted(),{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyImport",async function(t,r,o){const{importElements:s}=await as(vu("io.js"),"graphtyImport"),i=o?.styles!==void 0&&o.styles!==!1,a=await s(t,r,{...o,...i&&o.importId===void 0?{importId:L_(this)}:{}}),c=o?.applyStyles===!0&&a.stylesheet!==void 0,l=jc(this,a.elements);c&&a.bypass!==void 0&&M_(l,a.elements,a.bypass);const u=this.style();if(c&&a.stylesheet!==void 0&&u!==void 0){let d=u;for(const f of a.stylesheet)d=d.selector(f.selector).style(f.style);d.update()}return{elements:l,directed:a.directed,format:a.format,report:a.report,...a.stylesheet===void 0?{}:{stylesheet:a.stylesheet}}});const e=async(t,r,o)=>{const{exportElements:s}=await as(vu("io.js"),"graphtyExport");return s(t,r,o)};n("core","graphtyExport",function(t,r){return e(this.elements(),t,r)}),n("collection","graphtyExport",function(t,r){return e(this,t,r)})}function F_(n,e,t,r){const{positions:o,dim:s,n:i}=n,a=new Float32Array(3*i),c=[0,0,0];for(let l=0;l<i;l++)for(let u=0;u<3;u++)a[3*l+u]=u<s?o[s*l+u]*e+c[u]:c[u];return a}function B_(n,e,t){const r=new Float64Array(t),o=new Float64Array(t);for(let s=0;s<e*t;s++){const i=n[s];Number.isNaN(i)||(r[s%t]+=i,o[s%t]++)}for(let s=0;s<t;s++)r[s]=o[s]>0?r[s]/o[s]:0;return r}function z_(n,e,t,r){let o=0;for(let s=0;s<e;s++){let i=0;for(let a=0;a<t;a++){const c=n[t*s+a]-r[a];Number.isNaN(c)||(i+=c*c)}o=Math.max(o,Math.sqrt(i))}return o}function Jn(n,e,t=1,r){const o=Math.floor(n.length/e),s=B_(n,o,e),i=z_(n,o,e,s),a=i>0?t/i:0;for(let c=0;c<o*e;c++){const l=n[c],u=r?.[c%e]??0;Number.isNaN(l)||(n[c]=a===0?u:(l-s[c%e])*a+u)}return n}const qc=34359738337,G_=185852,W_=1;let Vg=class{constructor(e){this.seed=e===null||e===0||Number.isNaN(e)?Math.floor(Math.random()*1e6):e,this.state=this.seed%qc}next(){return this.state=(G_*this.state+W_)%qc,this.state/qc}};function V_(n){const e=[0,0,0];if(n===null)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function bi(n,e,t,r,o,s,i){const a=n.nodeCount;if(r!==2&&r!==3)throw new RangeError(`dim must be 2 or 3, got ${String(r)}`);if(e.length!==3*a)throw new RangeError(`positions has ${e.length} entries, expected ${3*a}`);if(!Number.isFinite(o)||o<=0)throw new RangeError(`scale must be a finite number > 0, got ${o}`);const c=V_(s),l=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];let d=0,f=0;for(let y=0;y<a;y++){let b=!0;for(let v=0;v<r;v++){const A=e[3*y+v];Number.isFinite(A)?(A<l[v]&&(l[v]=A),A>u[v]&&(u[v]=A)):b=!1}b?d++:f++}if(f===0)return;const h=i==="fr"?0:-1,g=1,w=[h,h,h],p=[g,g,g];if(d>0){for(let y=0;y<r;y++)if(Number.isFinite(l[y])&&Number.isFinite(u[y])&&(w[y]=(l[y]-c[y])/o,p[y]=(u[y]-c[y])/o,w[y]===p[y])){const b=(g-h)/2;w[y]-=b,p[y]+=b}}const m=new Vg(t);for(let y=0;y<a;y++){let b=!1;for(let v=0;v<r;v++)Number.isFinite(e[3*y+v])||(b=!0);if(b){for(let v=0;v<r;v++){const A=3*y+v;if(!Number.isFinite(e[A])){const E=m.next(),I=w[v]+E*(p[v]-w[v]);e[A]=I*o+c[v]}}r===2&&(e[3*y+2]=c[2])}}}const jg=new WeakMap;function j_(n){if(n!=null)return typeof n=="number"?n:typeof n=="string"?Number(n):Number.NaN}function co(n,e=null){if(vv(n)){if(!n.directed)return n;const r=jg.get(n);if(r!==void 0)return r;const o=n.toUndirected().snapshot;return jg.set(n,o),o}const t=new oi({directed:!1,weighted:"auto"});if(Array.isArray(n))t.addNodes(n);else{t.addNodes(n.nodes());for(const[r,o]of n.edges()){const s=e!==null&&n.getEdgeData!==void 0?n.getEdgeData(r,o,e):void 0;t.addEdge(r,o,j_(s))}}return t.freeze()}function ze(n,e,t){return Object.assign(n,{code:e,params:t})}function en(n,e){const t=e.dim??2;if(t!==2&&t!==3)throw ze(new Error(`dim must be 2 or 3, got ${String(t)}`),"E_BAD_OPTION",{option:"dim",value:t});const r=Array.from({length:t},(o,s)=>e.center?.[s]??0);return{n:n.nodeCount,dim:t,scale:e.scale??1,center:r}}function Wt(n,e,t){return{positions:Float32Array.from(n),dim:e,n:t}}function Rn(n,e,t){if(e===2)return n;const r=n.length/2,o=new Float64Array(3*r);for(let s=0;s<r;s++)o[3*s]=n[2*s],o[3*s+1]=n[2*s+1],o[3*s+2]=Number.isNaN(n[2*s])?Number.NaN:t[2];return o}function qg(n){const e=n??2;if(e!==2&&e!==3)throw ze(new RangeError(`dim must be 2 or 3, got ${String(e)}`),"E_BAD_OPTION",{option:"dim",value:e});return e}function q_(n,e,t){const r=n.nodeCount;if(e==null)return new Float32Array(3*r).fill(Number.NaN);if(e.length!==t*r)throw ze(new RangeError(`pos has ${e.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:e.length,expected:t*r});return F_({positions:e,dim:t,n:r},1)}function H_(n,e={}){const{scaling:t=1,a:r=1.1,maxIter:o=1e3}=e;if(r<=1)throw ze(new Error("The parameter a should be larger than 1"),"E_BAD_OPTION",{option:"a",value:r});const s=co(n),i=qg(e.dim),a=s.nodeCount,c=Float64Array.from(q_(s,e.pos,i));bi(s,c,e.seed??null,i,1,null,"fr");const l=new Float64Array(i*a);for(let b=0;b<a;b++)for(let v=0;v<i;v++)l[i*b+v]=c[3*b+v];const{rowPtr:u,colIdx:d}=s,f=t*Math.sqrt(a),h=.001,g=1e-6,w=new Float64Array(i*a),p=new Float64Array(i),m=new Int32Array(a);let y=g+1;for(let b=0;y>g&&b<o;b++){w.fill(0);for(let v=0;v<a;v++){for(let A=u[v];A<u[v+1];A++)m[d[A]]=v+1;for(let A=0;A<a;A++){if(v===A)continue;let E=0;for(let N=0;N<i;N++)p[N]=l[i*v+N]-l[i*A+N],E+=p[N]*p[N];const I=Math.sqrt(E)||.01,k=m[A]===v+1?r:1;for(let N=0;N<i;N++)w[i*v+N]+=f/I*p[N]-k*p[N]}}y=0;for(let v=0;v<a;v++){let A=0;for(let E=0;E<i;E++)l[i*v+E]+=w[i*v+E]*h,A+=w[i*v+E]*w[i*v+E];y+=Math.sqrt(A)}}return(e.scale!==void 0||e.center!==void 0)&&Jn(l,i,e.scale??1,e.center),{positions:Float32Array.from(l),dim:i,n:a}}function Hc(n,e,t,r,o,s,i="subsets"){if(r!=="vertical"&&r!=="horizontal")throw ze(new Error("align must be either vertical or horizontal"),"E_BAD_OPTION",{option:"align",value:r});const a=new Float64Array(2*n).fill(Number.NaN);if(e.forEach((c,l)=>{for(let u=0;u<c.length;u++){const d=c[u];if(!Number.isInteger(d)||d<0||d>=n)throw ze(new Error(`layer node index ${String(d)} is not a node of the graph`),"E_BAD_NODE",{option:i,index:d});[a[2*d],a[2*d+1]]=t(l,e.length,u,c.length)}}),r==="vertical")return Jn(a,2,o,s);Jn(a,2,o,[s[1],s[0]]);for(let c=0;c<n;c++)[a[2*c],a[2*c+1]]=[a[2*c+1],a[2*c]];return a}const Hg=(n,e,t,r)=>[n-(e-1)/2,t-(r-1)/2];function Kg(n,e,t){const r=n.nodes.get(e);if(r===null)throw ze(new Error(`${t} names node column "${e}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:t,column:e});if(r.dtype!=="u32"&&r.dtype!=="dict")throw ze(new Error(`${t} column "${e}" must be u32 or dict, not ${r.dtype}`),"E_COLUMN_TYPE",{option:t,column:e,dtype:r.dtype,expected:["u32","dict"]});const o=r.dtype==="u32"?r.data:r.codes,s=new Map;for(let i=0;i<n.nodeCount;i++)if(r.isSet(i)){const a=s.get(o[i]);a===void 0?s.set(o[i],[i]):a.push(i)}return[...s.keys()].sort((i,a)=>i-a).map(i=>s.get(i)??[])}function K_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{subsets:i="subset",align:a="vertical"}=e,c=typeof i=="string"?Kg(n,i,"subsets"):i.map(l=>ss(n,l));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Y_(n,e){const t=n.nodeCount;if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`start node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"start",index:e});const r=new Uint8Array(t);r[e]=1;let o=1;const s=[[e]];for(let i=s[0];;){const a=[];for(const c of i)for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];r[u]===0&&(r[u]=1,a.push(u))}if(a.length===0)break;o+=a.length,s.push(a),i=a}if(o<t)throw Object.assign(new Error("bfs_layout didn't include all nodes. Graph may be disconnected."),{code:"E_NOT_CONNECTED",params:{nodeCount:t,reached:o}});return s}function X_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{start:i=0,align:a="vertical"}=e,c=t===0?[]:Y_(co(n),xe(n,i));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Q_(n,e,t,r,o,s,i){const a=r;return Hc(n,[e,t],(c,l,u,d)=>[c*a-a/2,u/d-.5],o,s,i)}function J_(n,e){const t=typeof e=="string"||e instanceof Uint32Array?e:Df(n,e);if(typeof t!="string"){if(t.length<Math.ceil(n.nodeCount/32))throw ze(new Error(`top mask has ${t.length} words; ${n.nodeCount} nodes need ${Math.ceil(n.nodeCount/32)}`),"E_BAD_OPTION",{option:"top",length:t.length,expected:Math.ceil(n.nodeCount/32)});return o=>(t[o>>>5]>>>(o&31)&1)===1}const r=n.nodes.get(t);if(r===null)throw ze(new Error(`top names node column "${t}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:"top",column:t});if(r.dtype!=="bool")throw ze(new Error(`top column "${t}" must be bool, not ${r.dtype}`),"E_COLUMN_TYPE",{option:"top",column:t,dtype:r.dtype,expected:["bool"]});return o=>r.isSet(o)&&(r.data[o>>>5]>>>(o&31)&1)===1}function Yg(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{top:i,align:a="vertical",aspectRatio:c=1.3333333333333333}=e,l=i===void 0?f=>f%2===0:J_(n,i),u=[],d=[];for(let f=0;f<t;f++)(l(f)?u:d).push(f);return Wt(Rn(Q_(t,u,d,c,a,o,s),r,s),r,t)}const ds={zeros:function(n){return typeof n=="number"?new Array(n).fill(0):n.length===1?new Array(n[0]).fill(0):new Array(n[0]).fill(0).map(()=>this.zeros(n.slice(1)))},ones:function(n){return typeof n=="number"?new Array(n).fill(1):n.length===1?new Array(n[0]).fill(1):new Array(n[0]).fill(1).map(()=>this.ones(n.slice(1)))},linspace:function(n,e,t){if(t===1)return[n];const r=(e-n)/(t-1);return Array.from({length:t},(o,s)=>n+s*r)},array:function(n){return Array.isArray(n)?[...n]:[n]},repeat:function(n,e){const t=[];for(let r=0;r<e;r++)t.push(...ds.array(n));return t},mean:function(n,e=null){if(e===null){const t=Array.isArray(n[0])?n.flat(1/0):n;return t.reduce((o,s)=>o+s,0)/t.length}if(e===0){const t=[],r=n;for(let o=0;o<r[0].length;o++){let s=0;for(let i=0;i<r.length;i++)s+=r[i][o];t.push(s/r.length)}return t}return n.map(t=>ds.mean(t))},add:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n+e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t+e[r]):n.map(t=>t+e):e.map(t=>n+t)},subtract:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n-e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t-e[r]):n.map(t=>t-e):e.map(t=>n-t)},max:function(n){return Array.isArray(n)?Math.max(...n.flat(1/0)):n},min:function(n){return Array.isArray(n)?Math.min(...n.flat(1/0)):n},norm:function(n){return Math.sqrt(n.reduce((e,t)=>e+t*t,0))}};function Z_(n,e,t,r){const o=new Float64Array(n*e);if(n===1)o.set(r);else if(e===2){const s=ds.linspace(0,2*Math.PI,n+1);for(let i=0;i<n;i++)o[2*i]=yn(s[i])*t+r[0],o[2*i+1]=Jt(s[i])*t+r[1]}else{const s=(1+Math.sqrt(5))/2;for(let i=0;i<n;i++){const a=2*Math.PI*i/s,c=Of(1-2*(i+.5)/n);o[3*i]=Jt(c)*yn(a)*t+r[0],o[3*i+1]=Jt(c)*Jt(a)*t+r[1],o[3*i+2]=yn(c)*t+r[2]}}return o}function eI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Z_(t,r,o,s),r,t)}const ut=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1}),vi=.01,tI=1e-4,Xg=1e-8,xr=256,Qg=.9,nI=5,rI=1e4;function Jg(n,e,t){if(t.meta.components!==1)throw new RangeError(`node column "${e}" has ${t.meta.components} components; a node vector has one`);switch(t.dtype){case"f32":case"f64":{const r=n.nodes.gpuView(e);return r instanceof Float32Array?r:new Float32Array(r)}case"u32":case"i32":return new Float32Array(n.nodes.gpuView(e));case"u8":return new Float32Array(t.data);default:throw new TypeError(`node column "${e}" is ${t.dtype}, not numeric`)}}function oI(n,e,t){const r=e.nodeCount;if(n==null){const s=e.nodes.byRole("mass");if(s!==null)return Jg(e,s.meta.name,s);const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=t(a);return i}if(n instanceof Float32Array){if(n.length!==r)throw new RangeError(`the node vector has ${n.length} values, expected ${r}`);return n}if(typeof n=="string"){const s=e.nodes.get(n);if(s===null)throw new RangeError(`the option names node column "${n}", which the snapshot does not hold`);return Jg(e,n,s)}const o=new Float32Array(r);for(let s=0;s<r;s++){const i=n[e.ids.idOf(s)];o[s]=i===void 0?t(s):i}return o}function Zg(n,e){if(n===!0)return e.weights;if(n===!1||n===null||n===void 0)return null;const t=e.edges.get(n);if(t===null)throw new RangeError(`weight names edge column "${n}", which the snapshot does not hold`);if(t.meta.components!==1)throw new RangeError(`edge column "${n}" has ${t.meta.components} components; a weight column has one`);switch(t.dtype){case"f32":case"f64":case"u32":case"i32":{const r=Va(e,e.edges.gpuView(n));return r instanceof Float32Array?r:new Float32Array(r)}default:throw new TypeError(`edge column "${n}" is ${t.dtype}; a weight column is f32, f64, u32 or i32`)}}function Zn(n,e,t,r,o){if(e===void 0)return t;if(typeof e!="number"||!r(e))throw new RangeError(`ForceAtlas2Simulation: ${n} must be ${o}, got ${String(e)}`);return e}function Kc(n,e,t){if(e===void 0)return t;if(typeof e!="boolean")throw new TypeError(`ForceAtlas2Simulation: ${n} must be a boolean, got ${String(e)}`);return e}function sI(n){const e=[0,0,0];if(n===void 0)return e;if(n.length>3)throw new RangeError(`ForceAtlas2Simulation: center has ${n.length} components, at most 3 expected`);for(let t=0;t<n.length;t++){const r=n[t];if(typeof r!="number"||!Number.isFinite(r))throw new RangeError(`ForceAtlas2Simulation: center[${t}] is not finite`);e[t]=r}return e}function Ai(n){return Number.isInteger(n)&&n>=1}function iI(n){const e=n??{},t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`ForceAtlas2Simulation: dim must be 2 or 3, got ${String(t)}`);const r=e.compat??"paper";if(r!=="paper"&&r!=="networkx")throw new RangeError(`ForceAtlas2Simulation: compat must be "paper" or "networkx", got ${String(r)}`);return{maxIter:Zn("maxIter",e.maxIter,ut.maxIter,Ai,"an integer >= 1"),jitterTolerance:Zn("jitterTolerance",e.jitterTolerance,ut.jitterTolerance,o=>o>0,"> 0"),scalingRatio:Zn("scalingRatio",e.scalingRatio,ut.scalingRatio,o=>o>0,"> 0"),gravity:Zn("gravity",e.gravity,ut.gravity,o=>o>=0,">= 0"),strongGravity:Kc("strongGravity",e.strongGravity,ut.strongGravity),distributedAction:Kc("distributedAction",e.distributedAction,ut.distributedAction),linlog:Kc("linlog",e.linlog,ut.linlog),nodeMass:e.nodeMass??null,weight:e.weight??null,dim:t,scale:Zn("scale",e.scale,ut.scale,o=>Number.isFinite(o)&&o>0,"a finite number > 0"),center:sI(e.center),settleThreshold:Zn("settleThreshold",e.settleThreshold,ut.settleThreshold,o=>o>=0,">= 0"),settleWindow:Zn("settleWindow",e.settleWindow,ut.settleWindow,Ai,"an integer >= 1"),iterationsPerStep:Zn("iterationsPerStep",e.iterationsPerStep,ut.iterationsPerStep,Ai,"an integer >= 1"),compat:r,seed:e.seed??null}}function Yc(n){return{attraction:new Float64Array(3*n),force:new Float64Array(3*n),swing:new Float64Array(n),traction:new Float64Array(n),sumX:new Float64Array(n),sumY:new Float64Array(n),sumZ:new Float64Array(n),sumW:new Float64Array(n),disp:new Float64Array(n),free:new Float64Array(n)}}function ew(n){for(let e=xr/2;e>0;e=Math.floor(e/2))for(let t=0;t<e;t++)n[t]=n[t]+n[t+e];return n[0]}function er(n,e){const t=Math.ceil(e/xr),r=new Float64Array(t),o=new Float64Array(xr);for(let s=0;s<t;s++){for(let i=0;i<xr;i++){const a=s*xr+i;o[i]=a<e?n[a]:0}r[s]=ew(o)}return r}function tr(n){const e=new Float64Array(xr);for(let t=0;t<n.length;t++){const r=t%xr;e[r]=e[r]+n[t]}return ew(e)}function Dn(n,e,t){return Math.sqrt(n*n+e*e+t*t)}function tw(n){let e=n>>>0;return e=(e^e>>>16)>>>0,e=Math.imul(e,2146121005)>>>0,e=(e^e>>>15)>>>0,e=Math.imul(e,2221713035)>>>0,e=(e^e>>>16)>>>0,e}function aI(n,e){const t=Math.min(n,e),r=Math.max(n,e);return tw((Math.imul(t,2654435769)>>>0^r)>>>0)}function nw(n){return(n>>>8)*5960464477539063e-23}function rw(n,e,t){const r=aI(n,e),o=6.283185307179586*nw(r);let s;if(t===2)s=[yn(o),Jt(o),0];else{const i=2*nw(tw((r^1540483477)>>>0))-1,a=Math.sqrt(Math.max(0,1-i*i));s=[a*yn(o),a*Jt(o),i]}return n>e?[-s[0],-s[1],-s[2]]:s}function cI(n,e,t,r,o,s){const i=n,a=s,c=.05*Math.sqrt(i),l=Math.sqrt(c),u=10,d=Math.max(t,1e-30),f=Math.min(u,c*t/(i*i));let h=a*Math.max(l,f),g=o;e>2*d&&(g>.05&&(g=g*.5),h=Math.max(h,a));const w=e===0?1e30:h*g*t/e;return e>h*t?g>.05&&(g=g*.7):r<1e3&&(g=g*1.3),{speed:r+Math.min(w-r,.5*r),speedEfficiency:g}}function lI(n,e,t,r){for(let o=0;o<t;o++){if(n[o]===e[o])continue;const s=Math.min(r,o*32+32);for(let i=o*32;i<s;i++)if(_e(n,i)&&!_e(e,i))return!0}return!1}class uI{constructor(e){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.weights=null,this.mass=new Float64Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.fixed=null,this.scratch=Yc(0),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.settledCountValue=0,this.iterationsDoneValue=0,this.centroid=[0,0,0],this.pending=null,this.options=iI(e),this.dim=this.options.dim,this.swingMode=this.options.compat==="networkx"?1:0,this.gravityCenter=this.options.compat==="networkx"?1:0}get settled(){return this.state!=="loaded"?!1:this.n===0||this.iterationsDoneValue>=this.options.maxIter||this.settledCountValue>=this.options.settleWindow}get iterationsDone(){return this.iterationsDoneValue}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("ForceAtlas2Simulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new Error(`ForceAtlas2Simulation: positions.length ${t.length} !== 3 x ${r}`);const o=e.outDegree(),s=oI(this.options.nodeMass,e,p=>o[p]+1),i=Zg(this.options.weight,e),a=new Float64Array(r);for(let p=0;p<r;p++)if(a[p]=s[p],!(a[p]>0))throw new Error(`ForceAtlas2Simulation: mass[${p}] must be positive`);const c=i===null?null:Float64Array.from(i);r!==this.n&&(this.fixed=null),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.mass=a,this.weights=c,this.owner=t;const{scale:l,center:u,seed:d}=this.options;bi(e,t,d,this.dim,l,u,"fa2");const[f,h,g]=u,w=new Float64Array(3*r);for(let p=0;p<r;p++)w[3*p]=(t[3*p]-f)/l,w[3*p+1]=(t[3*p+1]-h)/l,w[3*p+2]=this.dim===2?0:(t[3*p+2]-g)/l;this.positions=w,this.oldForce=new Float64Array(3*r),this.scratch=Yc(r),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.pending=null,this.writeInitialStatistics(),this.state="loaded",this.reheat()}step(e=this.options.iterationsPerStep){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed");if(this.state==="created")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)");if(!Ai(e))throw new RangeError(`ForceAtlas2Simulation: iterations must be an integer >= 1, got ${String(e)}`);if(this.settled)return;let t=0;for(;t<e&&!this.settled;)this.iterate(),this.iterationsDoneValue+=1,t+=1;this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`ForceAtlas2Simulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);const o=this.fixed,s=o!==null&&lI(o,e,r,t),i=new Uint32Array(r);i.set(e.subarray(0,r)),this.fixed=i,s&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s,owner:i}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`ForceAtlas2Simulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("ForceAtlas2Simulation: setPosition: coordinates must be finite");i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o;const{scale:a}=this.options,[c,l,u]=this.options.center;this.positions[3*e]=(i[3*e]-c)/a,this.positions[3*e+1]=(i[3*e+1]-l)/a,this.positions[3*e+2]=this.dim===2?0:(i[3*e+2]-u)/a,this.reheat()}reheat(){this.assertNotDisposed(),this.iterationsDoneValue=0,this.settledCountValue=0,this.swingMode===1&&(this.swingValue=1,this.tractionValue=1)}dispose(){this.state="disposed",this.owner=new Float32Array(0),this.scratch=Yc(0),this.pending=null,this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.mass=new Float64Array(0),this.weights=null,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null,this.n=0}assertNotDisposed(){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)")}isFixed(e){return this.fixed!==null&&_e(this.fixed,e)}writeBack(){const{n:e,owner:t,positions:r}=this,{scale:o}=this.options,[s,i,a]=this.options.center;for(let c=0;c<e;c++)this.isFixed(c)||(t[3*c]=r[3*c]*o+s,t[3*c+1]=r[3*c+1]*o+i,t[3*c+2]=this.dim===2?a:r[3*c+2]*o+a)}writeInitialStatistics(){const{n:e,positions:t}=this,r=[0,0,0];for(let o=0;o<e;o++)for(let s=0;s<3;s++)r[s]+=t[3*o+s];e===0?this.centroid=[0,0,0]:this.centroid=[r[0]/e,r[1]/e,r[2]/e],this.settledCountValue=0}foldTotals(e){return{sum:[tr(e.sumX),tr(e.sumY),tr(e.sumZ)],sumSq:tr(e.sumW),disp:tr(e.disp),free:tr(e.free)}}fold(e){const t=this.foldTotals(e),r=this.n,o=Math.sqrt(Math.max(t.sumSq,0)/r),s=t.free===0?0:t.disp/t.free;this.centroid=[t.sum[0]/r,t.sum[1]/r,t.sum[2]/r],this.settledCountValue=s<=this.options.settleThreshold*o?this.settledCountValue+1:0}iterate(){const{n:e,scratch:t}=this;this.pending!==null&&this.fold(this.pending);const{positions:r,mass:o,rowPtr:s,colIdx:i,weights:a,oldForce:c}=this,{scalingRatio:l,gravity:u,linlog:d,distributedAction:f,strongGravity:h}=this.options,{attraction:g,force:w,swing:p,traction:m,sumX:y,sumY:b,sumZ:v,sumW:A,disp:E,free:I}=t;for(let R=0;R<e;R++){let D=0,U=0,B=0;const V=r[3*R],W=r[3*R+1],q=r[3*R+2];for(let K=s[R];K<s[R+1];K++){const X=i[K];if(X===R)continue;const H=a===null?1:a[K],Y=r[3*X]-V,ee=r[3*X+1]-W,Z=r[3*X+2]-q;let J=H;if(d){const ce=Math.max(Dn(Y,ee,Z),vi);J=H*Ge(1+ce)/ce}D=D+Y*J,U=U+ee*J,B=B+Z*J}f&&(D=D/o[R],U=U/o[R],B=B/o[R]),g[3*R]=D,g[3*R+1]=U,g[3*R+2]=B}p.fill(0),m.fill(0);const k=this.centroid[0],N=this.centroid[1],C=this.centroid[2];for(let R=0;R<e;R++){const D=r[3*R],U=r[3*R+1],B=r[3*R+2],V=o[R];let W=0,q=0,K=0;for(let he=0;he<e;he++){if(he===R)continue;const ge=o[he],me=D-r[3*he],De=U-r[3*he+1],Ne=B-r[3*he+2];let He=me*me+De*De+Ne*Ne;if(He<Xg){const Ft=rw(R,he,this.dim),Nt=l*V*ge/vi;W=W+Ft[0]*Nt,q=q+Ft[1]*Nt,K=K+Ft[2]*Nt;continue}He=Math.max(He,tI);const mt=l*V*ge/He;W=W+me*mt,q=q+De*mt,K=K+Ne*mt}let X=0,H=0,Y=0;const ee=this.gravityCenter===0?D-k:D,Z=this.gravityCenter===0?U-N:U,J=this.gravityCenter===0?B-C:B,ce=-u*V;if(h)X=ce*ee,H=ce*Z,Y=ce*J;else{const he=Dn(ee,Z,J);he>vi&&(X=ce*ee/he,H=ce*Z/he,Y=ce*J/he)}W=W+X,q=q+H,K=K+Y;const de=g[3*R]+W,ne=g[3*R+1]+q,ve=g[3*R+2]+K;w[3*R]=de,w[3*R+1]=ne,w[3*R+2]=ve;const ue=c[3*R],we=c[3*R+1],Xe=c[3*R+2];this.swingMode===1?(p[R]=V*Dn(D-de,U-ne,B-ve),m[R]=.5*V*Dn(D+de,U+ne,B+ve)):this.isFixed(R)||(p[R]=V*Dn(de-ue,ne-we,ve-Xe),m[R]=.5*V*Dn(de+ue,ne+we,ve+Xe))}const O=tr(er(p,e)),T=tr(er(m,e));let $=O,L=T;this.swingMode===1&&($=this.swingValue+O,L=this.tractionValue+T);const F=cI(e,$,L,this.speedValue,this.speedEfficiencyValue,this.options.jitterTolerance);this.speedValue=F.speed,this.speedEfficiencyValue=F.speedEfficiency,this.swingValue=$,this.tractionValue=L;const M=this.speedValue;E.fill(0),I.fill(0);for(let R=0;R<e;R++){const D=w[3*R],U=w[3*R+1],B=w[3*R+2],V=o[R];let W=V*Dn(D,U,B);this.swingMode===0&&(W=V*Dn(D-c[3*R],U-c[3*R+1],B-c[3*R+2]));const q=M/(1+Math.sqrt(M*W)),K=this.isFixed(R),X=K?0:D*q,H=K?0:U*q;let Y=K?0:B*q;this.dim===2&&(Y=0);const ee=r[3*R]+X,Z=r[3*R+1]+H,J=r[3*R+2]+Y;r[3*R]=ee,r[3*R+1]=Z,r[3*R+2]=J,this.swingMode===0&&(c[3*R]=D,c[3*R+1]=U,c[3*R+2]=B);const ce=ee-k,de=Z-N,ne=J-C;y[R]=ee,b[R]=Z,v[R]=J,A[R]=ce*ce+de*de+ne*ne,K||(E[R]=Dn(X,H,Y),I[R]=1)}this.pending={sumX:er(y,e),sumY:er(b,e),sumZ:er(v,e),sumW:er(A,e),disp:er(E,e),free:er(I,e)}}}const fs=.1,dI=50,fI=.1,hI=.7;function gI(n){const e=[0,0,0];if(n===void 0)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function Ei(n,e,t,r,o){if(!Number.isFinite(e)||e<t||e>r||o&&!Number.isInteger(e))throw new RangeError(`FruchtermanReingoldSimulation: ${n} must be ${o?"an integer":"a finite number"} in [${t}, ${r}], got ${e}`);return e}class wI{constructor(e={}){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.fixed=null,this.k=0,this.dt=0,this.t=fs,this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0,this.pendingEnergy=null,this.iterationsDoneValue=0,this.settledCountValue=0,this.settledValue=!1,this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;const t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`FruchtermanReingoldSimulation: dim must be 2 or 3, got ${String(t)}`);this.dim=t;const r=e.scale??ut.scale;if(!Number.isFinite(r)||r<=0)throw new RangeError(`FruchtermanReingoldSimulation: scale must be a finite number > 0, got ${r}`);this.scale=r,this.center=gI(e.center),this.seed=e.seed??null;const o=e.k??null;if(o===null||Number.isNaN(o)||o===0)this.kOption=null;else{if(!Number.isFinite(o)||o<0)throw new RangeError(`FruchtermanReingoldSimulation: k must be null, 0 or a finite number > 0, got ${o}`);this.kOption=o}const s=e.cooling??"linear";if(s!=="linear"&&s!=="adaptive")throw new RangeError(`FruchtermanReingoldSimulation: cooling must be "linear" or "adaptive", got ${String(s)}`);this.adaptive=s==="adaptive",this.iterations=Ei("iterations",e.iterations??(this.adaptive?rI:dI),0,Number.MAX_SAFE_INTEGER,!0),this.settleThreshold=Ei("settleThreshold",e.settleThreshold??ut.settleThreshold,0,Number.POSITIVE_INFINITY,!1),this.settleWindow=Ei("settleWindow",e.settleWindow??ut.settleWindow,1,Number.MAX_SAFE_INTEGER,!0),this.iterationsPerStep=Ei("iterationsPerStep",e.iterationsPerStep??ut.iterationsPerStep,1,Number.MAX_SAFE_INTEGER,!0),this.fixedOption=e.fixed??null}get settled(){return this.settledValue}get iterationsDone(){return this.iterationsDoneValue}get settledCount(){return this.settledCountValue}get meanDisplacement(){return this.meanDisplacementValue}get rmsRadius(){return this.rmsRadiusValue}get temperature(){return this.t}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("FruchtermanReingoldSimulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new RangeError(`FruchtermanReingoldSimulation: positions has ${t.length} entries, expected ${3*r}`);const o=this.resolveFixed(e,r);r!==this.n&&(this.positions=new Float64Array(3*r),this.displacement=new Float64Array(3*r)),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.owner=t,this.fixed=o,bi(e,t,this.seed,this.dim,this.scale,this.center,"fr");const s=this.positions,[i,a,c]=this.center,{scale:l}=this;for(let u=0;u<r;u++)s[3*u]=(t[3*u]-i)/l,s[3*u+1]=(t[3*u+1]-a)/l,s[3*u+2]=this.dim===2?0:(t[3*u+2]-c)/l;this.k=this.kOption??1/Math.sqrt(r),this.dt=fs/(this.iterations+1),this.t=fs,this.resetAdaptive(),this.pendingEnergy=null,this.writeInitialStatistics(),this.iterationsDoneValue=0,this.settledCountValue=0,this.state="loaded",this.settledValue=r===0||this.computeSettled()}step(e=this.iterationsPerStep){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded");if(!Number.isInteger(e)||e<1)throw new RangeError(`FruchtermanReingoldSimulation: step(${e}): an integer >= 1 is required`);if(this.settledValue)return;let t=0;for(;t<e&&!this.settledValue;)this.iterate(),t++,this.iterationsDoneValue++,this.settledValue=this.computeSettled();this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`FruchtermanReingoldSimulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);let o=!1;const s=this.fixed;if(s!==null)for(let i=0;i<t&&!o;i++)_e(s,i)&&!_e(e,i)&&(o=!0);this.fixed=new Uint32Array(e.subarray(0,r)),o&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`FruchtermanReingoldSimulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("FruchtermanReingoldSimulation: setPosition: coordinates must be finite");const{owner:i,positions:a,scale:c}=this,[l,u,d]=this.center;i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o,a[3*e]=(t-l)/c,a[3*e+1]=(r-u)/c,a[3*e+2]=this.dim===2?0:(o-d)/c,this.reheat()}reheat(){this.assertNotDisposed(),this.settledCountValue=0,this.adaptive?(this.iterationsDoneValue=0,this.t=fs,this.resetAdaptive()):(this.iterationsDoneValue=Math.floor(hI*this.iterations),this.t=fs-this.dt*this.iterationsDoneValue),this.state==="loaded"&&(this.settledValue=this.n===0||this.computeSettled())}dispose(){this.state="disposed",this.n=0,this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.owner=new Float32Array(0),this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null}iterate(){this.adaptive&&this.pendingEnergy!==null&&this.updateAdaptive(this.pendingEnergy);const{n:e,k:t,t:r,positions:o,displacement:s,rowPtr:i,colIdx:a,fixed:c}=this;s.fill(0);for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=b+1;I<e;I++){const k=v-o[3*I],N=A-o[3*I+1],C=E-o[3*I+2],O=k*k+N*N+C*C;let T,$,L;if(O<Xg){const F=rw(b,I,this.dim),M=t*t/vi;T=F[0]*M,$=F[1]*M,L=F[2]*M}else{const F=Math.sqrt(O),M=t*t/F;T=k/F*M,$=N/F*M,L=C/F*M}s[3*b]+=T,s[3*b+1]+=$,s[3*b+2]+=L,s[3*I]-=T,s[3*I+1]-=$,s[3*I+2]-=L}}for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=i[b];I<i[b+1];I++){const k=a[I],N=v-o[3*k],C=A-o[3*k+1],O=E-o[3*k+2],T=Math.sqrt(N*N+C*C+O*O)||fI,$=T*T/t;s[3*b]-=N/T*$,s[3*b+1]-=C/T*$,s[3*b+2]-=O/T*$}}const[l,u,d]=this.centroid;let f=0,h=0,g=0,w=0,p=0,m=0,y=0;for(let b=0;b<e;b++){if(c===null||!_e(c,b)){const C=s[3*b],O=s[3*b+1],T=s[3*b+2],$=C*C+O*O+T*T,L=Math.sqrt($);y+=$;const F=Math.min(L,r);L!==0&&(o[3*b]+=C/L*F,o[3*b+1]+=O/L*F,o[3*b+2]+=T/L*F),p+=F,m++}const v=o[3*b],A=o[3*b+1],E=o[3*b+2];f+=v,h+=A,g+=E;const I=v-l,k=A-u,N=E-d;w+=I*I+k*k+N*N}this.adaptive?this.pendingEnergy=y:this.t-=this.dt,this.centroid=[f/e,h/e,g/e],this.rmsRadiusValue=Math.sqrt(Math.max(w,0)/e),this.meanDisplacementValue=m===0?0:p/m,this.settledCountValue=this.meanDisplacementValue<=this.settleThreshold*this.rmsRadiusValue?this.settledCountValue+1:0}resetAdaptive(){this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0}updateAdaptive(e){e<this.previousEnergy?(this.progress++,this.progress>=nI&&(this.progress=0,this.t/=Qg)):(this.progress=0,this.t*=Qg),this.previousEnergy=e}writeBack(){const{n:e,owner:t,positions:r,scale:o,fixed:s}=this,[i,a,c]=this.center;for(let l=0;l<e;l++)s!==null&&_e(s,l)||(t[3*l]=r[3*l]*o+i,t[3*l+1]=r[3*l+1]*o+a,t[3*l+2]=r[3*l+2]*o+c)}writeInitialStatistics(){const{n:e,positions:t}=this;if(e===0){this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;return}let r=0,o=0,s=0;for(let a=0;a<e;a++)r+=t[3*a],o+=t[3*a+1],s+=t[3*a+2];r/=e,o/=e,s/=e;let i=0;for(let a=0;a<e;a++){const c=t[3*a]-r,l=t[3*a+1]-o,u=t[3*a+2]-s;i+=c*c+l*l+u*u}this.centroid=[r,o,s],this.rmsRadiusValue=Math.sqrt(i/e),this.meanDisplacementValue=0}computeSettled(){return this.iterationsDoneValue>=this.iterations||this.settledCountValue>=this.settleWindow}resolveFixed(e,t){const r=Math.ceil(t/32),o=this.fixedOption;if(typeof o=="string"){const i=e.nodes.get(o);if(i===null)throw new RangeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which the snapshot does not hold`);if(i.dtype!=="bool")throw new TypeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which is ${i.dtype}, not bool`);return new Uint32Array(i.data.subarray(0,r))}if(o!==null){if(o.length<r)throw new RangeError(`FruchtermanReingoldSimulation: the fixed mask has ${o.length} words, ${r} needed for ${t} nodes`);return new Uint32Array(o.subarray(0,r))}const s=e.nodes.byRole("fixed");return s!==null&&s.dtype==="bool"?new Uint32Array(s.data.subarray(0,r)):t===this.n?this.fixed:null}assertNotDisposed(){if(this.state==="disposed")throw new Error("FruchtermanReingoldSimulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded")}}function pI(n,e,t,r){if(e!==null&&(!Number.isInteger(e)||e<1))throw ze(new Error("columns must be a positive integer"),"E_BAD_OPTION",{option:"columns",value:e});const o=new Float64Array(2*n);if(n===0)return o;const s=Math.min(e??Math.ceil(Math.sqrt(n)),n),i=Math.ceil(n/s),a=Math.max(s-1,i-1),c=a===0?0:2*t/a;for(let l=0;l<n;l++)o[2*l]=r[0]+(l%s-(s-1)/2)*c,o[2*l+1]=r[1]+(Math.floor(l/s)-(i-1)/2)*c;return o}function mI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(pI(t,e.columns??null,o,s),r,s),r,t)}function yI(n,e,t,r){if(e.length===0)return n.map(l=>-l);const o=n.slice(),s=new Array(e.length).fill(0),i=[];for(let l=0;l<e.length;l++){const u=e[l],d=t[l];i.push(1/d.reduce((f,h,g)=>f+h*u[g],0))}for(let l=e.length-1;l>=0;l--){const u=e[l];s[l]=i[l]*u.reduce((d,f,h)=>d+f*o[h],0);for(let d=0;d<o.length;d++)o[d]-=s[l]*t[l][d]}let a=1;if(e.length>0&&t.length>0){const l=t[t.length-1];a=e[e.length-1].reduce((d,f,h)=>d+f*l[h],0)/l.reduce((d,f)=>d+f*f,0)}const c=o.map(l=>a*l);for(let l=0;l<e.length;l++){const u=e[l],d=t[l],f=i[l]*d.reduce((h,g,w)=>h+g*c[w],0);for(let h=0;h<c.length;h++)c[h]+=u[h]*(s[l]-f)}return c.map(l=>-l)}function bI(n,e,t,r,o,s){const c=r.reduce((d,f,h)=>d+f*e[h],0);if(c>=0)return 0;let l=s;const u=20;for(let d=0;d<u;d++){const f=n.map((g,w)=>g+l*e[w]);if(o(f)<=t+1e-4*l*c)return l;l*=.5}return 0}function vI(n,e,t){const r=e.length,o=.001,s=n.map(h=>h.map(g=>g===0?0:1/g)),i=e.flat(),a=500,c=1e-5,l=10,u=[],d=[];for(let h=0;h<a;h++){const[g,w]=Xc(i,s,o,t),p=yI(w,u,d),m=bI(i,p,g,w,I=>Xc(I,s,o,t)[0],1);if(m===0){if(u.length===0)break;u.length=0,d.length=0;continue}const y=[...i];for(let I=0;I<i.length;I++)i[I]+=m*p[I];const[,b]=Xc(i,s,o,t),v=i.map((I,k)=>I-y[k]),A=b.map((I,k)=>I-w[k]);if(v.reduce((I,k,N)=>I+k*A[N],0)>1e-10&&(u.push(v),d.push(A)),u.length>l&&(u.shift(),d.shift()),Math.sqrt(b.reduce((I,k)=>I+k*k,0))<c)break}const f=[];for(let h=0;h<r;h++)f.push(i.slice(h*t,(h+1)*t));return f}function AI(n,e,t){const r=t.length;for(let o=0;o<r;o++)for(let s=o+1;s<r;s++){const i=e[o].map((u,d)=>u-e[s][d]),a=Math.sqrt(i.reduce((u,d)=>u+d*d,0)),c=t[o][s],l=a*c-1;n+=l*l}return n}function EI(n,e,t,r){const o=t.length;for(let s=0;s<o;s++)for(let i=s+1;i<o;i++){const a=e[s].map((f,h)=>f-e[i][h]),c=Math.sqrt(a.reduce((f,h)=>f+h*h,0))||1e-10,l=a.map(f=>f/c),u=t[s][i],d=c*u-1;for(let f=0;f<r;f++){const h=2*u*d*l[f];n[s*r+f]+=h,n[i*r+f]-=h}}}function Xc(n,e,t,r){const o=e.length,s=[];for(let l=0;l<o;l++)s.push(n.slice(l*r,(l+1)*r));let i=0;const a=new Array(r).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)a[u]+=s[l][u];i+=.5*t*a.reduce((l,u)=>l+u*u,0),i=AI(i,s,e);const c=new Array(n.length).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)c[l*r+u]+=t*a[u];return EI(c,s,e,r),[i,c]}const _I=1e6,II=42,kI=24;function ow(n,e){const t=kI*n*n,r=e===null?`kamadaKawai: ${n} nodes need about ${t} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`kamadaKawai: ${n} nodes exceeds maxNodes ${e}; it would allocate about ${t} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(new RangeError(r),{code:"E_TOO_LARGE",params:{nodeCount:n,maxNodes:e,bytes:t}})}function SI(n,e){let t=null;return e===!0?t=n.edges.byRole("weight"):typeof e=="string"&&(t=n.edges.get(e)),t?.dtype==="f64"&&t.meta.components===1?Va(n,t.data):Zg(e,n)}function PI(n,e){const t=n.nodeCount;let r;if(e.dist!==null&&e.dist!==void 0){if(e.dist.length!==t*t)throw ze(new RangeError(`kamadaKawai: dist has ${e.dist.length} values, expected ${t*t} (n * n)`),"E_BAD_OPTION",{option:"dist",length:e.dist.length,expected:t*t});if(t>=2&&!e.dist.some((o,s)=>Number.isFinite(o)&&s%(t+1)!==0))throw ze(new RangeError("kamadaKawai: dist has no finite distance between two different nodes; was it computed from a graph without edges?"),"E_BAD_OPTION",{option:"dist"});r=e.dist}else{const o=SI(n,e.weight??!0);let s;try{s=new Float64Array(t*t).fill(Number.POSITIVE_INFINITY)}catch(c){throw c instanceof RangeError?ow(t,null):c}const{rowPtr:i,colIdx:a}=n;for(let c=0;c<t;c++){s[c*t+c]=0;for(let l=i[c];l<i[c+1];l++){const u=o===null?1:o[l];if(!(u>=0))throw ze(new RangeError(`kamadaKawai: weights are distances and must be >= 0, got ${u}`),"E_BAD_WEIGHT",{weight:u});const d=c*t+a[l];u<s[d]&&(s[d]=u)}}for(let c=0;c<t;c++)for(let l=0;l<t;l++){const u=s[l*t+c];if(u!==Number.POSITIVE_INFINITY)for(let d=0;d<t;d++){const f=u+s[c*t+d];f<s[l*t+d]&&(s[l*t+d]=f)}}r=s}return Array.from({length:t},(o,s)=>Array.from({length:t},(i,a)=>{const c=r[s*t+a];return s===a?0:Number.isFinite(c)?c:_I}))}function xI(n,e,t){const r=n.nodeCount,{pos:o}=e;if(o!=null){if(o.length!==t*r)throw ze(new RangeError(`kamadaKawai: pos has ${o.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:o.length,expected:t*r});return Array.from({length:r},(i,a)=>Array.from(o.subarray(t*a,t*a+t),c=>Number.isNaN(c)?0:c))}if(t===2){const i=ds.linspace(0,2*Math.PI,r+1);return Array.from({length:r},(a,c)=>[yn(i[c]),Jt(i[c])])}const s=new Float64Array(3*r).fill(Number.NaN);return bi(n,s,e.seed===void 0?II:e.seed,3,1,null,"fr"),Array.from({length:r},(i,a)=>Array.from(s.subarray(3*a,3*a+3)))}function CI(n,e={}){const t=co(n),r=qg(e.dim),o=t.nodeCount;if(e.maxNodes!==void 0&&(o>e.maxNodes||Number.isNaN(e.maxNodes)))throw ow(o,e.maxNodes);if(o<=1){const a=new Float32Array(r*o);return o===1&&a.set(Array.from({length:r},(c,l)=>e.center?.[l]??0)),{positions:a,dim:r,n:o}}const s=vI(PI(t,e),xI(t,e,r),r),i=Float64Array.from(s.flat());return Jn(i,r,e.scale??1,e.center),{positions:Float32Array.from(i),dim:r,n:o}}class NI{constructor(e){this.n=e,this.cw=Array.from({length:e},()=>new Map),this.ccw=Array.from({length:e},()=>new Map),this.first=new Int32Array(e).fill(-1)}has(e,t){return this.cw[e].has(t)}addCw(e,t,r){if(r<0){this.cw[e].set(t,t),this.ccw[e].set(t,t),this.first[e]=t;return}const o=this.cw[e].get(r);if(o===void 0)throw new Error("Cannot add edge. Reference neighbor does not exist");this.cw[e].set(r,t),this.cw[e].set(t,o),this.ccw[e].set(o,t),this.ccw[e].set(t,r)}addCcw(e,t,r){if(r<0){this.addCw(e,t,-1);return}this.addCw(e,t,this.ccw[e].get(r)??-1),r===this.first[e]&&(this.first[e]=t)}addFirst(e,t){this.addCcw(e,t,this.first[e])}nextFace(e,t){return[t,this.ccw[t].get(e)??-1]}neighboursCw(e){const t=this.first[e];if(t<0)return[];const r=[t];for(let o=this.cw[e].get(t)??t;o!==t;o=this.cw[e].get(o)??t)r.push(o);return r}}const _i=(n=-1,e=-1)=>({low:n,high:e}),Ln=n=>n.low<0&&n.high<0;class TI{constructor(e){this.adj=e,this.lowpt=new Map,this.lowpt2=new Map,this.nesting=new Map,this.oriented=new Set,this.ordered=[],this.ref=new Map,this.side=new Map,this.stack=[],this.stackBottom=new Map,this.lowptEdge=new Map,this.leftRef=new Map,this.rightRef=new Map,this.roots=[],this.n=e.length,this.height=new Int32Array(this.n).fill(-1),this.parentEdge=new Float64Array(this.n).fill(-1),this.out=Array.from({length:this.n},()=>[])}key(e,t){return e*this.n+t}target(e){return e%this.n}low(e){return this.lowpt.get(e)??0}run(){const{n:e}=this,t=this.adj.reduce((s,i)=>s+i.length,0)/2;if(e>2&&t>3*e-6)return null;for(let s=0;s<e;s++)this.height[s]<0&&(this.height[s]=0,this.roots.push(s),this.orient(s));const r=s=>[...this.out[s]].sort((i,a)=>(this.nesting.get(this.key(s,i))??0)-(this.nesting.get(this.key(s,a))??0));this.ordered=Array.from({length:e},(s,i)=>r(i));for(const s of this.roots)if(!this.test(s))return null;for(const s of this.oriented)this.nesting.set(s,this.sign(s)*(this.nesting.get(s)??0));const o=new NI(e);for(let s=0;s<e;s++){this.ordered[s]=r(s);let i=-1;for(const a of this.ordered[s])o.addCw(s,a,i),i=a}for(const s of this.roots)this.embed(s,o);return o}orient(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];for(;r[s]<this.adj[s].length;){const a=this.adj[s][r[s]],c=this.key(s,a),l=this.key(a,s);if(!o.has(c)){if(this.oriented.has(c)||this.oriented.has(l)){r[s]++;continue}if(this.oriented.add(c),this.out[s].push(a),this.lowpt.set(c,this.height[s]),this.lowpt2.set(c,this.height[s]),this.height[a]<0){this.parentEdge[a]=c,this.height[a]=this.height[s]+1,t.push(s,a),o.add(c);break}this.lowpt.set(c,this.height[a])}if(this.nesting.set(c,2*this.low(c)+((this.lowpt2.get(c)??0)<this.height[s]?1:0)),i>=0){const u=this.low(i),d=this.lowpt2.get(i)??0,f=this.low(c),h=this.lowpt2.get(c)??0;f<u?(this.lowpt2.set(i,Math.min(u,h)),this.lowpt.set(i,f)):f>u?this.lowpt2.set(i,Math.min(d,f)):this.lowpt2.set(i,Math.min(d,h))}r[s]++}}}conflicting(e,t){return!Ln(e)&&this.low(e.high)>this.low(t)}lowest(e){return Ln(e.left)?this.low(e.right.low):Ln(e.right)?this.low(e.left.low):Math.min(this.low(e.left.low),this.low(e.right.low))}top(){return this.stack.length===0?null:this.stack[this.stack.length-1]}test(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];let a=!1;const c=this.ordered[s];for(;r[s]<c.length;){const l=c[r[s]],u=this.key(s,l);if(!o.has(u)){if(this.stackBottom.set(u,this.top()),u===this.parentEdge[l]){t.push(s,l),o.add(u),a=!0;break}this.lowptEdge.set(u,u),this.stack.push({left:_i(),right:_i(u,u)})}if(this.low(u)<this.height[s]){if(l===c[0])this.lowptEdge.set(i,this.lowptEdge.get(u)??-1);else if(!this.addConstraints(u,i))return!1}r[s]++}!a&&i>=0&&this.removeBackEdges(i)}return!0}addConstraints(e,t){const r={left:_i(),right:_i()};for(;;){const o=this.stack.pop();if(Ln(o.left)||([o.left,o.right]=[o.right,o.left]),!Ln(o.left))return!1;if(this.low(o.right.low)>this.low(t)?(Ln(r.right)?r.right={...o.right}:this.ref.set(r.right.low,o.right.high),r.right.low=o.right.low):this.ref.set(o.right.low,this.lowptEdge.get(t)??-1),this.top()===(this.stackBottom.get(e)??null))break}for(let o=this.top();o!==null&&(this.conflicting(o.left,e)||this.conflicting(o.right,e));o=this.top()){const s=this.stack.pop();if(this.conflicting(s.right,e)&&([s.left,s.right]=[s.right,s.left]),this.conflicting(s.right,e))return!1;this.ref.set(r.right.low,s.right.high),s.right.low>=0&&(r.right.low=s.right.low),Ln(r.left)?r.left={...s.left}:this.ref.set(r.left.low,s.left.high),r.left.low=s.left.low}return Ln(r.left)&&Ln(r.right)||this.stack.push(r),!0}removeBackEdges(e){const t=Math.floor(e/this.n),r=o=>this.ref.get(o)??-1;for(;this.stack.length>0&&this.lowest(this.top())===this.height[t];){const o=this.stack.pop();o.left.low>=0&&this.side.set(o.left.low,-1)}if(this.stack.length>0){const o=this.stack.pop();for(;o.left.high>=0&&this.target(o.left.high)===t;)o.left.high=r(o.left.high);for(o.left.high<0&&o.left.low>=0&&(this.ref.set(o.left.low,o.right.low),this.side.set(o.left.low,-1),o.left.low=-1);o.right.high>=0&&this.target(o.right.high)===t;)o.right.high=r(o.right.high);o.right.high<0&&o.right.low>=0&&(this.ref.set(o.right.low,o.left.low),this.side.set(o.right.low,-1),o.right.low=-1),this.stack.push(o)}if(this.low(e)<this.height[t]){const o=this.top(),s=o.left.high,i=o.right.high;this.ref.set(e,s>=0&&(i<0||this.low(s)>this.low(i))?s:i)}}sign(e){const t=[e],r=new Map;for(;t.length>0;){const o=t.pop()??0,s=this.ref.get(o)??-1;if(s>=0)t.push(o,s),r.set(o,s),this.ref.set(o,-1);else{const i=r.get(o)??-1;this.side.set(o,(this.side.get(o)??1)*(i>=0?this.side.get(i)??1:1))}}return this.side.get(e)??1}embed(e,t){const r=[e],o=new Int32Array(this.n);for(;r.length>0;){const s=r.pop()??0,i=this.ordered[s];for(;o[s]<i.length;){const a=i[o[s]++],c=this.key(s,a);if(c===this.parentEdge[a]){t.addFirst(a,s),this.leftRef.set(s,a),this.rightRef.set(s,a),r.push(s,a);break}(this.side.get(c)??1)===1?t.addCw(a,s,this.rightRef.get(a)??-1):(t.addCcw(a,s,this.leftRef.get(a)??-1),this.leftRef.set(a,s))}}}}function OI(n,e,t,r){const{n:o}=n;if(r.has(e*o+t))return[];r.add(e*o+t);let s=e,i=t;const a=[e],c=new Set(a);let[,l]=n.nextFace(s,i);for(;i!==e||l!==t;)c.has(i)?(n.addCw(s,l,i),n.addCcw(l,s,i),r.add(i*o+l),r.add(l*o+s),i=s):(c.add(i),a.push(i)),s=i,[i,l]=n.nextFace(i,l),r.add(s*o+i);return a}function $I(n,e,t){let[,r]=n.nextFace(e,t),[,o]=n.nextFace(t,r);if(!(e===t||e===r))for(;e!==o;)n.has(e,r)?[e,t,r]=[t,r,o]:(n.addCw(e,r,t),n.addCcw(r,e,t),[t,r]=[r,o]),[,o]=n.nextFace(t,r)}function RI(n){const{n:e}=n,t=new Uint8Array(e),r=[];for(let a=0;a<e;a++)if(t[a]!==1){r.push(a),t[a]=1;for(const c=[a];c.length>0;)for(const l of n.neighboursCw(c.pop()??0))t[l]===0&&(t[l]=1,c.push(l))}for(let a=0;a+1<r.length;a++)n.addFirst(r[a],r[a+1]),n.addFirst(r[a+1],r[a]);let o=[];const s=[],i=new Set;for(let a=0;a<e;a++){const c=n.first[a];if(c<0)continue;let l=c;do{const u=OI(n,a,l,i);u.length>0&&(s.push(u),u.length>o.length&&(o=u)),l=n.cw[a].get(l)??c}while(l!==c)}for(const a of s)a!==o&&$I(n,a[0],a[1]);return o}class DI{constructor(e,t){this.embedding=e,this.ccwNbr=new Map,this.cwNbr=new Map;const{n:r}=e;this.v1=t[0],this.v2=t[1],this.chords=new Int32Array(r),this.marked=new Uint8Array(r),this.ready=new Set(t);let o=this.v2;for(let s=2;s<t.length;s++)this.ccwNbr.set(o,t[s]),o=t[s];this.ccwNbr.set(o,this.v1),o=this.v1;for(let s=t.length-1;s>0;s--)this.cwNbr.set(o,t[s]),o=t[s];for(const s of t)this.countChords(s,null)}run(){const{n:e}=this.embedding,t=new Array(e);t[0]=[this.v1,[]],t[1]=[this.v2,[]],this.ready.delete(this.v1),this.ready.delete(this.v2);for(let r=e-1;r>1;r--){const o=this.ready.values().next().value;this.ready.delete(o),this.marked[o]=1;const[s,i]=this.contourEnds(o),a=this.replaceContour(o,s,i);a.length===2?(this.releaseChord(s),this.releaseChord(i)):this.addInner(new Set(a.slice(1,-1))),t[r]=[o,a]}return t}isOuterNbr(e,t){return this.ccwNbr.get(e)===t||this.cwNbr.get(e)===t}isOnOuter(e){return this.marked[e]===0&&(this.ccwNbr.has(e)||e===this.v1)}countChords(e,t){for(const r of this.embedding.neighboursCw(e))this.isOnOuter(r)&&!this.isOuterNbr(e,r)&&(this.chords[e]++,this.ready.delete(e),t!==null&&!t.has(r)&&(this.chords[r]++,this.ready.delete(r)))}contourEnds(e){let t=-1,r=-1;for(const o of this.embedding.neighboursCw(e))if(this.isOnOuter(o)&&(o===this.v1?t=this.v1:o===this.v2?r=this.v2:this.cwNbr.get(o)===e?t=o:r=o),t>=0&&r>=0)break;return[t,r]}replaceContour(e,t,r){const o=[t];for(let s=t;s!==r;){const i=this.embedding.ccw[e].get(s)??r;o.push(i),this.cwNbr.set(s,i),this.ccwNbr.set(i,s),s=i}return o}releaseChord(e){--this.chords[e]===0&&this.ready.add(e)}addInner(e){for(const t of e)this.ready.add(t),this.countChords(t,e)}}function LI(n,e){return new DI(n,e).run()}function MI(n){const{n:e}=n,t=new Float64Array(2*e);if(e<4){const d=[0,0,2,0,1,1];return t.set(d.slice(0,2*e)),t}const r=LI(n,RI(n)),o=new Int32Array(e).fill(-1),s=new Int32Array(e).fill(-1),i=new Float64Array(e),a=new Float64Array(e),[c,l,u]=[r[0][0],r[1][0],r[2][0]];s[c]=u,i[l]=1,i[u]=1,a[u]=1,s[u]=l;for(let d=3;d<e;d++){const[f,h]=r[d],g=h[0],w=h[1],p=h[h.length-1],m=h[h.length-2],y=h.length>2;i[w]+=1,i[p]+=1;let b=0;for(let v=1;v<h.length;v++)b+=i[h[v]];i[f]=Math.floor((-a[g]+b+a[p])/2),a[f]=Math.floor((a[g]+b+a[p])/2),i[p]=b-i[f],y&&(i[w]-=i[f]),s[g]=f,s[f]=p,y?(o[f]=w,s[m]=-1):o[f]=-1}t[2*c+1]=a[c];for(const d=[c];d.length>0;){const f=d.pop()??0;for(const h of[o[f],s[f]])h>=0&&(t[2*h]=t[2*f]+i[h],t[2*h+1]=a[h],d.push(h))}return t}function UI(n){const e=[];for(let t=0;t<n.nodeCount;t++){const r=[];for(let o=n.rowPtr[t];o<n.rowPtr[t+1];o++){const s=n.colIdx[o];s!==t&&s!==r[r.length-1]&&r.push(s)}e.push(r)}return e}function FI(n,e,t){const r=new TI(UI(n)).run();if(r===null)throw Object.assign(new Error("G is not planar."),{code:"E_NOT_PLANAR",params:{nodeCount:n.nodeCount,edgeCount:n.edgeCount}});return Jn(MI(r),2,e,t)}function BI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(FI(co(n),o,s),r,s),r,t)}function sw(n,e,t,r,o=0){const s=new Float64Array(2*n).fill(Number.NaN);if(e.length===0)return s;const i=o==="networkx"?Math.PI/e.length:o;if(!Number.isFinite(i))throw ze(new TypeError(`rotate must be a finite number of radians or "networkx", not ${String(o)}`),"E_BAD_OPTION",{option:"rotate",value:o});const a=t/e.length;let c=a;return e[0].length===1&&(s[2*e[0][0]]=r[0],s[2*e[0][0]+1]=r[1]),e.forEach((l,u)=>{if(l.length===0||u===0&&l.length===1)return;const d=ds.linspace(0,2*Math.PI,l.length+1),f=(u+1)*i;for(let h=0;h<l.length;h++)s[2*l[h]]=yn(d[h]+f)*c+r[0],s[2*l[h]+1]=Jt(d[h]+f)*c+r[1];c+=a}),s}function zI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{nlist:i}=e,a=typeof i=="string"?Kg(n,i,"nlist"):i?.map(c=>ss(n,c))??[Array.from({length:t},(c,l)=>l)];for(const c of a)for(let l=0;l<c.length;l++)if(!Number.isInteger(c[l])||c[l]<0||c[l]>=t)throw ze(new Error(`shell node index ${String(c[l])} is not a node of the graph`),"E_BAD_NODE",{option:"nlist",index:c[l]});return Wt(Rn(sw(t,a,o,s,e.rotate),r,s),r,t)}function GI(n,e){const t=new Map;for(let r=n.rowPtr[e];r<n.rowPtr[e+1];r++)t.has(n.colIdx[r])||t.set(n.colIdx[r],n.arcToEdge[r]);return[...t.keys()].sort((r,o)=>(t.get(r)??0)-(t.get(o)??0))}function WI(n,e){const t=n.nodeCount,r=new Int32Array(t).fill(-1);if(t===0)return{rings:[],parent:r};if(e===null){let a=0,c=-1;for(let l=0;l<t;l++){let u=0;for(let d=n.rowPtr[l];d<n.rowPtr[l+1];d++)(d===n.rowPtr[l]||n.colIdx[d]!==n.colIdx[d-1])&&u++;u>c&&(a=l,c=u)}e=a}else if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`root node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"root",index:e});const o=new Uint8Array(t);o[e]=1;const s=[[e]];for(let a=s[0];a.length>0;){const c=[];for(const l of a)for(const u of GI(n,l))o[u]===0&&(o[u]=1,r[u]=l,c.push(u));c.length>0&&s.push(c),a=c}const i=[];for(let a=0;a<t;a++)o[a]===0&&i.push(a);return i.length>0&&s.push(i),{rings:s,parent:r}}function VI(n,e,t,r){const o=new Float64Array(n);for(let s=r-1;s>=0;s--)for(const i of e[s])o[i]||=1,s>0&&(o[t[i]]+=o[i]);return o}function jI(n,e,t,r,o){const s=new Float64Array(2*n);if(n===0)return s;const i=e.length>1?r/(e.length-1):0,a=e.at(-1)??[],c=e.length>1&&t[a[0]]===-1?e.length-1:e.length,l=VI(n,e,t,c),u=new Float64Array(n),d=new Float64Array(n),f=new Float64Array(n);d[e[0][0]]=2*Math.PI,c>1&&e[1].length===1&&(u[e[0][0]]=Math.PI/4-Math.PI);const h=(g,w,p)=>{s[2*g]=yn(p)*w+o[0],s[2*g+1]=Jt(p)*w+o[1]};h(e[0][0],0,0);for(let g=1;g<c;g++){const w=2*Of(g/(g+1));for(const p of e[g]){const m=t[p],y=d[m]*l[p]/l[m],b=u[m]+f[m]+y/2;f[m]+=y,h(p,g*i,b),d[p]=Math.min(y,w),u[p]=b-d[p]/2}}return c<e.length&&a.forEach((g,w)=>{h(g,r,2*Math.PI*w/a.length)}),s}function qI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=e.root??null,{arrangement:a="rings",rotate:c}=e;if(a!=="rings"&&a!=="sectors")throw ze(new Error(`arrangement must be "rings" or "sectors", not ${String(a)}`),"E_BAD_OPTION",{option:"arrangement",value:a});if(a==="sectors"&&c!==void 0&&c!==0)throw ze(new Error('rotate turns each ring separately, which only arrangement: "rings" allows'),"E_BAD_OPTION",{option:"rotate",value:c});const{rings:l,parent:u}=WI(co(n),i===null?null:xe(n,i));if(a==="sectors")return Wt(Rn(jI(t,l,u,o,s),r,s),r,t);const d=l.length>1?l.length/(l.length-1):1;return Wt(Rn(sw(t,l,o*d,s,c),r,s),r,t)}class iw{constructor(e){this.seed=e??Math.floor(Math.random()*1e6),this.m=34359738337,this.a=185852,this.c=1,this._state=this.seed%this.m}_next(){return this._state=(this.a*this._state+this.c)%this.m,this._state/this.m}rand(e=null){if(e===null)return this._next();if(typeof e=="number"){const r=[];for(let o=0;o<e;o++)r.push(this._next());return r}if(e.length===1){const r=[];for(let o=0;o<e[0];o++)r.push(this._next());return r}const t=[];for(let r=0;r<e[0];r++)t.push(this.rand(e.slice(1)));return t}}function HI(n,e,t,r,o){const s=new iw(o??void 0),i=new Float64Array(n*e);for(let a=0;a<n*e;a++)i[a]=s.rand()*t+r[a%e];return i}function KI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(HI(t,r,o,s,e.seed??null),r,t)}const YI=1e-9,XI=5e3;function QI(n,e,t,r,o){const s=n.nodeCount,i=new Float64Array(s*e);if(s<=2){for(let w=0;w<s;w++){const p=w===0?-t:t;for(let m=0;m<e;m++)i[e*w+m]=s===1?r[m]:r[m]+p}return i}const{rowPtr:a,colIdx:c}=n,l=(w,p)=>c[p]!==w&&(p===a[w]||c[p]!==c[p-1]),u=new Float64Array(s);for(let w=0;w<s;w++)for(let p=a[w];p<a[w+1];p++)u[w]+=l(w,p)?1:0;const d=w=>{const p=new Float64Array(s);for(let m=0;m<s;m++){let y=u[m]*w[m];for(let b=a[m];b<a[m+1];b++)l(m,b)&&(y-=w[c[b]]);p[m]=y}return p},f=YI*2*Math.max(1,...u),h=new iw(o??void 0),g=[new Float64Array(s).fill(1/Math.sqrt(s))];for(let w=0;w<e;w++){const p=Float64Array.from({length:s},()=>h.rand()-.5),m=aw(p,g)?JI(d,p,g,f):p.fill(0);g.push(m);for(let y=0;y<s;y++)i[e*y+w]=m[y]}Jn(i,e,t);for(let w=0;w<s*e;w++)i[w]+=r[w%e];return i}function JI(n,e,t,r){let o=n(e),s=null;for(let i=0;i<XI;i++){const a=Qc(e,o),c=o.map((p,m)=>p-a*e[m]);if(Jc(c)<r)break;const l=[e];for(const p of s===null?[c]:[c,s])aw(p,[...t,...l])&&l.push(p);const u=[o,...l.slice(1).map(n)],d=l.map(p=>u.map(m=>Qc(p,m))),f=ZI(d),h=new Float64Array(e.length),g=new Float64Array(e.length),w=new Float64Array(e.length);l.forEach((p,m)=>{for(let y=0;y<e.length;y++)h[y]+=f[m]*p[y],g[y]+=f[m]*u[m][y],m>0&&(w[y]+=f[m]*p[y])}),e.set(h),o=g,s=w}return e}function ZI(n){const e=n.length,t=n.map((o,s)=>n.map((i,a)=>s===a?1:0));for(let o=0;o<50;o++)for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)ek(n,t,s,i);let r=0;for(let o=1;o<e;o++)n[o][o]<n[r][r]&&(r=o);return t.map(o=>o[r])}function ek(n,e,t,r){if(Math.abs(n[t][r])<1e-300)return;const o=(n[r][r]-n[t][t])/(2*n[t][r]),s=Math.sign(o||1)/(Math.abs(o)+Math.sqrt(o*o+1)),i=1/Math.sqrt(s*s+1),a=s*i;for(const c of[n,e])for(const l of c)[l[t],l[r]]=[i*l[t]-a*l[r],a*l[t]+i*l[r]];[n[t],n[r]]=[n[t].map((c,l)=>i*c-a*n[r][l]),n[t].map((c,l)=>a*c+i*n[r][l])]}function aw(n,e){const t=Jc(n);for(let o=0;o<2;o++)for(const s of e){const i=Qc(n,s);for(let a=0;a<n.length;a++)n[a]-=i*s[a]}const r=Jc(n);if(r<=1e-8*t)return!1;for(let o=0;o<n.length;o++)n[o]/=r;return!0}function Qc(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function Jc(n){let e=0;for(const t of n)e+=t*t;return Math.sqrt(e)}function tk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(QI(co(n),r,o,s,e.seed??null),r,t)}function nk(n,e,t,r,o){const s=new Float64Array(2*n);if(o){let c=r;c+=1/(.5*c);for(let l=0;l<n;l++){const u=.5*c;c+=1/u,s[2*l]=yn(c)*u,s[2*l+1]=Jt(c)*u}}else for(let i=0;i<n;i++)s[2*i]=yn(r*i)*i,s[2*i+1]=Jt(r*i)*i;return Jn(s,2,e,t)}function rk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=nk(t,o,s,e.resolution??.35,e.equidistant??!1);return Wt(Rn(i,r,s),r,t)}function ok(n,e,t){switch(n){case"forceatlas2":return t?.forceAtlas2!==void 0?t.forceAtlas2(e):new uI(e);case"fruchtermanReingold":case"spring":return t?.fruchtermanReingold!==void 0?t.fruchtermanReingold(e):new wI(e);case"spring-electrical":if(t?.springElectrical===void 0)throw new Error('createSimulation: "spring-electrical" has no CPU simulation; inject an accelerator that implements springElectrical');return t.springElectrical(e);default:{const r=n;throw new Error(`createSimulation: unknown simulation type ${String(r)}`)}}}const sk={animate:!1,animationDuration:500,fit:!0,padding:30,randomize:!0,refresh:1};function ik(n,e){const t=new Map;return n.nodes.forEach((o,s)=>{const i=o.data(e);if(typeof i=="number"||typeof i=="string"){const a=t.get(i);a===void 0?t.set(i,[s]):a.push(s)}}),[...t.keys()].sort((o,s)=>typeof o=="number"&&typeof s=="number"?o-s:String(o).localeCompare(String(s))).map(o=>t.get(o)??[])}const cw={random:(n,e)=>KI(n,e),circular:(n,e)=>eI(n,e),spiral:(n,e)=>rk(n,e),grid:(n,e)=>mI(n,e),spectral:(n,e)=>tk(n,e),planar:(n,e)=>BI(n,e),arf:(n,e)=>H_(n,e),"kamada-kawai":(n,e)=>CI(n,e),shell:(n,e,t)=>{const r=e.nlist;return zI(n,{...e,nlist:r?.map(o=>Gt(t,o))})},multipartite:(n,e,t)=>{const r=e.subsets??"subset",o=typeof r=="string"?ik(t,r):r.map(s=>Gt(t,s));return K_(n,{...e,subsets:o})},bipartite:(n,e,t)=>{if(e.top===void 0)return Yg(n,e);const r=At(n.nodeCount);for(const o of Gt(t,e.top))pn(r,o,!0);return Yg(n,{...e,top:r})},bfs:(n,{root:e,...t},r)=>X_(n,{...t,start:ao(r,e,"graphty layout: root")}),radial:(n,e,t)=>qI(n,{...e,root:ao(t,e.root,"graphty layout: root")})},ak={forceatlas2:{maxIter:100},fruchtermanReingold:{iterations:50}},lw={forceatlas2:"forceatlas2","fruchterman-reingold":"fruchtermanReingold","spring-electrical":"spring-electrical"},ck=[...Object.keys(cw),...Object.keys(lw)];function uw(n,e){if(n===void 0){const t=r=>Number.isFinite(r)?r:1;return{x1:0,y1:0,w:t(e.width()),h:t(e.height())}}return"w"in n?n:{x1:n.x1,y1:n.y1,w:n.x2-n.x1,h:n.y2-n.y1}}function Zc(n){return{radius:Math.max(Math.min(n.w,n.h)/2,1),center:[n.x1+n.w/2,n.y1+n.h/2,0]}}function dw(n,e,t,r){const o=new Float64Array(2*t);for(let a=0;a<t;a++)o[2*a]=n[e*a],o[2*a+1]=n[e*a+1];const{radius:s,center:i}=Zc(r);return Jn(o,2,s,i)}function lk(n,e,t,r){let o=0,s=0,i=0;for(let f=0;f<t;f++)_e(e,f)&&(o+=n[3*f],s+=n[3*f+1],i++);o/=i,s/=i;const a=o>=r.x1&&o<=r.x1+r.w&&s>=r.y1&&s<=r.y1+r.h,c=(f,h,g,w)=>h===0?1/0:((h>0?w:g)-f)/h;let l=1/0,u=0;for(let f=0;f<t;f++)if(!_e(e,f)){const h=n[3*f]-o,g=n[3*f+1]-s;l=Math.min(l,c(o,h,r.x1,r.x1+r.w),c(s,g,r.y1,r.y1+r.h)),u=Math.max(u,Math.hypot(h,g))}a?Number.isFinite(l)||(l=1):l=u>0?Zc(r).radius/u:1;const d=new Float64Array(2*t);for(let f=0;f<t;f++){const h=_e(e,f)?1:l;d[2*f]=o+h*(n[3*f]-o),d[2*f+1]=s+h*(n[3*f+1]-s)}return d}function uk(n,e){const t={};for(const r of["nodeMass","nodeSize"]){const o=e[r];if(Array.isArray(o)||ArrayBuffer.isView(o)&&!(o instanceof Float32Array))t[r]=Float32Array.from(o);else if(typeof o=="string"){const s={};n.nodes.forEach(i=>{const a=i.data(o);typeof a=="number"&&Number.isFinite(a)&&(s[i.id()]=a)}),t[r]=s}}return t}function fw(n){return(e,t)=>Number.isNaN(n[2*t])?e.position():{x:n[2*t],y:n[2*t+1]}}function hw(n,e,t){const r=fw(t);e.layoutPositions(n,n.options,r)}function gw(n){return{...n,dim:n.dim??2,scale:1,center:void 0,seed:n.seed??null,weight:n.weight!==void 0}}function ww(n){return hi(n.eles.not(":parent"),{weight:n.weight})}function pw(n,e){if((e?n.animate!==!0&&!!n.animate:!!n.animate)&&!n.cy.styleEnabled())throw new Error(`${n.name}: animate needs a core that renders; create a headless core with styleEnabled: true, or pass animate: false`)}function dk(n,e){const t=n.options;pw(t,!1);const r=ww(t),o=e(r.snapshot,gw(t),r);hw(n,r.nodes,dw(o.positions,o.dim,o.n,uw(t.boundingBox,t.cy)))}function mw(n,e){for(;!n.settled&&!e.stopped&&!e.options.cy.destroyed();){const t=n.step(50);if(t instanceof Promise)return t.then(()=>mw(n,e))}}function fk(n,e){const t=n.options;if(pw(t,!0),$c(t.name,t.gpu),n.stopped=!1,t.accelerator!==void 0){n.backend=t.accelerator===null?{ran:"cpu",reason:"accelerator: null was passed",device:null}:{ran:"gpu",reason:null,device:t.accelerator.kind},tl(n,e,t.accelerator);return}const r=t.gpu==="require"?null:xg(t.gpu);if(r!==null){n.backend=Lc(r,!1,""),Dc(r,t.eles.nodes().length),tl(n,e,null);return}n.looping=!0,Cg(t.cy,t.gpu).then(o=>{if(n.looping=!1,n.backend=Lc(o,o.gpu!==null,""),Dc(o,t.eles.nodes().length),n.stopped||t.cy.destroyed()){n.emit({type:"layoutstop",layout:n});return}tl(n,e,o.gpu?.accelerator??null)}).catch(o=>{n.looping=!1,t.cy.destroyed()||n.emit("layouterror",[o]),n.emit({type:"layoutstop",layout:n})})}const el=new WeakMap;function yw(n,e){let t=0,r=0;for(let o=0;o<e;o++)t+=n[3*o],r+=n[3*o+1];return e===0?[0,0,0]:[t/e,r/e,0]}function tl(n,e,t){const r=n.options;if(t===null&&e==="spring-electrical"){const O=n.backend?.reason??"none was available";n.backend=void 0;const T=new Error(`graphty-spring-electrical has no CPU simulation and runs only on the GPU; no GPU ran because ${O}`);bw(n,T);return}const o=ww(r),s=o.snapshot,i=s.nodeCount,a=uw(r.boundingBox,r.cy),{radius:c,center:l}=Zc(a),u=r.dim??2,d=new Float32Array(3*i),f=At(i),h=new Vg(r.seed??null);let g=!1;o.nodes.forEach((O,T)=>{const $=O.locked();g||=$,pn(f,T,$);const L=O.position(),F=$||r.randomize===!1;d[3*T]=F?L.x:a.x1+h.next()*a.w,d[3*T+1]=F?L.y:a.y1+h.next()*a.h,d[3*T+2]=F||u===2?0:(h.next()*2-1)*c});const w=r.randomize===!1&&!g?el.get(r.cy)?.get(e):void 0,p=w??c,m=ok(e,{...ak[e],...gw(r),...uk(o,r),scale:p,center:w===void 0?l:yw(d,i),iterationsPerStep:1},t);m.load(s,d),g&&m.setFixed(f);const y=bg(s),b=()=>{if(m.dispose(),y(),!g){const[O,T]=yw(d,i);let $=0;for(let L=0;L<i;L++)$=Math.max($,Math.hypot(d[3*L]-O,d[3*L+1]-T));if($>0){const L=el.get(r.cy)??new Map;L.set(e,p*c/$),el.set(r.cy,L)}}},v=()=>g?lk(d,f,i,a):dw(d,3,i,a),A=O=>{n.looping=!1,b(),r.cy.destroyed()||n.emit("layouterror",[O]),n.emit({type:"layoutstop",layout:n})};if(r.animate!==!0){const O=()=>{n.looping=!1,b(),r.cy.destroyed()?n.emit({type:"layoutstop",layout:n}):hw(n,o.nodes,v())},T=mw(m,n);T===void 0?O():(n.looping=!0,T.then(O,A));return}n.looping=!0,n.emit({type:"layoutstart",layout:n});let E=!0;const I=typeof requestAnimationFrame=="function"?requestAnimationFrame:O=>setTimeout(O,16),k=()=>{n.looping=!1,b(),r.stop!==void 0&&n.one("layoutstop",r.stop),n.emit({type:"layoutstop",layout:n})},N=()=>{if(r.cy.destroyed()){k();return}o.nodes.positions(fw(v())),r.fit!==!1&&r.cy.fit(r.eles,r.padding),E&&(E=!1,r.ready!==void 0&&n.one("layoutready",r.ready),n.emit({type:"layoutready",layout:n})),m.settled||n.stopped?k():I(C)},C=()=>{if(n.stopped||r.cy.destroyed()){N();return}let O;try{O=m.step(r.refresh??1)}catch(T){A(T);return}O instanceof Promise?O.then(N,A):N()};C()}function bw(n,e){n.looping=!0,Promise.resolve().then(()=>{n.looping=!1,n.emit("layouterror",[e]),n.emit({type:"layoutstop",layout:n})})}const vw=new WeakMap;function hk(){return this.options.cy.destroyed()?bw(this,cs()):vw.get(this)?.(this),this}function gk(){return this.looping?this.stopped=!0:this.emit({type:"layoutstop",layout:this}),this}function Aw(n,e){function t(o){this.options={...sk,...o},this.stopped=!1,this.looping=!1,vw.set(this,n)}const r={run:hk};return e&&(r.stop=gk),Object.assign(t.prototype,r),t}function wk(n){for(const[e,t]of Object.entries(cw))n("layout",`graphty-${e}`,Aw(r=>{dk(r,t)},!1));for(const[e,t]of Object.entries(lw))n("layout",`graphty-${e}`,Aw(r=>{fk(r,t)},!0))}const Ew=Symbol.for("@graphty/cytoscape-extensions");function pk(n){const e=n;e[Ew]!==!0&&(e[Ew]=!0,wk(n),R_(n),U_(n))}const _w=Object.assign(pk,{ALGORITHM_NAMES:T_,ASYNC_ALGORITHM_NAMES:O_,configureWebGpu:b_,GPU_SIZE_FLOOR:Ag,LAYOUT_NAMES:ck,toSnapshot:hi,writeData:io}),{cytoscape:Iw}=globalThis;typeof Iw=="function"&&Iw.use(_w);const nl=256,lo=65535,rl=lo*nl,Ve=4294967295,Ii=256,uo=64,ki=256,Vt=256,kw=32768,mk=3,yk=256,Sw=16*1024*1024,bk=4,vk=4*1024,Ak=64*1024*1024,Pw=16*1024*1024,xw=2,Rt=256,fo=32,jt=256,Cw=64,Cr=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),nr=Object.freeze({repulsion:"auto",exactMaxNodes:kw,nearMax:64,deterministic:!0,gridMax2D:512,gridMax3D:128,extentFactor:6,compat:"paper"}),Ek=.01,_k=1e-4,Ik=1e-8,Nw=128,ol=1,Tw=2,Si=.1,kk=.7,Sk=.9,Pk=5,xk=1e4,Ck=Object.freeze({k:null,iterations:50,fixed:null,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2,cooling:"linear"}),Nk=300,sl=Object.freeze({springLength:10,springCoefficient:.8,gravity:-12,dragCoefficient:.9,timeStep:.5,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),Ow=Object.freeze({springElectrical:.003,fruchtermanReingold:.002}),Tk=2e3,Ok=2**128-2**104,$w=8,Rw=4,Dw=1024,Lw=1e-6,Mw=1.01,$k=24,$e=32,Rk=4096,Dk=2,Lk=24,Mk=32,ho=2139095040,Uk=.25,Fk=256,Bk=2,zk=100,Gk=256,Pi=64,il=32,Wk=4096,Uw=8,Nr=4,Vk=2147483648,jk=32,al=128,cl=65e3,Fw=2,qk=32,Hk=Object.freeze({});class S extends Error{constructor(e,t,r){super(t),this.name="WebGpuGraphError",this.code=e,this.details=r===void 0?Hk:Object.freeze({...r})}}function go(n){if(typeof n!="object"||n===null)return!1;const e=n;return e.name==="WebGpuGraphError"&&typeof e.code=="string"}function xi(n,e){return go(n)&&n.code===e}const Bw=Object.freeze(["maxBufferSize","maxStorageBufferBindingSize","maxStorageBuffersPerShaderStage","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX"]),Kk=["maxTextureDimension1D","maxTextureDimension2D","maxTextureDimension3D","maxTextureArrayLayers","maxBindGroups","maxBindGroupsPlusVertexBuffers","maxBindingsPerBindGroup","maxDynamicUniformBuffersPerPipelineLayout","maxDynamicStorageBuffersPerPipelineLayout","maxSampledTexturesPerShaderStage","maxSamplersPerShaderStage","maxStorageBuffersPerShaderStage","maxStorageBuffersInVertexStage","maxStorageBuffersInFragmentStage","maxStorageTexturesPerShaderStage","maxStorageTexturesInVertexStage","maxStorageTexturesInFragmentStage","maxUniformBuffersPerShaderStage","maxUniformBufferBindingSize","maxStorageBufferBindingSize","minUniformBufferOffsetAlignment","minStorageBufferOffsetAlignment","maxVertexBuffers","maxBufferSize","maxVertexAttributes","maxVertexBufferArrayStride","maxInterStageShaderVariables","maxColorAttachments","maxColorAttachmentBytesPerSample","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeWorkgroupsPerDimension","maxImmediateSize"],zw=new WeakSet;function Gw(n){return n instanceof Error?n.message:String(n)}function Ww(n){return n.architecture==="software"||n.architecture==="swiftshader"||n.architecture==="warp"||n.isFallbackAdapter===!0}function wo(n){const{info:e}=n,t=n.limits,r={};for(const o of Kk){const s=t[o];typeof s=="number"&&(r[o]=s)}return Object.freeze({vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description,software:Ww(e),subgroupMinSize:e.subgroupMinSize??0,subgroupMaxSize:e.subgroupMaxSize??0,features:Object.freeze(Array.from(n.features).sort()),limits:Object.freeze(r)})}async function Vw(n,e){let t;try{t=await n.requestAdapter({powerPreference:e})}catch(r){const o=`requestAdapter() threw: ${Gw(r)}`;throw new S("E_NO_ADAPTER",o,{reason:o})}if(t===null){const r="requestAdapter() returned null: no usable WebGPU adapter";throw new S("E_NO_ADAPTER",r,{reason:r})}return t}function Yk(n,e){const t={};if(e==="default")return t;if(e==="raise"){for(const r of Bw)t[r]=n.limits[r];return t}for(const r of Bw){const o=e[r];if(o===void 0)continue;const s=n.limits[r];if(o>s)throw new S("E_NO_DEVICE",`requested ${r} = ${o} exceeds the adapter's ${s}`,{reason:"limit",adapter:wo(n),limit:r,requested:o,available:s});t[r]=o}return t}function Xk(n,e,t){const r=[];for(const o of e){if(!n.features.has(o))throw new S("E_NO_DEVICE",`required feature "${o}" is not supported by the adapter`,{reason:"feature",adapter:wo(n),requested:o});r.includes(o)||r.push(o)}for(const o of t)n.features.has(o)&&!r.includes(o)&&r.push(o);return r}function jw(n,e){return new S("E_NO_DEVICE",`the adapter already created a device (an adapter is consumed by one requestDevice, spec 2.2 step 1): ${e}`,{reason:"consumed",adapter:wo(n)})}async function Qk(n,e){if(zw.has(n))throw jw(n,"recorded by this package");let t;try{t=await n.requestDevice(e)}catch(r){const o=Gw(r);throw/consumed|already been used/i.test(o)?jw(n,o):new S("E_NO_DEVICE",`requestDevice() rejected: ${o}`,{reason:"requestDevice",adapter:wo(n)})}return zw.add(n),t}function Jk(n,e,t,r){const o=new Set(n.features),s=o.has("subgroups");return{limits:n.limits,features:o,wgslFeatures:new Set(r),subgroupMinSize:s?e.subgroupMinSize??0:0,subgroupMaxSize:s?e.subgroupMaxSize??0:0,software:Ww(e),runtime:t,vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description}}function qw(n,e){const t=new Set(n.features),r=t.has("subgroups");return{limits:n.limits,features:t,wgslFeatures:e?.wgslFeatures??new Set,subgroupMinSize:r?e?.subgroupMinSize??0:0,subgroupMaxSize:r?e?.subgroupMaxSize??0:0,software:e?.software??!1,runtime:e?.runtime??"unknown",vendor:e?.vendor??"",architecture:e?.architecture??"",device:e?.device??"",description:e?.description??""}}function ll(n){const e=Math.min(nl,n.limits.maxComputeInvocationsPerWorkgroup);let t=1;for(;t*2<=e;)t*=2;return t}function ul(n){const e=n.limits.maxComputeWorkgroupsPerDimension;if(e!==lo)throw new S("E_NO_DEVICE",`maxComputeWorkgroupsPerDimension is ${e}; the dispatch planner and the WGSL prelude bake ${lo}`,{reason:"maxComputeWorkgroupsPerDimension",adapter:null,requested:lo,available:e});const t=ll(n);if(t<64)throw new S("E_NO_DEVICE",`the device allows a workgroup of ${t} invocations; the kernels need a power of two >= 64`,{reason:"limit",adapter:null,limit:"maxComputeInvocationsPerWorkgroup",requested:64,available:t})}function Zk(n,e){return n.messages.map(t=>{if(t.lineNum===0)return`${t.type} ${t.message}`;const r=t.lineNum-e;return r>=1?`${t.type} ${r}:${t.linePos} ${t.message}`:`${t.type} prelude:${t.lineNum}:${t.linePos} ${t.message}`})}class eS{constructor(e,t){this.live=new Map,this.residentBytes=0,this.pending=[],this.failure=null,this.serial=0,this.device=e,this.threshold=t??Sw}createBuffer(e){this.serial+=1;const t=e.label===void 0||e.label===""?`buffer-${this.serial}`:e.label,{size:r}=e,o=r>=this.threshold;o&&this.device.pushErrorScope("out-of-memory");const s=this.device.createBuffer({...e,label:t});if(this.live.set(s,r),this.residentBytes+=r,o){const i=this.device.popErrorScope().then(a=>{a!==null&&(this.live.has(s)&&(this.live.delete(s),this.residentBytes-=r),this.failure===null&&(this.failure=new S("E_OUT_OF_MEMORY",`out of memory creating "${t}" (${r} bytes, ${this.residentBytes} resident): ${a.message}`,{requested:r,resident:this.residentBytes,label:t})))},()=>{});this.pending.push(i)}return s}destroy(e){const t=this.live.get(e);t!==void 0&&(this.live.delete(e),this.residentBytes-=t),e.destroy()}async check(){for(;this.pending.length>0;){const e=this.pending.splice(0);await Promise.all(e)}if(this.failure!==null)throw this.failure}reset(){this.failure=null}get resident(){return this.residentBytes}get liveBuffers(){return this.live.size}}class tS{constructor(){this.queue=[]}set(e){this.queue.push(e)}take(){if(this.queue.length===0)return null;const e=this.queue.splice(0);let t=null;for(let r=e.length-1;r>=0;r-=1){const o=e[r];t=t===null?o:new S(o.code,o.message,{...o.details,next:t})}return t}get pending(){return this.queue.length>0}}function nS(n,e){const{message:t}=n;return n.constructor.name==="GPUOutOfMemoryError"?new S("E_OUT_OF_MEMORY",`uncaptured out-of-memory error on "${e}": ${t}`,{requested:0,resident:0,label:e}):new S("E_VALIDATION",`uncaptured validation error on "${e}": ${t}`,{label:e,message:t})}function rS(n,e,t){let r=!0;const o=n.label??"",s=i=>{if(!r)return;const a=nS(i.error,o);t!==null?t(a):e.set(a)};return n.addEventListener("uncapturederror",s),()=>{r=!1,typeof n.removeEventListener=="function"&&n.removeEventListener("uncapturederror",s)}}function oS(n,e){let t=!1;return n.lost.then(r=>(t||(t=!0,e(r)),r))}function Hw(n){return new S("E_DEVICE_LOST",`device lost (${n.reason}): ${n.message}`,{reason:n.reason,message:n.message})}const dl=16,sS=32,Kw=new WeakMap;let Yw=1;function iS(n){let e=Kw.get(n);return e===void 0&&(e=Yw,Yw+=1,Kw.set(n,e)),e}function aS(n,e){return n.offset<e.offset+e.size&&e.offset<n.offset+n.size}class cS{constructor(e,t,r,o,s){this.cache=new Map,this.device=e,this.spec=t,this.pipeline=o,this.layouts=s,this.workgroupSize=r.overrides.WG,this.entryPoint=r.entryPoint;const i=s.map(()=>[]);for(const a of t.bindings)i[a.group].push(a);for(const a of i)a.sort((c,l)=>c.binding-l.binding);this.groups=i,this.dynamicCounts=i.map(a=>a.filter(c=>c.kind==="uniform").length)}bind(e){const{id:t}=this.spec,r=new Map(this.spec.bindings.map(d=>[d.name,d]));for(const d of Object.keys(e))if(!r.has(d))throw new S("E_INVALID_ARGUMENT",`${t}: no binding named "${d}"`,{argument:"bindings",value:d,expected:[...r.keys()].join(", ")});const o=[];for(const d of this.spec.bindings){const f=e[d.name];if(f===void 0)throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" is missing`,{argument:"bindings",value:d.name,expected:"a Binding for every declared name"});if(!(Number.isInteger(f.size)&&f.size>0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has size ${f.size}`,{argument:d.name,value:f.size,expected:"size > 0 (a zero-length buffer is never bound)"});if(!(Number.isInteger(f.offset)&&f.offset>=0&&f.offset%ki===0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has offset ${f.offset}`,{argument:d.name,value:f.offset,expected:`a multiple of ${ki} (spec 2.6: the offset alignment the package always honours)`});o.push({decl:d,binding:f})}for(let d=0;d<o.length;d++)for(let f=d+1;f<o.length;f++){const h=o[d],g=o[f];if(!(h.binding.buffer!==g.binding.buffer||!(h.decl.kind==="storage"||g.decl.kind==="storage"))){if(h.decl.kind!==g.decl.kind)throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind one buffer with different access modes (writable usage next to another usage)`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"one access mode per buffer when a slot is read_write",reason:"usage"});if(aS(h.binding,g.binding))throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind intersecting ranges of one read_write buffer`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"disjoint ranges",reason:"range"})}}const s=o.map(({binding:d})=>`${iS(d.buffer)}:${d.offset}:${d.size}`).join("|"),i=this.cache.get(s);if(i!==void 0)return this.cache.delete(s),this.cache.set(s,i),i;const a=new Map(o.map(({decl:d,binding:f})=>[d.name,f])),c=this.layouts.map((d,f)=>this.device.createBindGroup({label:`${t}/${f}`,layout:d,entries:this.groups[f].map(h=>{const g=a.get(h.name);return{binding:h.binding,resource:{buffer:g.buffer,offset:g.offset,size:g.size}}})})),l=[];this.dynamicCounts.forEach((d,f)=>{d>0&&l.push(f)});const u=Object.freeze({kernel:this,bindGroups:Object.freeze(c),dynamicGroups:Object.freeze(l)});return this.cache.set(s,u),this.cache.size>sS&&this.cache.delete(this.cache.keys().next().value),u}dispatch(e,t,r,o){this.check(t,o),r.x!==0&&(this.setUp(e,t,o),e.dispatchWorkgroups(r.x,r.y,r.z))}dispatchIndirect(e,t,r,o,s){if(this.check(t,s),!Number.isInteger(o)||o<0||(o+1)*dl>r.size)throw new S("E_INVALID_ARGUMENT",`${this.spec.id}: args slot ${o} is outside the binding`,{argument:"slot",value:o,expected:`0 <= slot < ${Math.floor(r.size/dl)}`});this.setUp(e,t,s),e.dispatchWorkgroupsIndirect(r.buffer,r.offset+dl*o)}check(e,t){const{id:r}=this.spec;if(e.kernel!==this)throw new S("E_INVALID_ARGUMENT",`${r}: the bound kernel belongs to "${e.kernel.spec.id}"`,{argument:"bound",value:e.kernel.spec.id,expected:r});if(t!==void 0&&t.length!==e.dynamicGroups.length)throw new S("E_INVALID_ARGUMENT",`${r}: ${t.length} dynamic offsets for ${e.dynamicGroups.length} dynamic groups`,{argument:"dynamicOffsets",value:t.length,expected:e.dynamicGroups.length})}setUp(e,t,r){e.setPipeline(this.pipeline);let o=0;t.bindGroups.forEach((s,i)=>{const a=this.dynamicCounts[i];if(a>0){const c=r?.[o]??0;o+=1;const l=[];for(let u=0;u<a;u++)l.push(c);e.setBindGroup(i,s,l)}else e.setBindGroup(i,s)})}invalidate(){this.cache.clear()}}const Se=Object.freeze({MAP_READ:1,MAP_WRITE:2,COPY_SRC:4,COPY_DST:8,INDEX:16,VERTEX:32,UNIFORM:64,STORAGE:128,INDIRECT:256,QUERY_RESOLVE:512}),Xw=Object.freeze({READ:1,WRITE:2}),Qw=Object.freeze({VERTEX:1,FRAGMENT:2,COMPUTE:4});function Tr(n){if(!Number.isFinite(n))throw new S("E_INVALID_ARGUMENT",`wgslF32Literal: ${n} is not a finite number`,{argument:"value",value:n,expected:"a finite number"});const e=String(n);return/[.e]/.test(e)?e:`${e}.0`}const Jw=`// ---- prelude: constants, standard overrides, helpers (every module receives this text first)
2
2
  const INVALID_INDEX: u32 = ${x}u;
3
3
  const U32_MAX: u32 = ${Ve}u;
4
4
  const F32_INF_BITS: u32 = ${ho}u;