@bicharts/shape-core 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
+ import{a as w,f as b}from"./chunk-KUH5NS3H.mjs";import C from"papaparse";var D=500,S=/^[+-]?\d{1,15}$/,E=/^[+-]?(\d{1,3}(,\d{3})*|\d+)(\.\d+)?([eE][+-]?\d+)?$/,R=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/,L=/^\d{1,2}[\/\-.]\d{1,2}[\/\-.]\d{2,4}$/;function I(n){let i=0,e=0,r=0,o=0;for(let a of n){if(a==null)continue;if(typeof a=="number"){o++,e++,Number.isInteger(a)&&i++;continue}if(a instanceof Date){o++,r++;continue}if(typeof a=="boolean"){o++;continue}let c=String(a).trim();if(c!==""){if(o++,S.test(c)){i++,e++;continue}if(E.test(c)){e++;continue}if((R.test(c)||L.test(c))&&!isNaN(Date.parse(c))){r++;continue}}}return o===0?"String":r/o>.9?"DateTime":i===o?"Integer":e===o?"Decimal":"String"}function x(n,i){if(n==null)return null;if(typeof n=="number")return i==="String"?String(n):n;if(n instanceof Date)return i==="DateTime"?n:n.toISOString();if(typeof n=="boolean")return String(n);let e=String(n).trim();if(e==="")return null;switch(i){case"Integer":return S.test(e)?parseInt(e,10):null;case"Decimal":return E.test(e)?parseFloat(e.replace(/,/g,"")):null;case"DateTime":{let r=Date.parse(e);return isNaN(r)?null:new Date(r)}default:return e}}function M(n){let i=(n||"").toLowerCase().replace(/\(.*$/,"").trim();return/^(tinyint|smallint|int|integer|int2|int4|int8|bigint|serial|bigserial)$/.test(i)?"Integer":/^(decimal|numeric|money|smallmoney|float|real|double|double precision|number)$/.test(i)?"Decimal":/^(date|datetime|datetime2|smalldatetime|datetimeoffset|timestamp|timestamptz|time)$/.test(i)?"DateTime":(/^(bit|bool|boolean)$/.test(i),"String")}function g(n,i,e){if(n.length===0)throw new Error("ingest: no columns were resolved from the source. Supply column descriptors, or use a source shape that carries them (grid/table/objects/sql).");let r=n.length,o=n.map((t,s)=>t.dataType??I(i.slice(0,D).map(l=>l?.[s]))),a=new Set((e.measures??[]).map(t=>t.toLowerCase())),c=new Set((e.dimensions??[]).map(t=>t.toLowerCase())),d=new Set((e.nonAdditive??[]).map(t=>t.toLowerCase())),T=n.map((t,s)=>{let l=t.name.toLowerCase(),u=t.isMeasure??((o[s]==="Integer"||o[s]==="Decimal")&&!w(t.name));a.has(l)&&(u=!0),c.has(l)&&(u=!1);let h={name:t.name,dataType:o[s],isMeasure:u};return u&&d.has(l)&&(h.discourageAggregationAcrossGroups=!0),h}),m=new b;m.dedupRows=e.dedup!==!1,m.setColumns(T);for(let t=0;t<i.length;t++){let s=i[t];m.addRow(Array.from({length:r},(l,u)=>x(s?.[u],o[u])),t)}let y=m.getColumnsWithStats(e.privacyLevel??"20",e.locale??"en"),f=new Map(y.map(t=>[t.name,t]));n.forEach(t=>{let s=f.get(t.name);s&&(t.format&&(s.modelFormat=t.format),t.description&&(s.modelDesc=t.description))});for(let[t,s]of Object.entries(e.formats??{})){let l=f.get(t);l&&(l.modelFormat=s)}for(let[t,s]of Object.entries(e.descriptions??{})){let l=f.get(t);l&&(l.modelDesc=s)}for(let t of e.groupBy??[]){let s=f.get(t);s&&(s.isGrouping=!0)}return{columns:y,rows:m.toObjectArray(),totalRows:m.getRowCount(),index:m}}function p(n,i){return n.map(e=>Array.isArray(e)?e:i.map(r=>e[r]))}function A(n,i){let e=[],r=new Set,o=Math.min(n.length,Math.max(1,i));for(let a=0;a<o;a++){let c=n[a];if(!(!c||typeof c!="object"))for(let d of Object.keys(c))r.has(d)||(r.add(d),e.push(d))}return e}function $(n,i={}){switch(n.kind){case"csv":{let e=C.parse(n.text,{skipEmptyLines:!0});if(e.errors?.length&&e.data.length===0)throw new Error(`ingest: CSV parse failed - ${e.errors[0].message}`);let r=e.data;if(r.length<2)throw new Error("ingest: CSV needs a header line plus at least one data row.");let o=r[0].map(a=>(a??"").trim());return g(o.map(a=>({name:a})),r.slice(1),i)}case"grid":{if(!n.header?.length)throw new Error("ingest: 'grid' needs a non-empty header.");return g(n.header.map(e=>({name:(e??"").trim()})),n.rows??[],i)}case"table":{if(!n.columns?.length)throw new Error("ingest: 'table' needs at least one column descriptor.");let e=n.columns.map(r=>r.name);return g(n.columns,p(n.rows??[],e),i)}case"objects":{let e=n.rows??[],r=n.columns?.length?n.columns:A(e,i.columnScanLimit??D).map(o=>({name:o}));if(!r.length)throw new Error("ingest: 'objects' produced no columns - the rows array is empty or holds no object keys.");return g(r,p(e,r.map(o=>o.name)),i)}case"sql":{if(!n.schema?.length)throw new Error("ingest: 'sql' needs at least one schema column.");let e=n.schema.map(r=>{let o=M(r.dataType);return{name:r.name,dataType:o,isMeasure:r.isMeasure,format:r.format,description:r.description}});return g(e,p(n.rows??[],e.map(r=>r.name)),i)}default:{let e=n;throw new Error(`ingest: unknown source kind '${e?.kind}'. Expected one of: csv, grid, table, objects, sql.`)}}}export{M as a,$ as b};
@@ -0,0 +1,2 @@
1
+ /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
+ import{a as j,b as q}from"./chunk-2LR73DNS.mjs";import{a as Y,b as G,c as x}from"./chunk-NWDPA7DG.mjs";import{a as U}from"./chunk-GY54KQLP.mjs";import{a as z,b as F,c as k}from"./chunk-WBEROMBG.mjs";import{a as H}from"./chunk-QEH7WTLB.mjs";import X from"papaparse";var Z=12,$=100,J=.3,Q=.9,tt=120,et=1900,nt=2100,it=0,st=20,rt=new Set(["id","ids","uuid","guid","key","zip","zipcode","postal","postalcode","ssn","code","codes","sku","isbn","msisdn","imei"]);function at(p){if(!p)return!1;let e=p.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_\-./]+/g," ").toLowerCase().split(/\s+/).filter(o=>o.length>0);return e.length===0?!1:rt.has(e[e.length-1])}var ot=/\b(year|yr|fy|fiscal\s*year|calendar\s*year)\b/i,ut=/^(?:(?:19|20)\d{2}(?:[-/ ]?(?:q[1-4]|w(?:0?[1-9]|[1-4]\d|5[0-3])|(?:0?[1-9]|1[0-2])))?|q[1-4][-/ ](?:19|20)\d{2}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[-/ ]?(?:19|20)?\d{2})$/i;function W(p){if(!Number.isInteger(p)||p<190001||p>210012)return!1;let e=p%100;return e>=1&&e<=12}function P(p){if(!Number.isInteger(p)||p<19000101||p>21001231)return!1;let e=Math.floor(p/100)%100,o=p%100;return e>=1&&e<=12&&o>=1&&o<=31}function lt(p,e){if(!e||!/\b(?:19|20)\d{2}\b/.test(p))return!1;let o=p.replace(/\b(?:19|20)\d{2}\b/g,"").replace(/[-/.,]/g," ").trim();if(!o)return!1;let c=j(o);return c.length>0&&e[c]!==void 0}function ct(p){let{dataType:e,name:o,isMeasure:c,distinctCount:f}=p;if(e==="DateTime")return!0;if(c)return!1;if(e==="Integer"||e==="Decimal"){let n=p.minNum,b=p.maxNum;if(!(n!=null&&b!=null&&Number.isFinite(n)&&Number.isFinite(b)&&Number.isInteger(n)&&Number.isInteger(b)&&b>=n))return!1;let T=n>=1900&&b<=2100;if(T&&f>=2&&ot.test(o)||T&&f>=3&&f===b-n+1)return!0;let M=W(n)&&W(b),D=P(n)&&P(b);if(M||D){if(!p.sampleValues)return!0;let h=0,N=0;for(let l of p.sampleValues){if(l==null||l==="")continue;h++;let t=Number(String(l).trim());if(Number.isFinite(t)&&(M?W(t):P(t))&&N++,h>=60)break}if(h>=2&&N===h)return!0}return!1}if(p.sampleValues){let n=p.locale?q(p.locale):null,b=0,I=0;for(let T of p.sampleValues){if(T==null||T==="")continue;b++;let M=String(T).trim();if((ut.test(M)||lt(M,n))&&I++,b>=60)break}if(b>=2&&I/b>=.8)return!0}return!1}function mt(p){let e=(p||"").trim().toLowerCase();return e.startsWith("sum ")||e.startsWith("total ")?"sum":e.startsWith("average ")||e.startsWith("avg. ")?"avg":e.startsWith("count ")||e.startsWith("distinct count ")||e.startsWith("count (distinct) ")?"count":e.startsWith("min ")||e.startsWith("minimum ")?"min":e.startsWith("max ")||e.startsWith("maximum ")?"max":null}function ft(p){let{rows:e,measureColIdx:o,measureName:c,candidateDims:f,minNum:n,maxNum:b,discourageAgg:I}=p,T=100,M=.01,D="";for(let N of f){if(N.distinct<2||N.distinct>T)continue;let l=f.filter(i=>i.idx!==N.idx).map(i=>i.idx),t=new Map;for(let i of e){let u=i[o];if(typeof u!="number"||!Number.isFinite(u))continue;let d=l.length?l.map(y=>String(i[y])).join(D):"",g=t.get(d);g||(g={sum:0,cset:new Set},t.set(d,g)),g.sum+=u,g.cset.add(String(i[N.idx]))}let r=0,a=0,s=0;for(let i of t.values())i.cset.size<2||(s++,Math.abs(i.sum-100)<=100*M?r++:Math.abs(i.sum-1)<=1*M&&a++);if(s>=2&&(r/s>=.9||a/s>=.9))return{additivity:"part_of_whole",partOfWholeDim:N.name}}if(I)return{additivity:"intensive_rate"};let h=mt(c);return h==="avg"||h==="min"||h==="max"?{additivity:"intensive_rate"}:h==="sum"||h==="count"?{additivity:"additive"}:n!=null&&b!=null&&Number.isFinite(n)&&Number.isFinite(b)&&n>=0&&b<=1.0001&&b>0?{additivity:"intensive_rate"}:{additivity:"unknown"}}function B(p){let{dataType:e,isMeasure:o,name:c,distinct:f,nonblank:n,prec:b,maxval:I,minval:T}=p,M=I-T+1,D=M>0?f/M:1,h=n>0?f/n:0,N=e==="Decimal"||b>0;return at(c)?"Categorical":D>=Q&&(z(c)&&f<=tt||T>=et&&I<=nt||T>=it&&I<=st)?"Ordinal":o||f>Z&&(N||f>=$||h>=J)?"Continuous":"Categorical"}var K=class{_computedStatsForLevel=null;_cols=[];_rows=[];_origIndices=[];_rowHashes=new Set;dedupRows=!0;STR(e){return e==null?"":e.toString()}getPrecision(e){if(!isFinite(e))return 0;let c=e.toString().split(".")[1];return c?c.length:0}getColumns(){return this._cols}hasTimeComponent(e){return!(e instanceof Date)||isNaN(e.getTime())?!1:e.getHours()!==0||e.getMinutes()!==0||e.getSeconds()!==0||e.getMilliseconds()!==0}getColumnsWithStats(e,o){if(this._computedStatsForLevel==e)return this._cols;let c=0,f=parseInt(e),n=[];for(let t of this._cols){let r=new Map,a=[],s=0,i=0,u=0,d=null,g=null,y=null,w=!1,R=!0,A=!0,v=null,S=!1;for(let C of this._rows){let m=C[c],_=this.STR(m);if(_!=""){if(s+=_.length,r.set(_,(r.get(_)||0)+1),i++,t.dataType=="Integer"||t.dataType=="Decimal"||t.dataType=="DateTime")if((d===null||m<d)&&(d=m),(g===null||m>g)&&(g=m),t.dataType=="Integer"||t.dataType=="Decimal"){if(y===null?y=m:y+=m,t.dataType=="Decimal"){let L=this.getPrecision(m);L>u&&(u=L)}a.push(m)}else w=w||this.hasTimeComponent(m);S&&(m<v?R=!1:m>v&&(A=!1)),v=m,S=!0}}if(i>=3&&(R&&!A?t.sortedDirection="asc":A&&!R?t.sortedDirection="desc":t.sortedDirection="none"),i>0&&r.size>0&&!t.isMeasure){let C=0,m=Number.MAX_SAFE_INTEGER;for(let _ of r.values())_>C&&(C=_),_<m&&(m=_);if(t.modalShare=C/i,t.minGroupCount=m===Number.MAX_SAFE_INTEGER?null:m,r.size===2){let _=[...r.keys()].map(V=>Y(V).trim().toLowerCase()).sort(),E=[["false","true"],["no","yes"],["n","y"],["0","1"],["f","t"]].some(V=>_[0]===V[0]&&_[1]===V[1]),O=/^(is|has)[_a-z0-9]|(?:default|churn|fraud|approv|convert|active|cancel|delinquen|flag|paid|win|pass|fail)/i.test(t.name);(E||O)&&(t.isBinaryFlag=!0)}}t.dataType=="DateTime"&&(t.dateWithTime=w),t.isTemporal=ct({dataType:t.dataType,name:t.name,isMeasure:t.isMeasure,distinctCount:r.size,minNum:typeof d=="number"?d:null,maxNum:typeof g=="number"?g:null,sampleValues:r.keys(),locale:o}),this.updateColumnStats10(f,t,i,r,u,g,d),this.updateColumnStats20(f,a,i,y,t,s,w,d,g,u,r,o),!t.isMeasure&&(t.dataType==="Integer"||t.dataType==="Decimal")&&B({dataType:t.dataType,isMeasure:!1,name:t.name,distinct:r.size,nonblank:i,prec:u,maxval:typeof g=="number"?g:0,minval:typeof d=="number"?d:0})==="Continuous"&&(t.isMeasure=!0),n[c]=t.isMeasure||r.size>2e3?null:new Set(r.keys()),c++}let b=[];this._cols.forEach((t,r)=>{t.isMeasure||b.push({idx:r,distinct:t.distinctCount??0,name:t.name})}),this._cols.forEach((t,r)=>{if(!t.isMeasure)return;let a=typeof t.lowValue=="number"?t.lowValue:null,s=typeof t.highValue=="number"?t.highValue:null,i=ft({rows:this._rows,measureColIdx:r,measureName:t.name,candidateDims:b,minNum:a,maxNum:s,discourageAgg:!!t.discourageAggregationAcrossGroups});t.additivity=i.additivity,i.partOfWholeDim&&(t.partOfWholeDim=i.partOfWholeDim)});let I=50,T=b.filter(t=>t.distinct>=2&&t.distinct<=I);this._cols.forEach((t,r)=>{if(!t.isMeasure)return;let a=[];for(let v of this._rows){let S=v[r];if(S==null||S==="")continue;let C=typeof S=="number"?S:parseFloat(S);isNaN(C)||a.push(C)}if(a.length===0)return;let s=[...a].sort((v,S)=>v-S),i=v=>s[Math.min(s.length-1,Math.max(0,Math.floor(v*(s.length-1))))],u=i(.5),d=i(.1),g=i(.9),y=Math.abs(u)>1e-9?Math.abs(u):Math.abs(s[s.length-1])>1e-9?Math.abs(s[s.length-1]):1;t.relativeDispersion=Math.round((g-d)/y*1e3)/1e3;let w=0;for(let v of a)w+=v;w/=a.length;let R=0;for(let v of a)R+=(v-w)*(v-w);if(R<=1e-12)return;let A=[];for(let v of T){let S=new Map;for(let m of this._rows){let _=m[r];if(_==null||_==="")continue;let L=typeof _=="number"?_:parseFloat(_);if(isNaN(L))continue;let E=this.STR(m[v.idx])+"",O=S.get(E);O?(O.s+=L,O.n++):S.set(E,{s:L,n:1})}let C=0;for(let m of S.values()){let _=m.s/m.n;C+=m.n*(_-w)*(_-w)}A.push({otherColumn:v.name,eta2:Math.round(C/R*1e4)/1e4})}A.length>0&&(t.groupDiscrimination=A)});let M=.97,D=5,h=this._cols.map((t,r)=>({c:t,i:r})).filter(t=>t.c.isMeasure);for(let t=0;t<h.length;t++)for(let r=t+1;r<h.length;r++){let a=h[t].i,s=h[r].i,i=0,u=0,d=0,g=0,y=0,w=0;for(let S of this._rows){let C=S[a],m=S[s];if(C==null||C===""||m===null||m===void 0||m==="")continue;let _=typeof C=="number"?C:parseFloat(C),L=typeof m=="number"?m:parseFloat(m);isNaN(_)||isNaN(L)||(i++,u+=_,d+=L,g+=_*_,y+=L*L,w+=_*L)}if(i<D)continue;let R=i*g-u*u,A=i*y-d*d;if(R<=1e-12||A<=1e-12)continue;let v=(i*w-u*d)/Math.sqrt(R*A);if(Math.abs(v)>=M){let S=h[t].c,C=h[r].c;S.collinearWithMeasures||(S.collinearWithMeasures=[]),C.collinearWithMeasures||(C.collinearWithMeasures=[]),S.collinearWithMeasures.push(C.name),C.collinearWithMeasures.push(S.name)}}for(let t=0;t<this._cols.length;t++){let r=n[t];if(!r||r.size===0)continue;let a=[];for(let s=0;s<this._cols.length;s++){if(s===t)continue;let i=n[s];if(!i||i.size===0)continue;let u=0;for(let g of r)i.has(g)&&u++;let d=Math.round(u/r.size*100);d>0&&a.push({otherColumn:this._cols[s].name,percentShared:d})}a.length>0&&(this._cols[t].sharedValueRatioWithOthers=a)}let N=50,l=[];for(let t=0;t<this._cols.length;t++){let r=n[t];r&&r.size>=2&&r.size<=N&&l.push(t)}if(l.length>=2){let t=new Map,r=(s,i)=>s+":"+i;for(let s=0;s<l.length;s++)for(let i=s+1;i<l.length;i++)t.set(r(l[s],l[i]),new Map);for(let s of this._rows)for(let i=0;i<l.length;i++){let u=this.STR(s[l[i]])+"";for(let d=i+1;d<l.length;d++){let g=""+this.STR(s[l[d]]),y=t.get(r(l[i],l[d])),w=u+""+g;y.set(w,(y.get(w)??0)+1)}}let a=new Map;for(let s=0;s<l.length;s++)for(let i=s+1;i<l.length;i++){let u=l[s],d=l[i],g=n[u].size,y=n[d].size,w=t.get(r(u,d)),R=w.size,A=0;for(let m of w.values())(A===0||m<A)&&(A=m);let v=Math.round(R/(g*y)*100),S=R===g,C=R===y;if((this._cols[u].categoricalPairStats||=[]).push({otherColumn:this._cols[d].name,fillPct:v,determinesOther:S,minCellCount:A,distinctCombinations:R}),(this._cols[d].categoricalPairStats||=[]).push({otherColumn:this._cols[u].name,fillPct:v,determinesOther:C,minCellCount:A,distinctCombinations:R}),S&&g>y){let m=a.get(u);(!m||y<m.card)&&a.set(u,{name:this._cols[d].name,card:y,ratio:y/g})}if(C&&y>g){let m=a.get(d);(!m||g<m.card)&&a.set(d,{name:this._cols[u].name,card:g,ratio:g/y})}}for(let[s,i]of a)this._cols[s].primaryParentColumn=i.name,this._cols[s].nestingRatio=Math.round(i.ratio*100)/100}return this._computedStatsForLevel=e,this._cols}updateColumnStats20(e,o,c,f,n,b,I,T,M,D,h,N){if(e>=20){let l=[...o].sort((a,s)=>a-s),t=Math.floor(l.length/2);if(c>0&&f!=null?n.avgValue=n.dataType=="Integer"?Math.round(f/c):f/c:n.avgValue=null,c>0&&(n.avgLength=b/c),this._rows.length>0&&(n.dataType!="DateTime"||I||!T?n.lowValue=T:n.lowValue=new Date(T).toISOString().slice(0,10)+"T00:00:00.000Z",n.dataType!="DateTime"||I||!M?n.highValue=M:n.highValue=new Date(M).toISOString().slice(0,10)+"T00:00:00.000Z",n.medianValue=l.length===0?null:l.length%2===0?n.dataType=="Integer"?Math.round((l[t-1]+l[t])/2):(l[t-1]+l[t])/2:l[t],n.numericPrecision=D),l.length>0){let a=n.avgValue??0,s=l.length,i=0,u=0;for(let g of l){let y=g-a;i+=y*y,u+=y*y*y}let d=i/s;n.skewness=d===0?0:u/s/Math.pow(Math.sqrt(d),3),n.stdDev=Math.sqrt(d)}f!==null&&(n.sum=f);let r=Array.from(h.entries()).sort((a,s)=>s[1]-a[1]);if(n.topCategories=r.slice(0,10).map(a=>a[1]),!n.isMeasure&&r.length>0){if(n.dataType==="String"){let s=r.map(u=>u[0]);n.formatSignature=H(s);let i=/^(UUID|EMAIL_LIKE|URL_LIKE|PHONE_LIKE|NUMERIC_ID|HEX_ID|OPAQUE_ID_ALPHANUMERIC|DATE_STR|BOOLEAN)$/;n.formatSignature&&!i.test(n.formatSignature)&&(n.avgLength===void 0||n.avgLength>=3)&&(n.isFreeText=!0)}else n.topCategoryValues=r.slice(0,5).map(s=>s[0]);if(e>=20){let s=r.map(u=>u[0]),i=k(s,N);if(i!==null)n.ordinalPattern=i.pattern,n.orderedDomain=i.orderedDomain;else if(n.dataType==="String"){let u=F(s);u!==null&&(n.safeDistinctValues=u)}}let a=U(r.map(s=>s[0]),n.name,N);a!==null&&(n.geoKind=a.geoKind,n.geoMatchPct=a.geoMatchPct,a.geoAmbiguous&&(n.geoAmbiguous=!0))}if(l.length>=8&&(n.dataType==="Integer"||n.dataType==="Decimal")){let a=s=>l[Math.floor((l.length-1)*s)];n.quantiles={p05:a(.05),p25:a(.25),p75:a(.75),p95:a(.95)}}}}updateColumnStats10(e,o,c,f,n,b,I){e>=10&&(o.blankCount=this._rows.length-c,o.distinctCount=f.size+(o.blankCount!=0?1:0),o.valueNature="Categorical",c>0&&(o.dataType==="Integer"||o.dataType==="Decimal"?o.valueNature=B({dataType:o.dataType,isMeasure:!!o.isMeasure,name:o.name,distinct:f.size,nonblank:c,prec:n,maxval:b,minval:I}):o.dataType==="DateTime"&&(o.valueNature=o.dateWithTime?"Continuous":"Ordinal")))}getRowCount(){return this._rows.length}getLeafCardinality(){if(this._leafCardinality!==null)return this._leafCardinality;let e=[];if(this._cols.forEach((c,f)=>{c.isMeasure||e.push(f)}),e.length===0)return this._leafCardinality=this._rows.length,this._leafCardinality;let o=new Set;for(let c of this._rows)o.add(JSON.stringify(e.map(f=>c[f])));return this._leafCardinality=o.size,this._leafCardinality}_leafCardinality=null;obfuscateString(e){let o="abcdefghijklmnopqrstuvwxyz",c=()=>o[Math.floor(x()*o.length)],f=()=>c().toUpperCase(),n=()=>Math.floor(x()*10).toString(),b=t=>/[A-Z]/.test(t)?f():/[a-z]/.test(t)?c():/[0-9]/.test(t)?n():t,I=e.includes("@")&&e.includes("."),T=I?e.split("@"):[e],M=I?T[1]:"",D=M.endsWith(".com"),h=D?".com":"",N=D?M.slice(0,-4):M,l=t=>{let r="";for(let a of t)r+=b(a),/[a-zA-Z0-9]/.test(a)&&x()<.2&&(r+=b(a));if(r.length>6){let a=Math.floor(x()*Math.min(3,r.length-6));for(let s=0;s<a;s++){let i=0;for(;i<5;){let u=Math.floor(x()*r.length);if(/[a-zA-Z0-9]/.test(r[u])){r=r.slice(0,u)+r.slice(u+1);break}i++}}}return r};if(I){let t=l(T[0]),r=l(N);return`${t}@${r}${h}`}else return l(e)}toObjectArray(){return this._rows.map(e=>{let o={};return this._cols.forEach((c,f)=>{o[c.name]=e[f]}),o})}async getCSVAsync(e){let o=[],c=e?25:1e7,f=e?4e3:1e7,n=new Map;for(let I of this._rows){let T={};for(let M=0;M<this._cols.length;M++){let D=this._cols[M],h=I[M];if(this.STR(h)!=""){if(e&&D.dataType=="String")if(n.has(h))h=n.get(h);else{let N=this.obfuscateString(h);n.set(h,N),h=N}else D.dataType=="DateTime"&&!D.dateWithTime&&(h=new Date(h).toISOString().slice(0,10)+"T00:00:00.000Z");f-=this.STR(h).length}else h=null;T[M]=h,--f}if(o.push(T),--c,c<=0||f<=0)break}return await X.unparse(o,{header:!1})}getCSVHeaderLine(){return X.unparse([this._cols.map(e=>this.STR(e.name))])}addRow(e,o){if(this.dedupRows){let c="";for(let n of e)c+=this.STR(n)+"~";let f=G(c);if(this._rowHashes.has(f))return!1;this._rowHashes.add(f)}return this._rows.push(e),this._origIndices.push(o??-1),!0}getOriginalRowIndex(e){return e<0||e>=this._origIndices.length?-1:this._origIndices[e]}reset(){this._cols=[],this._rows=[],this._origIndices=[],this._rowHashes=new Set,this._leafCardinality=null}setColumns(e){this._cols=e}};export{at as a,ct as b,mt as c,ft as d,B as e,K as f};
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
- import{a as U,b as X,c as Y,d as tt,e as nt,f as et}from"./chunk-FVSPBUW2.mjs";import{a as j,b as J,c as Q}from"./chunk-NWDPA7DG.mjs";import{a as K,b as V,c as E,d as F}from"./chunk-GY54KQLP.mjs";import{a as C,b as f,c as $,d as D,e as g,f as H,g as O,h as b,i as B}from"./chunk-3UOCZ2D6.mjs";import{a as G,b as N,c as _}from"./chunk-WBEROMBG.mjs";import{a as q}from"./chunk-QEH7WTLB.mjs";import{a as W,b as Z}from"./chunk-2LR73DNS.mjs";var R=85,S=2,ot=100,L=400,w=new Set(["us","usa","u s","u s a","united states","united states of america","america","ca","can","canada","mx","mex","mexico","estados unidos mexicanos"]);function m(i){let n=new Set;for(let e of i){if(e==null)continue;let o=C(String(e));if(o&&!n.has(o)&&(n.add(o),n.size>=L))break}return Array.from(n)}function P(i){let n=m(i);return n.length===0||!n.every(e=>w.has(e))?!1:n.some(e=>!f(e))}function M(i){return w.has(i)&&!!f(i)}function x(i){let n=m(i);if(n.length===0)return 0;let e=0;for(let o of n)f(o)&&e++;return Math.round(e/n.length*1e3)/10}function z(i){let n=new Set;for(let e of i){if(e==null)continue;let o=String(e).trim();if(o&&!n.has(o)&&(n.add(o),n.size>=L))break}return Array.from(n)}function I(i){let n=z(i);if(n.length===0)return 0;let e=0;for(let o of n)g(o).length>0&&e++;return Math.round(e/n.length*1e3)/10}function it(i){let n=m(i);if(n.length===0)return 0;let e=0;for(let o of n)b(o)&&e++;return Math.round(e/n.length*1e3)/10}function k(i,n){let e=0;for(let o of m(i))n(o)&&e++;return e}function st(i,n){let e=0;for(let o of z(i))n(o)&&e++;return e}function rt(i,n,e){let o=[],p=[],s={},A=new Set(i),d=t=>n.map(r=>r[t]);for(let t of["city","zip","lat","lon","country"]){let r=e?.[t];r&&A.has(r)&&(s[t]=r)}let u=e?.state;if(u&&A.has(u)){let t=d(u),r=m(t);r.length>0&&r.every(M)?p.push(`state=${u} (every value is "CA", which is both Canada and California)`):P(t)?(p.push(`state=${u} (every value is a country, not a state)`),s.country||(s.country=u)):x(t)<R?p.push(`state=${u} (only ${x(t)}% of values are states/provinces)`):s.state=u}let l=new Set(Object.values(s).filter(Boolean)),y=i.filter(t=>!l.has(t)&&!t.startsWith("__"));if(!s.state){let t=null;for(let r of y){let a=d(r);if(P(a))continue;let c=x(a);if(c<R)continue;let v=k(a,h=>!!f(h)),T=k(a,h=>!!f(h)&&!M(h));v<S&&T<1||(!t||c>t.pct)&&(t={name:r,pct:c})}t&&(s.state=t.name,l.add(t.name),o.push(`state=${t.name} (${t.pct}% states/provinces)`))}if(!s.zip)for(let t of y){if(l.has(t))continue;let r=d(t),a=I(r);if(!(a<ot)&&!(st(r,c=>g(c).length>0)<S)){s.zip=t,l.add(t),o.push(`zip=${t} (${a}% ZIP codes)`);break}}if(!s.country){for(let t of y)if(!l.has(t)&&P(d(t))){s.country=t,l.add(t),o.push(`country=${t}`);break}}if(!s.city){let t=null;for(let r of y){if(l.has(r))continue;let a=d(r),c=it(a);c<R||k(a,v=>b(v))<S||(!t||c>t.pct)&&(t={name:r,pct:c})}t&&(s.city=t.name,o.push(`city=${t.name} (${t.pct}% known cities)`))}return{bind:!!(s.city||s.state||s.zip||s.lat&&s.lon)?s:null,backfilled:o,refused:p}}export{Q as GET_RANDOM,et as IndexedText,J as SIMPLE_STRING_HASH,j as STR,x as admin1MatchPct,F as buildGeoIsoColumn,O as buildGeoPointColumns,B as cityMatchPct,tt as classifyAdditivity,nt as classifyNumericValueNature,X as classifyTemporal,q as detectFormatSignature,K as detectGeo,_ as detectOrdinalDomain,Y as hostAggHint,U as isIdentifierName,E as isJoinGeoKind,G as isOrdinalFriendlyName,P as looksLikeCountryColumn,Z as monthLookupFor,$ as normalizeCountry,W as normalizeMonthKey,C as normalizePlaceName,f as resolveAdmin1,H as resolveGeoPoint,rt as resolvePointRoles,N as safeDistinctValuesToShip,V as toGeoIso,I as zipMatchPct,g as zipPrefixCandidates,D as zipToPrefix3};
2
+ import{a as ot,b as it}from"./chunk-DX43BJEE.mjs";import{a as U,b as X,c as Y,d as tt,e as nt,f as et}from"./chunk-KUH5NS3H.mjs";import{a as W,b as Z}from"./chunk-2LR73DNS.mjs";import{a as j,b as J,c as Q}from"./chunk-NWDPA7DG.mjs";import{a as q,b as E,c as F,d as K}from"./chunk-GY54KQLP.mjs";import{a as v,b as f,c as _,d as $,e as h,f as O,g as H,h as R,i as B}from"./chunk-3UOCZ2D6.mjs";import{a as G,b as N,c as D}from"./chunk-WBEROMBG.mjs";import{a as V}from"./chunk-QEH7WTLB.mjs";var b=85,S=2,st=100,L=400,T=new Set(["us","usa","u s","u s a","united states","united states of america","america","ca","can","canada","mx","mex","mexico","estados unidos mexicanos"]);function m(i){let n=new Set;for(let e of i){if(e==null)continue;let o=v(String(e));if(o&&!n.has(o)&&(n.add(o),n.size>=L))break}return Array.from(n)}function P(i){let n=m(i);return n.length===0||!n.every(e=>T.has(e))?!1:n.some(e=>!f(e))}function A(i){return T.has(i)&&!!f(i)}function x(i){let n=m(i);if(n.length===0)return 0;let e=0;for(let o of n)f(o)&&e++;return Math.round(e/n.length*1e3)/10}function I(i){let n=new Set;for(let e of i){if(e==null)continue;let o=String(e).trim();if(o&&!n.has(o)&&(n.add(o),n.size>=L))break}return Array.from(n)}function w(i){let n=I(i);if(n.length===0)return 0;let e=0;for(let o of n)h(o).length>0&&e++;return Math.round(e/n.length*1e3)/10}function rt(i){let n=m(i);if(n.length===0)return 0;let e=0;for(let o of n)R(o)&&e++;return Math.round(e/n.length*1e3)/10}function M(i,n){let e=0;for(let o of m(i))n(o)&&e++;return e}function at(i,n){let e=0;for(let o of I(i))n(o)&&e++;return e}function ct(i,n,e){let o=[],p=[],s={},k=new Set(i),d=t=>n.map(r=>r[t]);for(let t of["city","zip","lat","lon","country"]){let r=e?.[t];r&&k.has(r)&&(s[t]=r)}let u=e?.state;if(u&&k.has(u)){let t=d(u),r=m(t);r.length>0&&r.every(A)?p.push(`state=${u} (every value is "CA", which is both Canada and California)`):P(t)?(p.push(`state=${u} (every value is a country, not a state)`),s.country||(s.country=u)):x(t)<b?p.push(`state=${u} (only ${x(t)}% of values are states/provinces)`):s.state=u}let l=new Set(Object.values(s).filter(Boolean)),y=i.filter(t=>!l.has(t)&&!t.startsWith("__"));if(!s.state){let t=null;for(let r of y){let a=d(r);if(P(a))continue;let c=x(a);if(c<b)continue;let C=M(a,g=>!!f(g)),z=M(a,g=>!!f(g)&&!A(g));C<S&&z<1||(!t||c>t.pct)&&(t={name:r,pct:c})}t&&(s.state=t.name,l.add(t.name),o.push(`state=${t.name} (${t.pct}% states/provinces)`))}if(!s.zip)for(let t of y){if(l.has(t))continue;let r=d(t),a=w(r);if(!(a<st)&&!(at(r,c=>h(c).length>0)<S)){s.zip=t,l.add(t),o.push(`zip=${t} (${a}% ZIP codes)`);break}}if(!s.country){for(let t of y)if(!l.has(t)&&P(d(t))){s.country=t,l.add(t),o.push(`country=${t}`);break}}if(!s.city){let t=null;for(let r of y){if(l.has(r))continue;let a=d(r),c=rt(a);c<b||M(a,C=>R(C))<S||(!t||c>t.pct)&&(t={name:r,pct:c})}t&&(s.city=t.name,o.push(`city=${t.name} (${t.pct}% known cities)`))}return{bind:!!(s.city||s.state||s.zip||s.lat&&s.lon)?s:null,backfilled:o,refused:p}}export{Q as GET_RANDOM,et as IndexedText,J as SIMPLE_STRING_HASH,j as STR,x as admin1MatchPct,K as buildGeoIsoColumn,H as buildGeoPointColumns,B as cityMatchPct,tt as classifyAdditivity,nt as classifyNumericValueNature,X as classifyTemporal,V as detectFormatSignature,q as detectGeo,D as detectOrdinalDomain,ot as engineTypeForSqlType,Y as hostAggHint,it as ingest,U as isIdentifierName,F as isJoinGeoKind,G as isOrdinalFriendlyName,P as looksLikeCountryColumn,Z as monthLookupFor,_ as normalizeCountry,W as normalizeMonthKey,v as normalizePlaceName,f as resolveAdmin1,O as resolveGeoPoint,ct as resolvePointRoles,N as safeDistinctValuesToShip,E as toGeoIso,w as zipMatchPct,h as zipPrefixCandidates,$ as zipToPrefix3};
@@ -1,2 +1,2 @@
1
1
  /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
- import{a,b,c,d,e,f}from"./chunk-FVSPBUW2.mjs";import"./chunk-NWDPA7DG.mjs";import"./chunk-GY54KQLP.mjs";import"./chunk-3UOCZ2D6.mjs";import"./chunk-WBEROMBG.mjs";import"./chunk-QEH7WTLB.mjs";import"./chunk-2LR73DNS.mjs";export{f as IndexedText,d as classifyAdditivity,e as classifyNumericValueNature,b as classifyTemporal,c as hostAggHint,a as isIdentifierName};
2
+ import{a,b,c,d,e,f}from"./chunk-KUH5NS3H.mjs";import"./chunk-2LR73DNS.mjs";import"./chunk-NWDPA7DG.mjs";import"./chunk-GY54KQLP.mjs";import"./chunk-3UOCZ2D6.mjs";import"./chunk-WBEROMBG.mjs";import"./chunk-QEH7WTLB.mjs";export{f as IndexedText,d as classifyAdditivity,e as classifyNumericValueNature,b as classifyTemporal,c as hostAggHint,a as isIdentifierName};
@@ -0,0 +1,2 @@
1
+ /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
+ import{a,b}from"./chunk-DX43BJEE.mjs";import"./chunk-KUH5NS3H.mjs";import"./chunk-2LR73DNS.mjs";import"./chunk-NWDPA7DG.mjs";import"./chunk-GY54KQLP.mjs";import"./chunk-3UOCZ2D6.mjs";import"./chunk-WBEROMBG.mjs";import"./chunk-QEH7WTLB.mjs";export{a as engineTypeForSqlType,b as ingest};
@@ -13,3 +13,5 @@ export { resolvePointRoles, looksLikeCountryColumn, admin1MatchPct, zipMatchPct,
13
13
  export type { PointBind, PointRoleResolution } from "./geoPointRoles";
14
14
  export { monthLookupFor, normalizeMonthKey } from "./monthNames";
15
15
  export { STR, SIMPLE_STRING_HASH, GET_RANDOM } from "./util";
16
+ export { ingest, engineTypeForSqlType } from "./ingest";
17
+ export type { DataSource, IngestOptions, IngestResult, ColumnDescriptor, SqlColumnMeta, EngineDataType, } from "./ingest";
@@ -58,6 +58,14 @@ export declare class IndexedText implements IValueCollection {
58
58
  private _rows;
59
59
  private _origIndices;
60
60
  private _rowHashes;
61
+ /**
62
+ * Collapse value-identical rows on addRow. DEFAULT TRUE — the long-standing behaviour,
63
+ * and the right one for shape measurement. See addRow for when to turn it off.
64
+ *
65
+ * A public field rather than a constructor argument so it stays additive: existing
66
+ * callers construct IndexedText with no arguments and are unaffected.
67
+ */
68
+ dedupRows: boolean;
61
69
  private STR;
62
70
  private getPrecision;
63
71
  getColumns(): LLMColumnWithValue[];
@@ -0,0 +1,121 @@
1
+ import { IndexedText } from "./indexedText";
2
+ import type { LLMColumnWithValue } from "./models";
3
+ /** Engine value types. Anything a decoder cannot map confidently becomes "String". */
4
+ export type EngineDataType = "String" | "Integer" | "Decimal" | "DateTime";
5
+ /**
6
+ * One descriptor per column, as the shared core consumes it. Everything except `name` is
7
+ * optional: a schema-aware caller supplies the known type, role, format and description; a
8
+ * bare CSV supplies only names and the core infers the rest.
9
+ */
10
+ export interface ColumnDescriptor {
11
+ name: string;
12
+ /** Omit to infer from a sample of values. */
13
+ dataType?: EngineDataType | string;
14
+ /** Explicit measure/dimension role. Omit to apply the numeric-non-identifier heuristic. */
15
+ isMeasure?: boolean;
16
+ /** Format string from the model, e.g. "$#,##0" or "0.0%". Surfaces as modelFormat. */
17
+ format?: string;
18
+ /** Human description from the model. Surfaces as modelDesc. */
19
+ description?: string;
20
+ }
21
+ /** Column metadata as a relational catalogue reports it (INFORMATION_SCHEMA and friends). */
22
+ export interface SqlColumnMeta {
23
+ name: string;
24
+ /** The SQL type name — "int", "decimal", "nvarchar", "datetime2", … Case-insensitive. */
25
+ dataType: string;
26
+ numericPrecision?: number;
27
+ numericScale?: number;
28
+ isNullable?: boolean;
29
+ /** Optional model-level extras, when the caller has them. */
30
+ format?: string;
31
+ description?: string;
32
+ /** Explicit role, when the caller knows better than the type mapping. */
33
+ isMeasure?: boolean;
34
+ }
35
+ export interface IngestOptions {
36
+ /** Force these columns to MEASURE, by name (case-insensitive). */
37
+ measures?: string[];
38
+ /** Force these columns to DIMENSION, by name (case-insensitive). */
39
+ dimensions?: string[];
40
+ /** column -> format string. Overrides a descriptor's own `format`. */
41
+ formats?: Record<string, string>;
42
+ /** column -> description. Overrides a descriptor's own `description`. */
43
+ descriptions?: Record<string, string>;
44
+ /** Columns that are the primary series/breakdown. Surfaces as isGrouping. */
45
+ groupBy?: string[];
46
+ /** MEASURE columns that must not be summed across groups (a ratio, average or rate). */
47
+ nonAdditive?: string[];
48
+ /** "0" | "10" | "20" | "30" — how much detail the measured shape carries. Default "20". */
49
+ privacyLevel?: string;
50
+ /** Locale for temporal classification (month-name matching). Default "en". */
51
+ locale?: string;
52
+ /**
53
+ * Collapse value-identical rows. DEFAULT TRUE, which preserves the engine's long-standing
54
+ * behaviour and is usually what a chart wants — duplicate rows add no shape information
55
+ * and inflate every distribution statistic.
56
+ *
57
+ * Set false when row identity matters to the caller: the returned `rows` must line up
58
+ * one-to-one with the source rows for selection round-tripping, or duplicates are
59
+ * themselves the signal (raw event streams, where "the same reading twice" is data).
60
+ *
61
+ * This changes `rows`, `totalRows` and every count-derived statistic, so it is a
62
+ * measurement decision, not a formatting one.
63
+ */
64
+ dedup?: boolean;
65
+ /**
66
+ * For the `objects` decoder: how many rows to scan when discovering column names.
67
+ * Default 500. Raise it for sparse payloads where late rows introduce new keys.
68
+ */
69
+ columnScanLimit?: number;
70
+ }
71
+ export interface IngestResult {
72
+ /** The MEASURED shape — bind this straight to a renderer. */
73
+ columns: LLMColumnWithValue[];
74
+ /** Row objects keyed by column name — bind this straight to a renderer. */
75
+ rows: Record<string, any>[];
76
+ /**
77
+ * Rows the engine actually holds. With dedup on this is the DISTINCT count, which is the
78
+ * honest denominator for the statistics in `columns`.
79
+ */
80
+ totalRows: number;
81
+ /** The live engine, for callers that need more than the shape (leaf cardinality, CSV…). */
82
+ index: IndexedText;
83
+ }
84
+ /** Discriminated union of everything the front door accepts. */
85
+ export type DataSource = {
86
+ kind: "csv";
87
+ text: string;
88
+ } | {
89
+ kind: "grid";
90
+ header: string[];
91
+ rows: any[][];
92
+ } | {
93
+ kind: "table";
94
+ columns: ColumnDescriptor[];
95
+ rows: Array<any[] | Record<string, any>>;
96
+ } | {
97
+ kind: "objects";
98
+ rows: Record<string, any>[];
99
+ columns?: ColumnDescriptor[];
100
+ } | {
101
+ kind: "sql";
102
+ schema: SqlColumnMeta[];
103
+ rows: Array<any[] | Record<string, any>>;
104
+ };
105
+ /**
106
+ * Map a relational type name onto an engine type. Deliberately generous about vendor
107
+ * spellings — the cost of a miss is a numeric column measured as text, which changes the
108
+ * chart. Unknown types fall through to "String", which is always safe: a value that cannot
109
+ * be parsed is better described as a label than silently nulled.
110
+ */
111
+ export declare function engineTypeForSqlType(sqlType: string): EngineDataType;
112
+ /**
113
+ * Turn a data source into a measured shape plus directly bindable rows.
114
+ *
115
+ * The result is meant to be destructured and handed straight to a renderer:
116
+ *
117
+ * const { rows, columns } = ingest({ kind: "csv", text });
118
+ *
119
+ * `index` is there for callers that need the engine itself; nothing routine should.
120
+ */
121
+ export declare function ingest(source: DataSource, opts?: IngestOptions): IngestResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bicharts/shape-core",
3
- "version": "0.1.15",
3
+ "version": "0.2.0",
4
4
  "description": "Host-agnostic data-shape profiler: ingest a dataset's rows through IValueCollection.addRow and read back the measured shape as an LLMColumnWithValue[] payload — types, cardinality, temporal/ordinal detection, geographic region and point resolution, cross-column signals. MEASUREMENT only: the policy that decides what a measured shape means for chart selection lives server-side.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -14,6 +14,11 @@
14
14
  "import": "./dist/index.mjs",
15
15
  "default": "./dist/index.mjs"
16
16
  },
17
+ "./ingest": {
18
+ "types": "./dist/types/ingest.d.ts",
19
+ "import": "./dist/ingest.mjs",
20
+ "default": "./dist/ingest.mjs"
21
+ },
17
22
  "./indexedText": {
18
23
  "types": "./dist/types/indexedText.d.ts",
19
24
  "import": "./dist/indexedText.mjs",
@@ -1,2 +0,0 @@
1
- /*! @bicharts/shape-core — Apache-2.0. Bundled reference data: GeoNames (https://www.geonames.org/) CC BY 4.0; US Census/TIGER (public domain). Full text: NOTICE in this package. */
2
- import{a as Y,b as G,c as x}from"./chunk-NWDPA7DG.mjs";import{a as U}from"./chunk-GY54KQLP.mjs";import{a as z,b as F,c as k}from"./chunk-WBEROMBG.mjs";import{a as H}from"./chunk-QEH7WTLB.mjs";import{a as j,b as q}from"./chunk-2LR73DNS.mjs";import X from"papaparse";var Z=12,$=100,J=.3,Q=.9,tt=120,et=1900,nt=2100,it=0,st=20,rt=new Set(["id","ids","uuid","guid","key","zip","zipcode","postal","postalcode","ssn","code","codes","sku","isbn","msisdn","imei"]);function at(p){if(!p)return!1;let e=p.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_\-./]+/g," ").toLowerCase().split(/\s+/).filter(o=>o.length>0);return e.length===0?!1:rt.has(e[e.length-1])}var ot=/\b(year|yr|fy|fiscal\s*year|calendar\s*year)\b/i,ut=/^(?:(?:19|20)\d{2}(?:[-/ ]?(?:q[1-4]|w(?:0?[1-9]|[1-4]\d|5[0-3])|(?:0?[1-9]|1[0-2])))?|q[1-4][-/ ](?:19|20)\d{2}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[-/ ]?(?:19|20)?\d{2})$/i;function W(p){if(!Number.isInteger(p)||p<190001||p>210012)return!1;let e=p%100;return e>=1&&e<=12}function P(p){if(!Number.isInteger(p)||p<19000101||p>21001231)return!1;let e=Math.floor(p/100)%100,o=p%100;return e>=1&&e<=12&&o>=1&&o<=31}function lt(p,e){if(!e||!/\b(?:19|20)\d{2}\b/.test(p))return!1;let o=p.replace(/\b(?:19|20)\d{2}\b/g,"").replace(/[-/.,]/g," ").trim();if(!o)return!1;let c=j(o);return c.length>0&&e[c]!==void 0}function ct(p){let{dataType:e,name:o,isMeasure:c,distinctCount:f}=p;if(e==="DateTime")return!0;if(c)return!1;if(e==="Integer"||e==="Decimal"){let n=p.minNum,b=p.maxNum;if(!(n!=null&&b!=null&&Number.isFinite(n)&&Number.isFinite(b)&&Number.isInteger(n)&&Number.isInteger(b)&&b>=n))return!1;let T=n>=1900&&b<=2100;if(T&&f>=2&&ot.test(o)||T&&f>=3&&f===b-n+1)return!0;let M=W(n)&&W(b),D=P(n)&&P(b);if(M||D){if(!p.sampleValues)return!0;let h=0,N=0;for(let l of p.sampleValues){if(l==null||l==="")continue;h++;let t=Number(String(l).trim());if(Number.isFinite(t)&&(M?W(t):P(t))&&N++,h>=60)break}if(h>=2&&N===h)return!0}return!1}if(p.sampleValues){let n=p.locale?q(p.locale):null,b=0,I=0;for(let T of p.sampleValues){if(T==null||T==="")continue;b++;let M=String(T).trim();if((ut.test(M)||lt(M,n))&&I++,b>=60)break}if(b>=2&&I/b>=.8)return!0}return!1}function mt(p){let e=(p||"").trim().toLowerCase();return e.startsWith("sum ")||e.startsWith("total ")?"sum":e.startsWith("average ")||e.startsWith("avg. ")?"avg":e.startsWith("count ")||e.startsWith("distinct count ")||e.startsWith("count (distinct) ")?"count":e.startsWith("min ")||e.startsWith("minimum ")?"min":e.startsWith("max ")||e.startsWith("maximum ")?"max":null}function ft(p){let{rows:e,measureColIdx:o,measureName:c,candidateDims:f,minNum:n,maxNum:b,discourageAgg:I}=p,T=100,M=.01,D="";for(let N of f){if(N.distinct<2||N.distinct>T)continue;let l=f.filter(i=>i.idx!==N.idx).map(i=>i.idx),t=new Map;for(let i of e){let u=i[o];if(typeof u!="number"||!Number.isFinite(u))continue;let d=l.length?l.map(y=>String(i[y])).join(D):"",g=t.get(d);g||(g={sum:0,cset:new Set},t.set(d,g)),g.sum+=u,g.cset.add(String(i[N.idx]))}let r=0,a=0,s=0;for(let i of t.values())i.cset.size<2||(s++,Math.abs(i.sum-100)<=100*M?r++:Math.abs(i.sum-1)<=1*M&&a++);if(s>=2&&(r/s>=.9||a/s>=.9))return{additivity:"part_of_whole",partOfWholeDim:N.name}}if(I)return{additivity:"intensive_rate"};let h=mt(c);return h==="avg"||h==="min"||h==="max"?{additivity:"intensive_rate"}:h==="sum"||h==="count"?{additivity:"additive"}:n!=null&&b!=null&&Number.isFinite(n)&&Number.isFinite(b)&&n>=0&&b<=1.0001&&b>0?{additivity:"intensive_rate"}:{additivity:"unknown"}}function B(p){let{dataType:e,isMeasure:o,name:c,distinct:f,nonblank:n,prec:b,maxval:I,minval:T}=p,M=I-T+1,D=M>0?f/M:1,h=n>0?f/n:0,N=e==="Decimal"||b>0;return at(c)?"Categorical":D>=Q&&(z(c)&&f<=tt||T>=et&&I<=nt||T>=it&&I<=st)?"Ordinal":o||f>Z&&(N||f>=$||h>=J)?"Continuous":"Categorical"}var K=class{_computedStatsForLevel=null;_cols=[];_rows=[];_origIndices=[];_rowHashes=new Set;STR(e){return e==null?"":e.toString()}getPrecision(e){if(!isFinite(e))return 0;let c=e.toString().split(".")[1];return c?c.length:0}getColumns(){return this._cols}hasTimeComponent(e){return!(e instanceof Date)||isNaN(e.getTime())?!1:e.getHours()!==0||e.getMinutes()!==0||e.getSeconds()!==0||e.getMilliseconds()!==0}getColumnsWithStats(e,o){if(this._computedStatsForLevel==e)return this._cols;let c=0,f=parseInt(e),n=[];for(let t of this._cols){let r=new Map,a=[],s=0,i=0,u=0,d=null,g=null,y=null,w=!1,A=!0,R=!0,v=null,S=!1;for(let C of this._rows){let m=C[c],_=this.STR(m);if(_!=""){if(s+=_.length,r.set(_,(r.get(_)||0)+1),i++,t.dataType=="Integer"||t.dataType=="Decimal"||t.dataType=="DateTime")if((d===null||m<d)&&(d=m),(g===null||m>g)&&(g=m),t.dataType=="Integer"||t.dataType=="Decimal"){if(y===null?y=m:y+=m,t.dataType=="Decimal"){let L=this.getPrecision(m);L>u&&(u=L)}a.push(m)}else w=w||this.hasTimeComponent(m);S&&(m<v?A=!1:m>v&&(R=!1)),v=m,S=!0}}if(i>=3&&(A&&!R?t.sortedDirection="asc":R&&!A?t.sortedDirection="desc":t.sortedDirection="none"),i>0&&r.size>0&&!t.isMeasure){let C=0,m=Number.MAX_SAFE_INTEGER;for(let _ of r.values())_>C&&(C=_),_<m&&(m=_);if(t.modalShare=C/i,t.minGroupCount=m===Number.MAX_SAFE_INTEGER?null:m,r.size===2){let _=[...r.keys()].map(V=>Y(V).trim().toLowerCase()).sort(),E=[["false","true"],["no","yes"],["n","y"],["0","1"],["f","t"]].some(V=>_[0]===V[0]&&_[1]===V[1]),O=/^(is|has)[_a-z0-9]|(?:default|churn|fraud|approv|convert|active|cancel|delinquen|flag|paid|win|pass|fail)/i.test(t.name);(E||O)&&(t.isBinaryFlag=!0)}}t.dataType=="DateTime"&&(t.dateWithTime=w),t.isTemporal=ct({dataType:t.dataType,name:t.name,isMeasure:t.isMeasure,distinctCount:r.size,minNum:typeof d=="number"?d:null,maxNum:typeof g=="number"?g:null,sampleValues:r.keys(),locale:o}),this.updateColumnStats10(f,t,i,r,u,g,d),this.updateColumnStats20(f,a,i,y,t,s,w,d,g,u,r,o),!t.isMeasure&&(t.dataType==="Integer"||t.dataType==="Decimal")&&B({dataType:t.dataType,isMeasure:!1,name:t.name,distinct:r.size,nonblank:i,prec:u,maxval:typeof g=="number"?g:0,minval:typeof d=="number"?d:0})==="Continuous"&&(t.isMeasure=!0),n[c]=t.isMeasure||r.size>2e3?null:new Set(r.keys()),c++}let b=[];this._cols.forEach((t,r)=>{t.isMeasure||b.push({idx:r,distinct:t.distinctCount??0,name:t.name})}),this._cols.forEach((t,r)=>{if(!t.isMeasure)return;let a=typeof t.lowValue=="number"?t.lowValue:null,s=typeof t.highValue=="number"?t.highValue:null,i=ft({rows:this._rows,measureColIdx:r,measureName:t.name,candidateDims:b,minNum:a,maxNum:s,discourageAgg:!!t.discourageAggregationAcrossGroups});t.additivity=i.additivity,i.partOfWholeDim&&(t.partOfWholeDim=i.partOfWholeDim)});let I=50,T=b.filter(t=>t.distinct>=2&&t.distinct<=I);this._cols.forEach((t,r)=>{if(!t.isMeasure)return;let a=[];for(let v of this._rows){let S=v[r];if(S==null||S==="")continue;let C=typeof S=="number"?S:parseFloat(S);isNaN(C)||a.push(C)}if(a.length===0)return;let s=[...a].sort((v,S)=>v-S),i=v=>s[Math.min(s.length-1,Math.max(0,Math.floor(v*(s.length-1))))],u=i(.5),d=i(.1),g=i(.9),y=Math.abs(u)>1e-9?Math.abs(u):Math.abs(s[s.length-1])>1e-9?Math.abs(s[s.length-1]):1;t.relativeDispersion=Math.round((g-d)/y*1e3)/1e3;let w=0;for(let v of a)w+=v;w/=a.length;let A=0;for(let v of a)A+=(v-w)*(v-w);if(A<=1e-12)return;let R=[];for(let v of T){let S=new Map;for(let m of this._rows){let _=m[r];if(_==null||_==="")continue;let L=typeof _=="number"?_:parseFloat(_);if(isNaN(L))continue;let E=this.STR(m[v.idx])+"",O=S.get(E);O?(O.s+=L,O.n++):S.set(E,{s:L,n:1})}let C=0;for(let m of S.values()){let _=m.s/m.n;C+=m.n*(_-w)*(_-w)}R.push({otherColumn:v.name,eta2:Math.round(C/A*1e4)/1e4})}R.length>0&&(t.groupDiscrimination=R)});let M=.97,D=5,h=this._cols.map((t,r)=>({c:t,i:r})).filter(t=>t.c.isMeasure);for(let t=0;t<h.length;t++)for(let r=t+1;r<h.length;r++){let a=h[t].i,s=h[r].i,i=0,u=0,d=0,g=0,y=0,w=0;for(let S of this._rows){let C=S[a],m=S[s];if(C==null||C===""||m===null||m===void 0||m==="")continue;let _=typeof C=="number"?C:parseFloat(C),L=typeof m=="number"?m:parseFloat(m);isNaN(_)||isNaN(L)||(i++,u+=_,d+=L,g+=_*_,y+=L*L,w+=_*L)}if(i<D)continue;let A=i*g-u*u,R=i*y-d*d;if(A<=1e-12||R<=1e-12)continue;let v=(i*w-u*d)/Math.sqrt(A*R);if(Math.abs(v)>=M){let S=h[t].c,C=h[r].c;S.collinearWithMeasures||(S.collinearWithMeasures=[]),C.collinearWithMeasures||(C.collinearWithMeasures=[]),S.collinearWithMeasures.push(C.name),C.collinearWithMeasures.push(S.name)}}for(let t=0;t<this._cols.length;t++){let r=n[t];if(!r||r.size===0)continue;let a=[];for(let s=0;s<this._cols.length;s++){if(s===t)continue;let i=n[s];if(!i||i.size===0)continue;let u=0;for(let g of r)i.has(g)&&u++;let d=Math.round(u/r.size*100);d>0&&a.push({otherColumn:this._cols[s].name,percentShared:d})}a.length>0&&(this._cols[t].sharedValueRatioWithOthers=a)}let N=50,l=[];for(let t=0;t<this._cols.length;t++){let r=n[t];r&&r.size>=2&&r.size<=N&&l.push(t)}if(l.length>=2){let t=new Map,r=(s,i)=>s+":"+i;for(let s=0;s<l.length;s++)for(let i=s+1;i<l.length;i++)t.set(r(l[s],l[i]),new Map);for(let s of this._rows)for(let i=0;i<l.length;i++){let u=this.STR(s[l[i]])+"";for(let d=i+1;d<l.length;d++){let g=""+this.STR(s[l[d]]),y=t.get(r(l[i],l[d])),w=u+""+g;y.set(w,(y.get(w)??0)+1)}}let a=new Map;for(let s=0;s<l.length;s++)for(let i=s+1;i<l.length;i++){let u=l[s],d=l[i],g=n[u].size,y=n[d].size,w=t.get(r(u,d)),A=w.size,R=0;for(let m of w.values())(R===0||m<R)&&(R=m);let v=Math.round(A/(g*y)*100),S=A===g,C=A===y;if((this._cols[u].categoricalPairStats||=[]).push({otherColumn:this._cols[d].name,fillPct:v,determinesOther:S,minCellCount:R,distinctCombinations:A}),(this._cols[d].categoricalPairStats||=[]).push({otherColumn:this._cols[u].name,fillPct:v,determinesOther:C,minCellCount:R,distinctCombinations:A}),S&&g>y){let m=a.get(u);(!m||y<m.card)&&a.set(u,{name:this._cols[d].name,card:y,ratio:y/g})}if(C&&y>g){let m=a.get(d);(!m||g<m.card)&&a.set(d,{name:this._cols[u].name,card:g,ratio:g/y})}}for(let[s,i]of a)this._cols[s].primaryParentColumn=i.name,this._cols[s].nestingRatio=Math.round(i.ratio*100)/100}return this._computedStatsForLevel=e,this._cols}updateColumnStats20(e,o,c,f,n,b,I,T,M,D,h,N){if(e>=20){let l=[...o].sort((a,s)=>a-s),t=Math.floor(l.length/2);if(c>0&&f!=null?n.avgValue=n.dataType=="Integer"?Math.round(f/c):f/c:n.avgValue=null,c>0&&(n.avgLength=b/c),this._rows.length>0&&(n.dataType!="DateTime"||I||!T?n.lowValue=T:n.lowValue=new Date(T).toISOString().slice(0,10)+"T00:00:00.000Z",n.dataType!="DateTime"||I||!M?n.highValue=M:n.highValue=new Date(M).toISOString().slice(0,10)+"T00:00:00.000Z",n.medianValue=l.length===0?null:l.length%2===0?n.dataType=="Integer"?Math.round((l[t-1]+l[t])/2):(l[t-1]+l[t])/2:l[t],n.numericPrecision=D),l.length>0){let a=n.avgValue??0,s=l.length,i=0,u=0;for(let g of l){let y=g-a;i+=y*y,u+=y*y*y}let d=i/s;n.skewness=d===0?0:u/s/Math.pow(Math.sqrt(d),3),n.stdDev=Math.sqrt(d)}f!==null&&(n.sum=f);let r=Array.from(h.entries()).sort((a,s)=>s[1]-a[1]);if(n.topCategories=r.slice(0,10).map(a=>a[1]),!n.isMeasure&&r.length>0){if(n.dataType==="String"){let s=r.map(u=>u[0]);n.formatSignature=H(s);let i=/^(UUID|EMAIL_LIKE|URL_LIKE|PHONE_LIKE|NUMERIC_ID|HEX_ID|OPAQUE_ID_ALPHANUMERIC|DATE_STR|BOOLEAN)$/;n.formatSignature&&!i.test(n.formatSignature)&&(n.avgLength===void 0||n.avgLength>=3)&&(n.isFreeText=!0)}else n.topCategoryValues=r.slice(0,5).map(s=>s[0]);if(e>=20){let s=r.map(u=>u[0]),i=k(s,N);if(i!==null)n.ordinalPattern=i.pattern,n.orderedDomain=i.orderedDomain;else if(n.dataType==="String"){let u=F(s);u!==null&&(n.safeDistinctValues=u)}}let a=U(r.map(s=>s[0]),n.name,N);a!==null&&(n.geoKind=a.geoKind,n.geoMatchPct=a.geoMatchPct,a.geoAmbiguous&&(n.geoAmbiguous=!0))}if(l.length>=8&&(n.dataType==="Integer"||n.dataType==="Decimal")){let a=s=>l[Math.floor((l.length-1)*s)];n.quantiles={p05:a(.05),p25:a(.25),p75:a(.75),p95:a(.95)}}}}updateColumnStats10(e,o,c,f,n,b,I){e>=10&&(o.blankCount=this._rows.length-c,o.distinctCount=f.size+(o.blankCount!=0?1:0),o.valueNature="Categorical",c>0&&(o.dataType==="Integer"||o.dataType==="Decimal"?o.valueNature=B({dataType:o.dataType,isMeasure:!!o.isMeasure,name:o.name,distinct:f.size,nonblank:c,prec:n,maxval:b,minval:I}):o.dataType==="DateTime"&&(o.valueNature=o.dateWithTime?"Continuous":"Ordinal")))}getRowCount(){return this._rows.length}getLeafCardinality(){if(this._leafCardinality!==null)return this._leafCardinality;let e=[];if(this._cols.forEach((c,f)=>{c.isMeasure||e.push(f)}),e.length===0)return this._leafCardinality=this._rows.length,this._leafCardinality;let o=new Set;for(let c of this._rows)o.add(JSON.stringify(e.map(f=>c[f])));return this._leafCardinality=o.size,this._leafCardinality}_leafCardinality=null;obfuscateString(e){let o="abcdefghijklmnopqrstuvwxyz",c=()=>o[Math.floor(x()*o.length)],f=()=>c().toUpperCase(),n=()=>Math.floor(x()*10).toString(),b=t=>/[A-Z]/.test(t)?f():/[a-z]/.test(t)?c():/[0-9]/.test(t)?n():t,I=e.includes("@")&&e.includes("."),T=I?e.split("@"):[e],M=I?T[1]:"",D=M.endsWith(".com"),h=D?".com":"",N=D?M.slice(0,-4):M,l=t=>{let r="";for(let a of t)r+=b(a),/[a-zA-Z0-9]/.test(a)&&x()<.2&&(r+=b(a));if(r.length>6){let a=Math.floor(x()*Math.min(3,r.length-6));for(let s=0;s<a;s++){let i=0;for(;i<5;){let u=Math.floor(x()*r.length);if(/[a-zA-Z0-9]/.test(r[u])){r=r.slice(0,u)+r.slice(u+1);break}i++}}}return r};if(I){let t=l(T[0]),r=l(N);return`${t}@${r}${h}`}else return l(e)}toObjectArray(){return this._rows.map(e=>{let o={};return this._cols.forEach((c,f)=>{o[c.name]=e[f]}),o})}async getCSVAsync(e){let o=[],c=e?25:1e7,f=e?4e3:1e7,n=new Map;for(let I of this._rows){let T={};for(let M=0;M<this._cols.length;M++){let D=this._cols[M],h=I[M];if(this.STR(h)!=""){if(e&&D.dataType=="String")if(n.has(h))h=n.get(h);else{let N=this.obfuscateString(h);n.set(h,N),h=N}else D.dataType=="DateTime"&&!D.dateWithTime&&(h=new Date(h).toISOString().slice(0,10)+"T00:00:00.000Z");f-=this.STR(h).length}else h=null;T[M]=h,--f}if(o.push(T),--c,c<=0||f<=0)break}return await X.unparse(o,{header:!1})}getCSVHeaderLine(){return X.unparse([this._cols.map(e=>this.STR(e.name))])}addRow(e,o){let c="";for(let n of e)c+=this.STR(n)+"~";let f=G(c);return this._rowHashes.has(f)?!1:(this._rows.push(e),this._origIndices.push(o??-1),this._rowHashes.add(f),!0)}getOriginalRowIndex(e){return e<0||e>=this._origIndices.length?-1:this._origIndices[e]}reset(){this._cols=[],this._rows=[],this._origIndices=[],this._rowHashes=new Set,this._leafCardinality=null}setColumns(e){this._cols=e}};export{at as a,ct as b,mt as c,ft as d,B as e,K as f};