@bicharts/shape-core 0.6.35 → 0.6.37

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,4 @@
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{u as c}from"./chunk-NFSQ4O5R.mjs";import{gzip as h}from"pako";var x=e=>h(e);function O(e){return w(x(JSON.stringify(e))).replace(/\//g,".")}function w(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function P(e){if(typeof e!="string"||e==="")throw new TypeError("keyedSigner needs the host's signing key");return{sign:t=>String(c(t+e))}}function W(e,t){let r=t.sign(e);if(typeof r!="string"||r.trim()==="")throw new TypeError("the host's signer returned a blank signature");return r}function u(e,t){if(e==null||typeof e!="object")return;let r=e,n=r[t];return n??r[t.charAt(0).toUpperCase()+t.slice(1)]}function S(e){return String(e??"").toLowerCase().includes("ndjson")}function C(e){let t=null;try{t=e.headers?.get?.("content-type")??null}catch{t=null}return{status:typeof e.status=="number"?e.status:0,...typeof e.statusText=="string"?{statusText:e.statusText}:{},contentType:t,body:e.body??null,text:()=>e.text()}}function m(e,t,r){let n=e.trim();if(!n)return{result:null,typed:!1,parsed:!1};let i;try{i=JSON.parse(n)}catch{return{result:null,typed:!1,parsed:!1}}return f(i,t,r)}function f(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return{result:null,typed:!1,parsed:!0};let n=u(e,"type");if(n!=null){if(n==="progress"){let s=String(u(e,"stage")??"").trim(),o=String(u(e,"stageId")??"").trim();return s&&t?.(s,o||void 0),{result:null,typed:!0,parsed:!0}}if(n==="result"){let s=u(e,"result");return{result:s&&typeof s=="object"?s:null,typed:!0,parsed:!0}}return{result:null,typed:!0,parsed:!0}}return r?{result:u(e,"code")!==void 0||u(e,"errorMessage")!==void 0?e:null,typed:!1,parsed:!0}:{result:e,typed:!1,parsed:!0}}var a=class{constructor(t){this.onStage=t}onStage;result=null;anyParsed=!1;take(t){let r=m(t,this.onStage,!0);r.parsed&&(this.anyParsed=!0),r.result&&(r.typed||this.result===null)&&(this.result=r.result)}};function d(){return new Error("the generate response ended without a result")}async function R(e,t){let r=e.body;if(!r||typeof r.getReader!="function")return p(await e.text(),t,null);let n=r.getReader(),i=new TextDecoder,s=new a(t),o="";try{for(;;){let{done:y,value:g}=await n.read();if(y)break;o+=i.decode(g,{stream:!0});let l;for(;(l=o.indexOf(`
3
+ `))>=0;)s.take(o.slice(0,l)),o=o.slice(l+1)}}finally{try{n.releaseLock?.()}catch{}}if(o+=i.decode(),s.take(o),!s.result)throw d();return s.result}function p(e,t,r){let n=new a(t);for(let i of e.split(`
4
+ `))n.take(i);if(n.result)return n.result;throw!n.anyParsed&&r?r:d()}async function k(e,t){let r=await e.text(),n;try{n=JSON.parse(r)}catch(s){return p(r,t,s)}if(!n||typeof n!="object"||Array.isArray(n))throw new SyntaxError("the generate response was JSON but not a result object");let i=f(n,t,!1);if(i.result)return i.result;throw d()}async function v(e,t){return S(e.contentType)?R(e,t):k(e,t)}export{x as a,O as b,P as c,W as d,u as e,S as f,C as g,v as h};
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 ln,b as un}from"./chunk-UQU75XXR.mjs";import{a as cn,b as j,c as dn,d as B,e as h,f as mn,g as H,h as fn}from"./chunk-JF3BJI7F.mjs";import{a as nn,b as rn,c as on,d as sn,e as an}from"./chunk-FNEHWEWX.mjs";import{A as zt,B as Kt,C as Wt,D as $t,E as jt,F as Bt,G as Ht,H as Yt,I as Qt,J as Xt,K as Zt,L as Jt,M as en,O as tn,a as ft,b as pt,c as yt,d as gt,e as Tt,f as Et,g as Rt,h as St,i as xt,j as vt,k as Lt,l as Pt,m as wt,n as Mt,o as At,p as Nt,q as _t,r as Ft,s as It,t as kt,u as Ot,v as Vt,w as Dt,x as Gt,y as Ut,z as qt}from"./chunk-KKSQBV76.mjs";import{a as ht}from"./chunk-QEH7WTLB.mjs";import{a as Ct,b as bt}from"./chunk-2LR73DNS.mjs";import{a as oe,b as ie,c as ut,d as ct,e as dt,f as mt}from"./chunk-6TVBXT4G.mjs";import{a as O,f as V,g as w,h as D,i as W,j as Je,k as et,l as re,m as P,n as tt,o as nt,p as rt,q as G,r as ot,s as it,t as st,u as at,v as $,w as lt}from"./chunk-TPVDJHU6.mjs";import"./chunk-5MRZID36.mjs";import{a as Qe,b as Xe,c as Ze}from"./chunk-6Q3MQ2MK.mjs";import{A as je,B as Be,C as He,D as Ye,a as Se,b as xe,c as ve,d as Le,e as Pe,f as z,g as we,h as Me,i as Ae,j as Ne,k as _e,l as Fe,m as Ie,n as ke,o as Oe,p as Ve,q as De,r as Ge,s as Ue,u as K,v as qe,w as ze,x as Ke,y as We,z as $e}from"./chunk-NFSQ4O5R.mjs";var Y=2,le=400;function X(t){return!!V(t)}function _(t){let e=new Set;for(let r of t){if(r==null)continue;let o=O(String(r));if(!D(o)&&!e.has(o)&&(e.add(o),e.size>=le))break}return Array.from(e)}function N(t){let e=_(t);if(e.length===0||Z(t)<95)return!1;let r=e.filter(u=>X(u)&&!P(u)).length,o=e.filter(u=>!X(u)&&!!P(u)).length;return r>=1&&r>=o}function se(t,e){if(!P(t))return!1;let r=V(t);return r?e==="world"?!0:re.has(r):!1}function Z(t){let e=_(t);if(e.length===0)return 0;let r=0;for(let o of e)X(o)&&r++;return Math.round(r/e.length*1e3)/10}function U(t){let e=_(t);if(e.length===0)return 0;let r=0;for(let o of e)P(o)&&r++;return Math.round(r/e.length*1e3)/10}function ee(t){let e=new Set;for(let r of t){if(r==null)continue;let o=String(r).trim();if(!D(O(o))&&!e.has(o)&&(e.add(o),e.size>=le))break}return Array.from(e)}function J(t){let e=ee(t);if(e.length===0)return 0;let r=0;for(let o of e)G(o).length>0&&r++;return Math.round(r/e.length*1e3)/10}function ae(t,e){return ie(e,oe)?!0:ee(t).some(r=>/^\d{5}(-\d{4})?$/.test(r.replace(/\.0+$/,"")))}function pn(t,e){let r=_(t);if(r.length===0)return 0;let o=0;for(let u of r)$(u,e)&&o++;return Math.round(o/r.length*1e3)/10}function Q(t,e){let r=0;for(let o of _(t))e(o)&&r++;return r}function yn(t,e){let r=0;for(let o of ee(t))e(o)&&r++;return r}function gn(t,e,r,o,u){let l=[],a=[],i={},E={},T=new Set(t),C=s=>e.map(c=>c[s]);for(let s of["city","country"]){let c=r?.[s];c&&T.has(c)&&(i[s]=c)}let S=new Set(u??t);for(let s of["lat","lon"]){let c=r?.[s];c&&S.has(c)&&(i[s]=c)}let y=r?.zip;if(y&&T.has(y)){let s=C(y),c=J(s);c<95?a.push(`zip=${y} (only ${c}% of values read as ZIPs)`):ae(s,y)?i.zip=y:a.push(`zip=${y} (all values are 3-4 digits with nothing to say they are postal)`)}let f=r?.state;if(f&&T.has(f)){let s=C(f),c=_(s);c.length>0&&c.every(p=>se(p,o))?a.push(`state=${f} (every value is "CA", which is both Canada and California)`):N(s)?(a.push(`state=${f} (every value is a country, not a state)`),i.country||(i.country=f)):U(s)<95?a.push(`state=${f} (only ${U(s)}% of values are states/provinces)`):i.state=f}let m=new Set(Object.values(i).filter(Boolean)),g=t.filter(s=>!m.has(s)&&!s.startsWith("__"));if(!i.state){let s=null;for(let c of g){let p=C(c);if(N(p))continue;let v=U(p);if(v<95)continue;let q=Q(p,k=>!!P(k)),Re=Q(p,k=>!!P(k)&&!se(k,o));q<Y&&Re<1||(!s||v>s.pct)&&(s={name:c,pct:v})}s&&(i.state=s.name,m.add(s.name),l.push(`state=${s.name} (${s.pct}% states/provinces)`))}if(!i.zip)for(let s of g){if(m.has(s))continue;let c=C(s),p=J(c);if(!(p<95)&&ae(c,s)&&!(yn(c,v=>G(v).length>0)<Y)){i.zip=s,m.add(s),l.push(`zip=${s} (${p}% ZIP codes)`);break}}let b=i.country;if(!b||!N(C(b))){let s=null;for(let c of g){if(m.has(c)||!N(C(c)))continue;let p=Z(C(c));(!s||p>s.pct)&&(s={name:c,pct:p})}s&&(b&&(a.push(`country=${b} (only ${Z(C(b))}% of values are country identifiers; using ${s.name} instead)`),E.country=b),i.country=s.name,m.add(s.name),l.push(`country=${s.name}`))}if(!i.city){let s=null;for(let c of g){if(m.has(c))continue;let p=C(c),v=pn(p,o);v<W||Q(p,q=>$(q,o))<Y||(!s||v>s.pct)&&(s={name:c,pct:v})}s&&(i.city=s.name,l.push(`city=${s.name} (${s.pct}% known cities)`))}let x=i.country?C(i.country):[],A=!!i.country&&N(x),I=A?new Set(x.map(s=>V(s==null?null:String(s))).filter(Boolean)).size:0,R=A&&I>=2,L=!!(i.lat&&i.lon)&&e.some(s=>{let c=+String(s[i.lat]??"").trim(),p=+String(s[i.lon]??"").trim();return isFinite(c)&&isFinite(p)&&c>=-90&&c<=90&&p>=-180&&p<=180&&String(s[i.lat]??"").trim()!==""&&String(s[i.lon]??"").trim()!==""});return i.lat&&i.lon&&!L&&a.push(`lat/lon=${i.lat}/${i.lon} (no row holds a usable coordinate pair)`),i.country&&!R&&!(i.city||i.state||i.zip||L)&&a.push(A?`country=${i.country} (every row resolves to the same country - nothing to place apart)`:`country=${i.country} (values are not country identifiers)`),{bind:!!(i.city||i.state||i.zip||R||L)?i:null,backfilled:l,refused:a,...Object.keys(E).length?{labelFallback:E}:{}}}var n=(t,...e)=>({part:t,langs:Object.freeze(e)}),te=Object.freeze({jaar:n("year","nl"),kwartaal:n("quarter","nl"),maand:n("month","nl"),dag:n("day","nl","sv","da","nb"),jahr:n("year","de"),quartal:n("quarter","de"),monat:n("month","de"),tag:n("day","de"),ann\u00E9e:n("year","fr"),mois:n("month","fr"),jour:n("day","fr"),trimestre:n("quarter","fr","es","pt","it"),a\u00F1o:n("year","es"),mes:n("month","es"),d\u00EDa:n("day","es"),ano:n("year","pt"),m\u00EAs:n("month","pt"),dia:n("day","pt"),anno:n("year","it"),mese:n("month","it"),giorno:n("day","it"),\u0433\u043E\u0434:n("year","ru"),\u043C\u0435\u0441\u044F\u0446:n("month","ru"),\u0440\u0456\u043A:n("year","uk"),\u043C\u0456\u0441\u044F\u0446\u044C:n("month","uk"),\u043A\u0432\u0430\u0440\u0442\u0430\u043B:n("quarter","ru","uk"),\u0434\u0435\u043D\u044C:n("day","ru","uk"),rok:n("year","pl","cs","sk"),kwarta\u0142:n("quarter","pl"),miesi\u0105c:n("month","pl"),dzie\u0144:n("day","pl"),\u010Dtvrtlet\u00ED:n("quarter","cs"),m\u011Bs\u00EDc:n("month","cs"),den:n("day","cs"),\u0161tvr\u0165rok:n("quarter","sk"),mesiac:n("month","sk"),de\u0148:n("day","sk"),\u00E5r:n("year","sv","da","nb"),kvartal:n("quarter","sv","da","nb"),m\u00E5nad:n("month","sv"),m\u00E5ned:n("month","da","nb"),vuosi:n("year","fi"),vuosinelj\u00E4nnes:n("quarter","fi"),kuukausi:n("month","fi"),p\u00E4iv\u00E4:n("day","fi"),\u00E9v:n("year","hu"),negyed\u00E9v:n("quarter","hu"),h\u00F3nap:n("month","hu"),nap:n("day","hu"),y\u0131l:n("year","tr"),\u00E7eyrek:n("quarter","tr"),ay:n("month","tr"),g\u00FCn:n("day","tr"),\u03AD\u03C4\u03BF\u03C2:n("year","el"),\u03C4\u03C1\u03AF\u03BC\u03B7\u03BD\u03BF:n("quarter","el"),\u03BC\u03AE\u03BD\u03B1\u03C2:n("month","el"),\u03B7\u03BC\u03AD\u03C1\u03B1:n("day","el"),an:n("year","ro"),trimestru:n("quarter","ro"),lun\u0103:n("month","ro"),zi:n("day","ro"),godina:n("year","hr"),tromjese\u010Dje:n("quarter","hr"),mjesec:n("month","hr"),dan:n("day","hr"),\u5E74:n("year","ja","zh"),\u56DB\u534A\u671F:n("quarter","ja"),\u5B63\u5EA6:n("quarter","zh"),\u6708:n("month","ja","zh"),\u65E5:n("day","ja","zh"),\uC5F0\uB3C4:n("year","ko"),\uBD84\uAE30:n("quarter","ko"),\uC6D4:n("month","ko"),\uC77C:n("day","ko"),tahun:n("year","id"),kuartal:n("quarter","id"),triwulan:n("quarter","id"),bulan:n("month","id"),hari:n("day","id"),n\u0103m:n("year","vi"),qu\u00FD:n("quarter","vi"),th\u00E1ng:n("month","vi"),ng\u00E0y:n("day","vi"),\u0E1B\u0E35:n("year","th"),\u0E44\u0E15\u0E23\u0E21\u0E32\u0E2A:n("quarter","th"),\u0E40\u0E14\u0E37\u0E2D\u0E19:n("month","th"),\u0E27\u0E31\u0E19:n("day","th"),\u0627\u0644\u0633\u0646\u0629:n("year","ar"),\u0633\u0646\u0629:n("year","ar"),\u0627\u0644\u0639\u0627\u0645:n("year","ar"),\u0639\u0627\u0645:n("year","ar"),\u0627\u0644\u0631\u0628\u0639:n("quarter","ar"),\u0631\u0628\u0639:n("quarter","ar"),"\u0631\u0628\u0639 \u0627\u0644\u0633\u0646\u0629":n("quarter","ar"),\u0627\u0644\u0634\u0647\u0631:n("month","ar"),\u0634\u0647\u0631:n("month","ar"),\u0627\u0644\u064A\u0648\u0645:n("day","ar"),\u064A\u0648\u0645:n("day","ar"),\u05E9\u05E0\u05D4:n("year","he"),\u05E8\u05D1\u05E2\u05D5\u05DF:n("quarter","he"),\u05D7\u05D5\u05D3\u05E9:n("month","he"),\u05D9\u05D5\u05DD:n("day","he"),\u0935\u0930\u094D\u0937:n("year","hi"),\u0938\u093E\u0932:n("year","hi"),\u0924\u093F\u092E\u093E\u0939\u0940:n("quarter","hi"),\u092E\u0939\u0940\u0928\u093E:n("month","hi"),\u092E\u093E\u0939:n("month","hi"),\u0926\u093F\u0928:n("day","hi"),\u0633\u0627\u0644:n("year","fa"),\u0645\u0627\u0647:n("month","fa"),\u0631\u0648\u0632:n("day","fa")}),hn=Object.freeze(Array.from(new Set(Object.values(te).flatMap(t=>t.langs)))),ue=Object.freeze(["fa","ar","he","th"]),ce=1900,de=2100;function Cn(t,e){let r=[],o=z(e);try{o&&r.push(t.toLocaleLowerCase(o.intl))}catch{}let u=t.toLowerCase();return r.includes(u)||r.push(u),r}function bn(t,e){let r=String(t??"").trim().normalize("NFC");if(!r)return null;for(let o of Cn(r,e)){let u=te[o];if(u&&u.langs.includes(e))return u.part}return null}function Tn(t,e){return ue.includes(t)?typeof e=="number"&&Number.isFinite(e)&&e>=ce&&e<=de:!0}function me(t,e){let r=e?.freemiumMaxShapeColumns;return typeof r!="number"||!isFinite(r)||r<1?null:!isFinite(t)||t<=r?0:Math.round(t-r)}function En(t,e,r){let o=me(t,e);if(o===null||o<=0)return null;let u=typeof e?.freemiumColumnCapPivot=="number"?e.freemiumColumnCapPivot:4,l=o>u?e?.freemiumColumnCapMessageMany:e?.freemiumColumnCapMessageFew;if(typeof l!="string"||l.trim().length===0)return null;let a=l.split("{n}").join(String(o)).split("{fields}").join(o===1?"field":"fields"),i=fe(r);return i.length===0?a:a+" "+i.join(" ")}function fe(t){if(!t||t.length===0)return[];let e=[],r=new Map,o=new Map;for(let l of t){let a=typeof l?.dateGroupId=="string"?l.dateGroupId.trim():"";if(a!==""&&(r.has(a)||(e.push(a),r.set(a,0)),l.isDatePart===!0&&r.set(a,r.get(a)+1),l.isReassembledDate===!0&&!o.has(a))){let i=typeof l.sourceField=="string"?l.sourceField.trim():"",E=typeof l.name=="string"?l.name.trim():"",T=i!==""?i:E;T!==""&&o.set(a,T)}}let u=[];for(let l of e){let a=o.get(l),i=r.get(l)??0;!a||i===0||u.push(`'${a}' is a date hierarchy and counts as ${i+1} fields - bind the date itself instead of its hierarchy.`)}return u}var d=t=>t==null?"":String(t),M=t=>t===!0,pe=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);return Number.isFinite(e)?e:null}return null},Rn=[["city","CityColumn"],["state","StateColumn"],["zip","ZipColumn"],["lat","LatColumn"],["lon","LonColumn"],["country","CountryColumn"]];function ye(t,e){let r={};for(let[o,u]of Rn){let l=d(h(t,e+u));l&&(r[o]=l)}return r}function Sn(t){let e=i=>h(t,i),r=e("retryAfterSeconds"),o=e("overrideThumbnailUpload"),u=e("forceThumbnailUpload"),l=ye(t,"point"),a=ye(t,"destPoint");return Object.keys(a).length&&(l.dest=a),{errorMessage:d(e("errorMessage")),code:d(e("code")),language:d(e("language")),version:Number(e("version")??0),codeSummary:d(e("codeSummary")),chartName:d(e("chartName")??e("chartType")),finalChartName:d(e("finalChartName")),warningMessage:d(e("warningMessage")),outputHash:d(e("outputHash")),validatorToken:d(e("validatorToken")),editCodeKey:d(e("editCodeKey")),signedLLMRequestID:d(e("signedLLMRequestID")),userReply:d(e("userReply")),userReplyOutcome:d(e("userReplyOutcome")),improvementSuggestion:d(e("improvementSuggestion")),geoColumn:d(e("geoColumn")),geoKind:d(e("geoKind")),geoPointCols:Object.keys(l).length?l:null,creditBalanceBefore:pe(e("creditBalanceBefore")),creditCost:pe(e("creditCost")),isServiceError:M(e("isServiceError")),isRateLimited:M(e("isRateLimited")),isRefusal:M(e("isRefusal")),isVersionNotFound:M(e("isVersionNotFound")),isGenerationCancelled:M(e("isGenerationCancelled")),retryAfterSeconds:typeof r=="number"&&Number.isFinite(r)?r:null,servedCorrelationId:d(e("servedCorrelationId")),...typeof o=="boolean"?{overrideThumbnailUpload:o}:{},...typeof u=="boolean"?{forceThumbnailUpload:u}:{}}}var ge=t=>t==null?void 0:Number(t),F=t=>d(t)||void 0;function xn(t){let e=h(t,"charts"),r=h(t,"refused"),o=Array.isArray(e)?e.map(l=>{let a=E=>h(l,E),i=a("recommended");return{name:d(a("chartTypeName")??a("name")),description:d(a("description")??a("chartDesc")),rank:ge(a("rank")),score:ge(a("score")),renderer:F(a("renderer")),language:F(a("language")),isPreview:M(a("isPreview")),recommended:typeof i=="boolean"?i:void 0,viaProjection:F(a("viaProjection")),viaProjectionKey:F(a("viaProjectionKey")),detailNote:F(a("detailNote"))}}).filter(l=>l.name):null,u=Array.isArray(r)?r.map(l=>({name:d(h(l,"chartTypeName")??h(l,"name")),reason:d(h(l,"reason")),isVeto:M(h(l,"isVeto"))})).filter(l=>l.name):[];return{errorMessage:d(h(t,"errorMessage")),charts:o,refused:u,noFitSummary:d(h(t,"noFitSummary"))}}function vn(t){return!t||typeof t!="object"?null:{status:String(h(t,"status")??""),verdictReason:h(t,"verdictReason")??null,instruction:h(t,"instruction")??null,fix:h(t,"fix")??null,errorMessage:h(t,"errorMessage")??null}}function Ln(t){let e=t.linkNonce?(t.linkNonce()??"").trim():null,r=e?{licensee:"",licenseKey:"",secretKey:""}:t.triple();return{request:{licenseKey:r.licenseKey,licensee:r.licensee,secretKey:r.secretKey,freemiumKey:t.freemiumKey?.()??""},linkNonce:e}}function Pn(t){let{width:e,height:r}=t.measure();return{request:{height:r,width:e},hints:{viewportWidth:e,viewportHeight:r}}}function wn(t){let e=0;for(let r of t){if(r.isMeasure)continue;let o=r.distinctCount;typeof o=="number"&&o>e&&(e=o)}return e}function he(t){if(t.recoveryFetchByCorrelation)return{version:null,fetchOnly:!0};if(t.recoveryFetchVersion!=null)return{version:t.recoveryFetchVersion,fetchOnly:!0};let e=t.settingVersion??null;if(t.genNew)return{version:e,fetchOnly:void 0};let r=(e??0)>0?e:null,o=(t.codeVersion??0)>0?t.codeVersion:null,u=r??o??e;return{version:u,fetchOnly:u!=null&&u>0?!0:void 0}}function Mn(t){let e=t.fetchCorrelationId!=null,o=e||t.recoveryFetchVersion!=null?!1:t.genNew,u=he({genNew:o,recoveryFetchVersion:t.recoveryFetchVersion,recoveryFetchByCorrelation:e,settingVersion:t.settingVersion,codeVersion:t.codeVersion});return{genNew:o,version:u.version,fetchOnly:u.fetchOnly,fetchCorrelationId:t.fetchCorrelationId??void 0}}function An(t){let e=r=>t.renderers.has(r);return{supportsD3:e("D3"),supportsPlotly:e("PLOTLY"),supportsVega:e("VEGA")}}function Nn(t){let e=t.cap!=null&&t.budget>t.cap?t.cap:t.budget;return{triesLeft:t.triesLeft??e,maxTries:e}}function _n(t){return t&&t>0?{leafCardinality:Math.round(t)}:{}}function Ce(t,e){return t!=null&&e!=null&&t!==e}function Fn(t,e){return t?Ce(e.capturedFor,e.now)?{shortlist:void 0,stale:!0}:{shortlist:{...t,ageMs:e.atMs>0?Math.max(0,Math.round(e.nowMs-e.atMs)):void 0},stale:!1}:{shortlist:void 0,stale:!1}}var In=Object.freeze({integer:"number",decimal:"number",double:"number",datetime:"date",date:"date",boolean:"boolean",string:"text"});function be(t){let e=String(t??"").trim().toLowerCase();return In[e]??e}function Te(t){let e="";for(let r of t)e+=JSON.stringify([String(r.name??""),r.isMeasure?"M":"D",be(r.dataType)]);return e}function kn(t){return K(Te(t))}var On=2,Vn=3,Dn=4,Gn=64,Un=8e3,qn=6e4,zn=Object.freeze({RENDER_START:"render-start",RENDER_OK:"render-ok",RENDER_ERROR:"render-error",VIEW:"view",VIEW_VERDICT:"view-verdict"});function Kn(t){return!!t&&!t.includes("|")&&!t.includes(",")}function ne(t,e,r,o){let u=`${t},${e}|${r}`;return o?`${u}|${Math.max(0,Math.round(o.count))}|${o.nonce}`:u}function Wn(t,e){let r=t;if(!r||!r.signer||typeof r.signer.sign!="function")throw new TypeError("createTelemetryClient needs the host's signer");if(!r.transport||typeof r.transport.post!="function")throw new TypeError("createTelemetryClient needs the host's transport");if(!r.clock||typeof r.clock.now!="function")throw new TypeError("createTelemetryClient needs the host's clock");if(!e||typeof e.baseUrl!="string"&&typeof e.baseUrl!="function")throw new TypeError("createTelemetryClient needs the service's base URL");if(typeof e.baseUrl=="string"&&e.baseUrl==="")throw new TypeError("createTelemetryClient needs the service's base URL");if(typeof e.clientVersion!="string"||e.clientVersion==="")throw new TypeError("createTelemetryClient needs the client version");if(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new TypeError("createTelemetryClient needs a positive deadline in milliseconds");let{signer:o,transport:u,clock:l}=r,a=e.apiPath??"/api",i=e.timeoutMs,E=()=>typeof e.baseUrl=="function"?e.baseUrl():e.baseUrl,T=S=>{try{e.onFailure?.(S)}catch{}},C=async(S,y,f,m)=>{let g;try{let b=await u.post(y,f,m,{timeoutMs:i});g=b.status;try{b.body?.cancel().catch(()=>{})}catch{}}catch(b){T({channel:S,stage:"post",status:null,error:b});return}(g<200||g>299)&&T({channel:S,stage:"status",status:g,error:null})};return{async sendClientMessage(S){let y,f,m;try{y=`${E()}${a}/LogClientMsg/?nocache=${l.now()}`,f=j(S),m=B(f,o)}catch(g){T({channel:"client-message",stage:"build",status:null,error:g});return}await C("client-message",y,f,{"Content-Type":"text/plain","X-Signature":m})},async countEvent(S,y,f){let m,g;try{m=`${E()}${a}/eventlog`,g=ne(S,e.clientVersion,y,f)}catch(b){T({channel:"event-count",stage:"build",status:null,error:b});return}await C("event-count",m,g,{"Content-Type":"text/plain"})}}}function Ee(t){return Object.assign(new Error(`The request did not finish within ${t} ms.`),{name:"TimeoutError"})}function $n(t,e={}){if(typeof t!="function")throw new TypeError("fetchTransport needs the host's fetch");let r=t,o=e.credentials??"omit";return{async post(u,l,a,i){let E=i.timeoutMs,T=new AbortController,C=!1,S=setTimeout(()=>{C=!0,T.abort(Ee(E))},E),y=()=>T.abort(i.signal?.reason);i.signal&&(i.signal.aborted?y():i.signal.addEventListener("abort",y,{once:!0}));let f=!1,m=()=>{f||(f=!0,clearTimeout(S),i.signal?.removeEventListener("abort",y))},g=R=>C?Ee(E):R,b;try{b=await r(u,{method:"POST",body:l,headers:a,credentials:o,signal:T.signal})}catch(R){throw m(),g(R)}let x=H(b);if(!x.body)return{status:x.status,contentType:x.contentType,body:null,text:async()=>{try{return await x.text()}catch(R){throw g(R)}finally{m()}}};let A=x.body.getReader(),I=new ReadableStream({async pull(R){try{let L=await A.read();if(L.done){m(),R.close();return}R.enqueue(L.value)}catch(L){m(),R.error(g(L))}},cancel(R){return m(),A.cancel(R)}});return{status:x.status,contentType:x.contentType,body:I,text:()=>new Response(I).text()}}}}export{W as CITY_ROLE_MATCH_PCT,zn as CLIENT_EVENT_KINDS,Ie as COMPOUND_MIN_STEM,de as DATE_LEVEL_GREGORIAN_YEAR_MAX,ce as DATE_LEVEL_GREGORIAN_YEAR_MIN,hn as DATE_LEVEL_LANGUAGES,te as DATE_LEVEL_NAMES,ue as DATE_LEVEL_NON_GREGORIAN_LANGUAGES,Gt as DEFAULT_GAP_FACTOR,Ke as DEFAULT_TEMPERATURE,qe as GET_RANDOM,Oe as GLUED_STEM_MIN,Et as INTENSIVE_SUFFIX_TOKENS,Tt as INTENSIVE_WORD_TOKENS,tn as IndexedText,Ut as MAX_RUN_BOUNDS,St as POSITIONAL_SUFFIX_TOKENS,Rt as POSITIONAL_WORD_TOKENS,ln as PREVIEW_OMITTED_FIELDS,w as ROLE_MATCH_PCT,Kt as SERIES_COMPLETENESS_MAX_LISTED,Wt as SERIES_COMPLETENESS_MIN_FILL,$t as SERIES_KEY_MAX_DISTINCT,Dn as SEV_ERROR,On as SEV_INFO,Gn as SEV_USER_PRESENTED,Vn as SEV_WARNING,K as SIMPLE_STRING_HASH,Ue as STR,De as SUBSTRING_MIN,Se as SUPPORTED_LANGUAGES,xe as SUPPORTED_LANGUAGE_CODES,qn as TELEMETRY_TIMEOUT_DEV_MS,Un as TELEMETRY_TIMEOUT_MS,Pe as VOCABULARY_LANGUAGE_CODES,Le as VOCABULARY_ONLY_LANGUAGES,U as admin1MatchPct,_t as allowedAggregations,mt as buildGeoIsoColumn,st as buildGeoPointColumns,An as capabilityFields,lt as cityMatchPct,at as cityTagsFor,Jt as classifyAdditivity,Nt as classifyForAggregation,en as classifyNumericValueNature,Xt as classifyTemporal,Pt as codeNeedsLegacyAggNames,Ot as codeReadsColumn,Vt as codeReadsColumnsByRoleOrPosition,Lt as collapseRepeatedAggPrefix,Dt as columnsTheCodeReads,yt as countryRegion,Wn as createTelemetryClient,Ln as credentialFields,bn as dateLevelPart,Tn as dateLevelYearAdmits,nn as decimalSeparatorOf,Ft as defaultAggregation,rn as detectDecimalSeparator,ht as detectFormatSignature,ut as detectGeo,Ze as detectOrdinalDomain,Qt as detectTextDatePattern,j as encodePayload,sn as engineTypeForSqlType,wt as englishImplicitAggNames,ne as eventLogLine,Mn as fetchFields,$n as fetchTransport,Me as foldName,En as freemiumColumnCapRefusal,me as freemiumColumnsOverCap,fe as freemiumDateHierarchyClauses,Ve as gluedPrefixStems,cn as gzipWireText,vt as hasDefaultAggPrefix,_e as hasUnsegmentedScript,Zt as hostAggHint,an as ingest,It as isAggregationAllowed,D as isBlankLike,et as isCityTableLoaded,ze as isDeterministicRefusal,Kn as isEventLogCode,ot as isGeoPointAmbiguity,Yt as isIdentifierName,dt as isJoinGeoKind,mn as isNdjsonContentType,Qe as isOrdinalFriendlyName,dn as keyedSigner,_n as leafCardinalityField,He as localMidnightDateColumns,Be as localMidnightToUtcDay,N as looksLikeCountryColumn,Ge as matchNameToken,wn as maxNonMeasureCardinality,zt as measureCadence,Ht as measureSeriesCompleteness,B as messageSignature,bt as monthLookupFor,At as nameLooksIntensiveRate,Mt as nameLooksPositional,Ae as nameWords,tt as normalizeCountry,Ye as normalizeLocalMidnightDates,Ct as normalizeMonthKey,O as normalizePlaceName,rt as normalizeZip5,Fn as offeredShortlistFor,We as parseDateStable,Sn as parseGenerateResponse,on as parseNumberText,xn as parseQualifyResponse,vn as parseReviewVerdict,qt as parseTemporalPoint,un as payloadPreview,Bt as pickSeriesColumn,fn as readGenerateStream,Ne as readName,h as readWireField,Je as registerCityTable,pt as registerIso3Regions,P as resolveAdmin1,he as resolveFetchVersion,it as resolveGeoPoint,we as resolveLanguage,gn as resolvePointRoles,Nn as retryFields,Xe as safeDistinctValuesToShip,Te as schemaIdentity,kn as schemaIdentityKey,be as schemaTypeFamily,jt as seriesKeyVerdict,kt as shareOfTotalIsHonest,Ce as shortlistIsStale,xt as stripHostAggPrefix,gt as summarizeCountryRegions,ft as summarizeGeoExtent,ve as supportedLanguage,ct as toGeoIso,Fe as unsegmentedRuns,Pn as viewportFields,z as vocabularyLanguage,$e as wholeDayFrame,je as wholeDayIso,H as wireResponseFromFetch,ke as wordEndsWith,J as zipMatchPct,G as zipPrefixCandidates,nt as zipToPrefix3};
2
+ import{a as fn,b as pn}from"./chunk-UQU75XXR.mjs";import{a as yn,b as O,c as gn,d as k,e as h,f as hn,g as Y,h as Q}from"./chunk-ARZ2GRKS.mjs";import{a as ln,b as un,c as cn,d as dn,e as mn}from"./chunk-FNEHWEWX.mjs";import{A as jt,B as Ht,C as Yt,D as Qt,E as Xt,F as Jt,G as Zt,H as en,I as tn,J as nn,K as rn,L as on,M as sn,O as an,a as Ct,b as bt,c as Tt,d as Et,e as wt,f as vt,g as Pt,h as Lt,i as Mt,j as _t,k as At,l as Ot,m as Nt,n as It,o as Ft,p as kt,q as Gt,r as Vt,s as Dt,t as Ut,u as Wt,v as qt,w as zt,x as Kt,y as $t,z as Bt}from"./chunk-KKSQBV76.mjs";import{a as St}from"./chunk-QEH7WTLB.mjs";import{a as Rt,b as xt}from"./chunk-2LR73DNS.mjs";import{a as ae,b as le,c as pt,d as yt,e as gt,f as ht}from"./chunk-6TVBXT4G.mjs";import{a as D,f as U,g as A,h as W,i as j,j as ot,k as it,l as se,m as M,n as st,o as at,p as lt,q,r as ut,s as ct,t as dt,u as mt,v as H,w as ft}from"./chunk-TPVDJHU6.mjs";import"./chunk-5MRZID36.mjs";import{a as tt,b as nt,c as rt}from"./chunk-6Q3MQ2MK.mjs";import{A as Xe,B as Je,C as Ze,D as et,a as Le,b as Me,c as _e,d as Ae,e as Oe,f as $,g as Ne,h as Ie,i as Fe,j as ke,k as Ge,l as Ve,m as De,n as Ue,o as We,p as qe,q as ze,r as Ke,s as $e,u as B,v as Be,w as je,x as He,y as Ye,z as Qe}from"./chunk-NFSQ4O5R.mjs";var X=2,de=400;function Z(t){return!!U(t)}function F(t){let e=new Set;for(let n of t){if(n==null)continue;let o=D(String(n));if(!W(o)&&!e.has(o)&&(e.add(o),e.size>=de))break}return Array.from(e)}function I(t){let e=F(t);if(e.length===0||ee(t)<95)return!1;let n=e.filter(u=>Z(u)&&!M(u)).length,o=e.filter(u=>!Z(u)&&!!M(u)).length;return n>=1&&n>=o}function ue(t,e){if(!M(t))return!1;let n=U(t);return n?e==="world"?!0:se.has(n):!1}function ee(t){let e=F(t);if(e.length===0)return 0;let n=0;for(let o of e)Z(o)&&n++;return Math.round(n/e.length*1e3)/10}function z(t){let e=F(t);if(e.length===0)return 0;let n=0;for(let o of e)M(o)&&n++;return Math.round(n/e.length*1e3)/10}function ne(t){let e=new Set;for(let n of t){if(n==null)continue;let o=String(n).trim();if(!W(D(o))&&!e.has(o)&&(e.add(o),e.size>=de))break}return Array.from(e)}function te(t){let e=ne(t);if(e.length===0)return 0;let n=0;for(let o of e)q(o).length>0&&n++;return Math.round(n/e.length*1e3)/10}function ce(t,e){return le(e,ae)?!0:ne(t).some(n=>/^\d{5}(-\d{4})?$/.test(n.replace(/\.0+$/,"")))}function Cn(t,e){let n=F(t);if(n.length===0)return 0;let o=0;for(let u of n)H(u,e)&&o++;return Math.round(o/n.length*1e3)/10}function J(t,e){let n=0;for(let o of F(t))e(o)&&n++;return n}function bn(t,e){let n=0;for(let o of ne(t))e(o)&&n++;return n}function Tn(t,e,n,o,u){let l=[],a=[],i={},S={},T=new Set(t),b=s=>e.map(d=>d[s]);for(let s of["city","country"]){let d=n?.[s];d&&T.has(d)&&(i[s]=d)}let y=new Set(u??t);for(let s of["lat","lon"]){let d=n?.[s];d&&y.has(d)&&(i[s]=d)}let m=n?.zip;if(m&&T.has(m)){let s=b(m),d=te(s);d<95?a.push(`zip=${m} (only ${d}% of values read as ZIPs)`):ce(s,m)?i.zip=m:a.push(`zip=${m} (all values are 3-4 digits with nothing to say they are postal)`)}let p=n?.state;if(p&&T.has(p)){let s=b(p),d=F(s);d.length>0&&d.every(E=>ue(E,o))?a.push(`state=${p} (every value is "CA", which is both Canada and California)`):I(s)?(a.push(`state=${p} (every value is a country, not a state)`),i.country||(i.country=p)):z(s)<95?a.push(`state=${p} (only ${z(s)}% of values are states/provinces)`):i.state=p}let c=new Set(Object.values(i).filter(Boolean)),C=t.filter(s=>!c.has(s)&&!s.startsWith("__"));if(!i.state){let s=null;for(let d of C){let E=b(d);if(I(E))continue;let P=z(E);if(P<95)continue;let K=J(E,V=>!!M(V)),Pe=J(E,V=>!!M(V)&&!ue(V,o));K<X&&Pe<1||(!s||P>s.pct)&&(s={name:d,pct:P})}s&&(i.state=s.name,c.add(s.name),l.push(`state=${s.name} (${s.pct}% states/provinces)`))}if(!i.zip)for(let s of C){if(c.has(s))continue;let d=b(s),E=te(d);if(!(E<95)&&ce(d,s)&&!(bn(d,P=>q(P).length>0)<X)){i.zip=s,c.add(s),l.push(`zip=${s} (${E}% ZIP codes)`);break}}let R=i.country;if(!R||!I(b(R))){let s=null;for(let d of C){if(c.has(d)||!I(b(d)))continue;let E=ee(b(d));(!s||E>s.pct)&&(s={name:d,pct:E})}s&&(R&&(a.push(`country=${R} (only ${ee(b(R))}% of values are country identifiers; using ${s.name} instead)`),S.country=R),i.country=s.name,c.add(s.name),l.push(`country=${s.name}`))}if(!i.city){let s=null;for(let d of C){if(c.has(d))continue;let E=b(d),P=Cn(E,o);P<j||J(E,K=>H(K,o))<X||(!s||P>s.pct)&&(s={name:d,pct:P})}s&&(i.city=s.name,l.push(`city=${s.name} (${s.pct}% known cities)`))}let w=i.country?b(i.country):[],v=!!i.country&&I(w),_=v?new Set(w.map(s=>U(s==null?null:String(s))).filter(Boolean)).size:0,x=v&&_>=2,g=!!(i.lat&&i.lon)&&e.some(s=>{let d=+String(s[i.lat]??"").trim(),E=+String(s[i.lon]??"").trim();return isFinite(d)&&isFinite(E)&&d>=-90&&d<=90&&E>=-180&&E<=180&&String(s[i.lat]??"").trim()!==""&&String(s[i.lon]??"").trim()!==""});return i.lat&&i.lon&&!g&&a.push(`lat/lon=${i.lat}/${i.lon} (no row holds a usable coordinate pair)`),i.country&&!x&&!(i.city||i.state||i.zip||g)&&a.push(v?`country=${i.country} (every row resolves to the same country - nothing to place apart)`:`country=${i.country} (values are not country identifiers)`),{bind:!!(i.city||i.state||i.zip||x||g)?i:null,backfilled:l,refused:a,...Object.keys(S).length?{labelFallback:S}:{}}}var r=(t,...e)=>({part:t,langs:Object.freeze(e)}),re=Object.freeze({jaar:r("year","nl"),kwartaal:r("quarter","nl"),maand:r("month","nl"),dag:r("day","nl","sv","da","nb"),jahr:r("year","de"),quartal:r("quarter","de"),monat:r("month","de"),tag:r("day","de"),ann\u00E9e:r("year","fr"),mois:r("month","fr"),jour:r("day","fr"),trimestre:r("quarter","fr","es","pt","it"),a\u00F1o:r("year","es"),mes:r("month","es"),d\u00EDa:r("day","es"),ano:r("year","pt"),m\u00EAs:r("month","pt"),dia:r("day","pt"),anno:r("year","it"),mese:r("month","it"),giorno:r("day","it"),\u0433\u043E\u0434:r("year","ru"),\u043C\u0435\u0441\u044F\u0446:r("month","ru"),\u0440\u0456\u043A:r("year","uk"),\u043C\u0456\u0441\u044F\u0446\u044C:r("month","uk"),\u043A\u0432\u0430\u0440\u0442\u0430\u043B:r("quarter","ru","uk"),\u0434\u0435\u043D\u044C:r("day","ru","uk"),rok:r("year","pl","cs","sk"),kwarta\u0142:r("quarter","pl"),miesi\u0105c:r("month","pl"),dzie\u0144:r("day","pl"),\u010Dtvrtlet\u00ED:r("quarter","cs"),m\u011Bs\u00EDc:r("month","cs"),den:r("day","cs"),\u0161tvr\u0165rok:r("quarter","sk"),mesiac:r("month","sk"),de\u0148:r("day","sk"),\u00E5r:r("year","sv","da","nb"),kvartal:r("quarter","sv","da","nb"),m\u00E5nad:r("month","sv"),m\u00E5ned:r("month","da","nb"),vuosi:r("year","fi"),vuosinelj\u00E4nnes:r("quarter","fi"),kuukausi:r("month","fi"),p\u00E4iv\u00E4:r("day","fi"),\u00E9v:r("year","hu"),negyed\u00E9v:r("quarter","hu"),h\u00F3nap:r("month","hu"),nap:r("day","hu"),y\u0131l:r("year","tr"),\u00E7eyrek:r("quarter","tr"),ay:r("month","tr"),g\u00FCn:r("day","tr"),\u03AD\u03C4\u03BF\u03C2:r("year","el"),\u03C4\u03C1\u03AF\u03BC\u03B7\u03BD\u03BF:r("quarter","el"),\u03BC\u03AE\u03BD\u03B1\u03C2:r("month","el"),\u03B7\u03BC\u03AD\u03C1\u03B1:r("day","el"),an:r("year","ro"),trimestru:r("quarter","ro"),lun\u0103:r("month","ro"),zi:r("day","ro"),godina:r("year","hr"),tromjese\u010Dje:r("quarter","hr"),mjesec:r("month","hr"),dan:r("day","hr"),\u5E74:r("year","ja","zh"),\u56DB\u534A\u671F:r("quarter","ja"),\u5B63\u5EA6:r("quarter","zh"),\u6708:r("month","ja","zh"),\u65E5:r("day","ja","zh"),\uC5F0\uB3C4:r("year","ko"),\uBD84\uAE30:r("quarter","ko"),\uC6D4:r("month","ko"),\uC77C:r("day","ko"),tahun:r("year","id"),kuartal:r("quarter","id"),triwulan:r("quarter","id"),bulan:r("month","id"),hari:r("day","id"),n\u0103m:r("year","vi"),qu\u00FD:r("quarter","vi"),th\u00E1ng:r("month","vi"),ng\u00E0y:r("day","vi"),\u0E1B\u0E35:r("year","th"),\u0E44\u0E15\u0E23\u0E21\u0E32\u0E2A:r("quarter","th"),\u0E40\u0E14\u0E37\u0E2D\u0E19:r("month","th"),\u0E27\u0E31\u0E19:r("day","th"),\u0627\u0644\u0633\u0646\u0629:r("year","ar"),\u0633\u0646\u0629:r("year","ar"),\u0627\u0644\u0639\u0627\u0645:r("year","ar"),\u0639\u0627\u0645:r("year","ar"),\u0627\u0644\u0631\u0628\u0639:r("quarter","ar"),\u0631\u0628\u0639:r("quarter","ar"),"\u0631\u0628\u0639 \u0627\u0644\u0633\u0646\u0629":r("quarter","ar"),\u0627\u0644\u0634\u0647\u0631:r("month","ar"),\u0634\u0647\u0631:r("month","ar"),\u0627\u0644\u064A\u0648\u0645:r("day","ar"),\u064A\u0648\u0645:r("day","ar"),\u05E9\u05E0\u05D4:r("year","he"),\u05E8\u05D1\u05E2\u05D5\u05DF:r("quarter","he"),\u05D7\u05D5\u05D3\u05E9:r("month","he"),\u05D9\u05D5\u05DD:r("day","he"),\u0935\u0930\u094D\u0937:r("year","hi"),\u0938\u093E\u0932:r("year","hi"),\u0924\u093F\u092E\u093E\u0939\u0940:r("quarter","hi"),\u092E\u0939\u0940\u0928\u093E:r("month","hi"),\u092E\u093E\u0939:r("month","hi"),\u0926\u093F\u0928:r("day","hi"),\u0633\u0627\u0644:r("year","fa"),\u0645\u0627\u0647:r("month","fa"),\u0631\u0648\u0632:r("day","fa")}),En=Object.freeze(Array.from(new Set(Object.values(re).flatMap(t=>t.langs)))),me=Object.freeze(["fa","ar","he","th"]),fe=1900,pe=2100;function Sn(t,e){let n=[],o=$(e);try{o&&n.push(t.toLocaleLowerCase(o.intl))}catch{}let u=t.toLowerCase();return n.includes(u)||n.push(u),n}function Rn(t,e){let n=String(t??"").trim().normalize("NFC");if(!n)return null;for(let o of Sn(n,e)){let u=re[o];if(u&&u.langs.includes(e))return u.part}return null}function xn(t,e){return me.includes(t)?typeof e=="number"&&Number.isFinite(e)&&e>=fe&&e<=pe:!0}function ye(t,e){let n=e?.freemiumMaxShapeColumns;return typeof n!="number"||!isFinite(n)||n<1?null:!isFinite(t)||t<=n?0:Math.round(t-n)}function wn(t,e,n){let o=ye(t,e);if(o===null||o<=0)return null;let u=typeof e?.freemiumColumnCapPivot=="number"?e.freemiumColumnCapPivot:4,l=o>u?e?.freemiumColumnCapMessageMany:e?.freemiumColumnCapMessageFew;if(typeof l!="string"||l.trim().length===0)return null;let a=l.split("{n}").join(String(o)).split("{fields}").join(o===1?"field":"fields"),i=ge(n);return i.length===0?a:a+" "+i.join(" ")}function ge(t){if(!t||t.length===0)return[];let e=[],n=new Map,o=new Map;for(let l of t){let a=typeof l?.dateGroupId=="string"?l.dateGroupId.trim():"";if(a!==""&&(n.has(a)||(e.push(a),n.set(a,0)),l.isDatePart===!0&&n.set(a,n.get(a)+1),l.isReassembledDate===!0&&!o.has(a))){let i=typeof l.sourceField=="string"?l.sourceField.trim():"",S=typeof l.name=="string"?l.name.trim():"",T=i!==""?i:S;T!==""&&o.set(a,T)}}let u=[];for(let l of e){let a=o.get(l),i=n.get(l)??0;!a||i===0||u.push(`'${a}' is a date hierarchy and counts as ${i+1} fields - bind the date itself instead of its hierarchy.`)}return u}var f=t=>t==null?"":String(t),N=t=>t===!0,he=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);return Number.isFinite(e)?e:null}return null},vn=[["city","CityColumn"],["state","StateColumn"],["zip","ZipColumn"],["lat","LatColumn"],["lon","LonColumn"],["country","CountryColumn"]];function Ce(t,e){let n={};for(let[o,u]of vn){let l=f(h(t,e+u));l&&(n[o]=l)}return n}function Pn(t){return Array.isArray(t)?t.map(e=>({code:f(h(e,"code")),severity:f(h(e,"severity")),text:f(h(e,"text"))})).filter(e=>e.text!==""):[]}function Ln(t){let e=S=>h(t,S),n=e("retryAfterSeconds"),o=e("overrideThumbnailUpload"),u=e("forceThumbnailUpload"),l=Ce(t,"point"),a=Ce(t,"destPoint");Object.keys(a).length&&(l.dest=a);let i=e("retryable");return{errorMessage:f(e("errorMessage")),errorCode:f(e("errorCode")),refusalCode:f(e("refusalCode")),retryable:typeof i=="boolean"?i:null,notices:Pn(e("notices")),freemiumStatusCode:f(e("freemiumStatusCode")),code:f(e("code")),language:f(e("language")),version:Number(e("version")??0),codeSummary:f(e("codeSummary")),chartName:f(e("chartName")??e("chartType")),finalChartName:f(e("finalChartName")),warningMessage:f(e("warningMessage")),outputHash:f(e("outputHash")),validatorToken:f(e("validatorToken")),editCodeKey:f(e("editCodeKey")),signedLLMRequestID:f(e("signedLLMRequestID")),userReply:f(e("userReply")),userReplyOutcome:f(e("userReplyOutcome")),improvementSuggestion:f(e("improvementSuggestion")),geoColumn:f(e("geoColumn")),geoKind:f(e("geoKind")),geoPointCols:Object.keys(l).length?l:null,creditBalanceBefore:he(e("creditBalanceBefore")),creditCost:he(e("creditCost")),isServiceError:N(e("isServiceError")),isRateLimited:N(e("isRateLimited")),isRefusal:N(e("isRefusal")),isVersionNotFound:N(e("isVersionNotFound")),isGenerationCancelled:N(e("isGenerationCancelled")),retryAfterSeconds:typeof n=="number"&&Number.isFinite(n)?n:null,servedCorrelationId:f(e("servedCorrelationId")),...typeof o=="boolean"?{overrideThumbnailUpload:o}:{},...typeof u=="boolean"?{forceThumbnailUpload:u}:{}}}var be=t=>t==null?void 0:Number(t),G=t=>f(t)||void 0;function Mn(t){let e=h(t,"charts"),n=h(t,"refused"),o=Array.isArray(e)?e.map(l=>{let a=S=>h(l,S),i=a("recommended");return{name:f(a("chartTypeName")??a("name")),description:f(a("description")??a("chartDesc")),rank:be(a("rank")),score:be(a("score")),renderer:G(a("renderer")),language:G(a("language")),isPreview:N(a("isPreview")),recommended:typeof i=="boolean"?i:void 0,viaProjection:G(a("viaProjection")),viaProjectionKey:G(a("viaProjectionKey")),detailNote:G(a("detailNote"))}}).filter(l=>l.name):null,u=Array.isArray(n)?n.map(l=>({name:f(h(l,"chartTypeName")??h(l,"name")),reason:f(h(l,"reason")),reasonCode:f(h(l,"reasonCode")),isVeto:N(h(l,"isVeto"))})).filter(l=>l.name):[];return{errorMessage:f(h(t,"errorMessage")),errorCode:f(h(t,"errorCode")),charts:o,refused:u,noFitSummary:f(h(t,"noFitSummary"))}}function _n(t){return!t||typeof t!="object"?null:{status:String(h(t,"status")??""),verdictReason:h(t,"verdictReason")??null,instruction:h(t,"instruction")??null,fix:h(t,"fix")??null,errorMessage:h(t,"errorMessage")??null,errorCode:h(t,"errorCode")??null}}var Te=["working","analyze","generate","refine","review"];function An(t,e){let n=String(t??"").trim().toLowerCase();if(Te.includes(n))return n;let o=String(e??"").toLowerCase();return o.includes("analyz")?"analyze":o.includes("generat")?"generate":o.includes("refin")?"refine":o.includes("review")?"review":null}var On="FREEMIUM_ATTEMPT_SPENT",Nn="CLIENT_SECRET_MISMATCH",In="FREEMIUM_COLUMN_CAP";function Fn(t){let e=t?.retryable;return typeof e=="boolean"?e:null}function kn(t){let e=t.linkNonce?(t.linkNonce()??"").trim():null,n=e?{licensee:"",licenseKey:"",secretKey:""}:t.triple();return{request:{licenseKey:n.licenseKey,licensee:n.licensee,secretKey:n.secretKey,freemiumKey:t.freemiumKey?.()??""},linkNonce:e}}function Gn(t){let{width:e,height:n}=t.measure();return{request:{height:n,width:e},hints:{viewportWidth:e,viewportHeight:n}}}function Vn(t){let e=0;for(let n of t){if(n.isMeasure)continue;let o=n.distinctCount;typeof o=="number"&&o>e&&(e=o)}return e}function Ee(t){if(t.recoveryFetchByCorrelation)return{version:null,fetchOnly:!0};if(t.recoveryFetchVersion!=null)return{version:t.recoveryFetchVersion,fetchOnly:!0};let e=t.settingVersion??null;if(t.genNew)return{version:e,fetchOnly:void 0};let n=(e??0)>0?e:null,o=(t.codeVersion??0)>0?t.codeVersion:null,u=n??o??e;return{version:u,fetchOnly:u!=null&&u>0?!0:void 0}}function Dn(t){let e=t.fetchCorrelationId!=null,o=e||t.recoveryFetchVersion!=null?!1:t.genNew,u=Ee({genNew:o,recoveryFetchVersion:t.recoveryFetchVersion,recoveryFetchByCorrelation:e,settingVersion:t.settingVersion,codeVersion:t.codeVersion});return{genNew:o,version:u.version,fetchOnly:u.fetchOnly,fetchCorrelationId:t.fetchCorrelationId??void 0}}function Un(t){let e=n=>t.renderers.has(n);return{supportsD3:e("D3"),supportsPlotly:e("PLOTLY"),supportsVega:e("VEGA")}}function Wn(t){let e=t.cap!=null&&t.budget>t.cap?t.cap:t.budget;return{triesLeft:t.triesLeft??e,maxTries:e}}function qn(t){return t&&t>0?{leafCardinality:Math.round(t)}:{}}function Se(t,e){return t!=null&&e!=null&&t!==e}function zn(t,e){return t?Se(e.capturedFor,e.now)?{shortlist:void 0,stale:!0}:{shortlist:{...t,ageMs:e.atMs>0?Math.max(0,Math.round(e.nowMs-e.atMs)):void 0},stale:!1}:{shortlist:void 0,stale:!1}}var Kn=Object.freeze({integer:"number",decimal:"number",double:"number",datetime:"date",date:"date",boolean:"boolean",string:"text"});function Re(t){let e=String(t??"").trim().toLowerCase();return Kn[e]??e}function xe(t){let e="";for(let n of t)e+=JSON.stringify([String(n.name??""),n.isMeasure?"M":"D",Re(n.dataType)]);return e}function $n(t){return B(xe(t))}var Bn=2,jn=3,Hn=4,Yn=64,Qn=8e3,Xn=6e4,Jn=Object.freeze({RENDER_START:"render-start",RENDER_OK:"render-ok",RENDER_ERROR:"render-error",VIEW:"view",VIEW_VERDICT:"view-verdict"});function Zn(t){return!!t&&!t.includes("|")&&!t.includes(",")}function oe(t,e,n,o){let u=`${t},${e}|${n}`;return o?`${u}|${Math.max(0,Math.round(o.count))}|${o.nonce}`:u}function er(t,e){let n=t;if(!n||!n.signer||typeof n.signer.sign!="function")throw new TypeError("createTelemetryClient needs the host's signer");if(!n.transport||typeof n.transport.post!="function")throw new TypeError("createTelemetryClient needs the host's transport");if(!n.clock||typeof n.clock.now!="function")throw new TypeError("createTelemetryClient needs the host's clock");if(!e||typeof e.baseUrl!="string"&&typeof e.baseUrl!="function")throw new TypeError("createTelemetryClient needs the service's base URL");if(typeof e.baseUrl=="string"&&e.baseUrl==="")throw new TypeError("createTelemetryClient needs the service's base URL");if(typeof e.clientVersion!="string"||e.clientVersion==="")throw new TypeError("createTelemetryClient needs the client version");if(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new TypeError("createTelemetryClient needs a positive deadline in milliseconds");let{signer:o,transport:u,clock:l}=n,a=e.apiPath??"/api",i=e.timeoutMs,S=()=>typeof e.baseUrl=="function"?e.baseUrl():e.baseUrl,T=y=>{try{e.onFailure?.(y)}catch{}},b=async(y,m,p,c)=>{let C;try{let R=await u.post(m,p,c,{timeoutMs:i});C=R.status;try{R.body?.cancel().catch(()=>{})}catch{}}catch(R){T({channel:y,stage:"post",status:null,error:R});return}(C<200||C>299)&&T({channel:y,stage:"status",status:C,error:null})};return{async sendClientMessage(y){let m,p,c;try{m=`${S()}${a}/LogClientMsg/?nocache=${l.now()}`,p=O(y),c=k(p,o)}catch(C){T({channel:"client-message",stage:"build",status:null,error:C});return}await b("client-message",m,p,{"Content-Type":"text/plain","X-Signature":c})},async countEvent(y,m,p){let c,C;try{c=`${S()}${a}/eventlog`,C=oe(y,e.clientVersion,m,p)}catch(R){T({channel:"event-count",stage:"build",status:null,error:R});return}await b("event-count",c,C,{"Content-Type":"text/plain"})}}}function we(t){return Object.assign(new Error(`The request did not finish within ${t} ms.`),{name:"TimeoutError"})}function tr(t,e={}){if(typeof t!="function")throw new TypeError("fetchTransport needs the host's fetch");let n=t,o=e.credentials??"omit";return{async post(u,l,a,i){let S=i.timeoutMs,T=new AbortController,b=!1,y=setTimeout(()=>{b=!0,T.abort(we(S))},S),m=()=>T.abort(i.signal?.reason);i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m,{once:!0}));let p=!1,c=()=>{p||(p=!0,clearTimeout(y),i.signal?.removeEventListener("abort",m))},C=g=>b?we(S):g,R;try{R=await n(u,{method:"POST",body:l,headers:a,credentials:o,signal:T.signal})}catch(g){throw c(),C(g)}let w=Y(R),v=w.statusText!==void 0?{statusText:w.statusText}:{};if(!w.body)return{status:w.status,...v,contentType:w.contentType,body:null,text:async()=>{try{return await w.text()}catch(g){throw C(g)}finally{c()}}};let _=w.body.getReader(),x=new ReadableStream({async pull(g){try{let L=await _.read();if(L.done){c(),g.close();return}g.enqueue(L.value)}catch(L){c(),g.error(C(L))}},cancel(g){return c(),_.cancel(g)}});return{status:w.status,...v,contentType:w.contentType,body:x,text:()=>new Response(x).text()}}}}var ve=300,nr="/LLMChart/",rr="/LLMChart/qualify",or="/VisionReview/",ir="/LLMChart/sample",sr=t=>!!t&&typeof t=="object"&&t.name==="TimeoutError",ie=async t=>JSON.parse(await t.text());function ar(t){try{t.body?t.body.cancel().catch(()=>{}):t.text().catch(()=>{})}catch{}}function lr(t,e){let n=t;if(!n||!n.signer||typeof n.signer.sign!="function")throw new TypeError("createGenerateClient needs the host's signer");if(!n.transport||typeof n.transport.post!="function")throw new TypeError("createGenerateClient needs the host's transport");if(!n.clock||typeof n.clock.now!="function")throw new TypeError("createGenerateClient needs the host's clock");if(!e||typeof e.baseUrl!="string"&&typeof e.baseUrl!="function")throw new TypeError("createGenerateClient needs the service's base URL");if(typeof e.baseUrl=="string"&&e.baseUrl==="")throw new TypeError("createGenerateClient needs the service's base URL");if(e.apiPath!==void 0&&typeof e.apiPath!="string")throw new TypeError("createGenerateClient's apiPath must be a string");if(e.nocache!==void 0&&e.nocache!==null&&typeof e.nocache!="function")throw new TypeError("createGenerateClient's nocache must be a function");let{signer:o,transport:u,clock:l}=n,a=e.apiPath??"/api",i=()=>typeof e.baseUrl=="function"?e.baseUrl():e.baseUrl,S=y=>e.nocache?e.nocache(y):String(l.now());async function T(y,m,p,c,C){let R=`${i()}${a}${m}?nocache=${S(y)}`,w={"Content-Type":"text/plain","X-Signature":k(p,o)},v=c.signal??void 0,_=(g,L)=>{let s=!!v?.aborted;return{kind:"transport",headersReceived:g,timedOut:!s&&sr(L),cancelled:s,error:L}},x;try{x=await u.post(R,p,w,v?{timeoutMs:c.timeoutMs,signal:v}:{timeoutMs:c.timeoutMs})}catch(g){return _(!1,g)}if(x.status<200||x.status>299){let g="";if(c.readErrorBody===!1)ar(x);else try{g=(await x.text()).slice(0,ve)}catch{}return{kind:"http",status:x.status,statusText:x.statusText??"",bodyStart:g}}try{return{kind:"answer",status:x.status,value:await C(x)}}catch(g){return _(!0,g)}}function b(y,m){if(!m||typeof m.timeoutMs!="number"||!Number.isFinite(m.timeoutMs)||m.timeoutMs<=0)throw new TypeError(`The ${y} call needs a positive deadline in milliseconds`);return m}return{async generate(y,m){let p=b("generate",m),c=p.onStage??void 0;return T("generate",nr,O(y),p,C=>Q(C,c))},async qualify(y,m){let p=b("qualify",m),c=p.route??rr;if(typeof c!="string"||!c.startsWith("/"))throw new TypeError("The qualify route must start with '/'");return T("qualify",c,O(y),p,ie)},async review(y,m){let p=b("review",m),c=JSON.stringify(y);if(typeof c!="string")throw new TypeError("The review wire did not serialize to JSON");return T("review",or,c,p,ie)},async sample(y,m){let p=b("sample",m);return T("sample",ir,O(y),p,ie)}}}export{j as CITY_ROLE_MATCH_PCT,Jn as CLIENT_EVENT_KINDS,Nn as CLIENT_SECRET_MISMATCH,De as COMPOUND_MIN_STEM,pe as DATE_LEVEL_GREGORIAN_YEAR_MAX,fe as DATE_LEVEL_GREGORIAN_YEAR_MIN,En as DATE_LEVEL_LANGUAGES,re as DATE_LEVEL_NAMES,me as DATE_LEVEL_NON_GREGORIAN_LANGUAGES,Kt as DEFAULT_GAP_FACTOR,He as DEFAULT_TEMPERATURE,On as FREEMIUM_ATTEMPT_SPENT,In as FREEMIUM_COLUMN_CAP,Be as GET_RANDOM,We as GLUED_STEM_MIN,ve as HTTP_BODY_START_CHARS,vt as INTENSIVE_SUFFIX_TOKENS,wt as INTENSIVE_WORD_TOKENS,an as IndexedText,$t as MAX_RUN_BOUNDS,Lt as POSITIONAL_SUFFIX_TOKENS,Pt as POSITIONAL_WORD_TOKENS,fn as PREVIEW_OMITTED_FIELDS,Te as PROGRESS_STAGE_IDS,A as ROLE_MATCH_PCT,Ht as SERIES_COMPLETENESS_MAX_LISTED,Yt as SERIES_COMPLETENESS_MIN_FILL,Qt as SERIES_KEY_MAX_DISTINCT,Hn as SEV_ERROR,Bn as SEV_INFO,Yn as SEV_USER_PRESENTED,jn as SEV_WARNING,B as SIMPLE_STRING_HASH,$e as STR,ze as SUBSTRING_MIN,Le as SUPPORTED_LANGUAGES,Me as SUPPORTED_LANGUAGE_CODES,Xn as TELEMETRY_TIMEOUT_DEV_MS,Qn as TELEMETRY_TIMEOUT_MS,Oe as VOCABULARY_LANGUAGE_CODES,Ae as VOCABULARY_ONLY_LANGUAGES,z as admin1MatchPct,Gt as allowedAggregations,Fn as answerIsRetryable,ht as buildGeoIsoColumn,dt as buildGeoPointColumns,Un as capabilityFields,ft as cityMatchPct,mt as cityTagsFor,on as classifyAdditivity,kt as classifyForAggregation,sn as classifyNumericValueNature,nn as classifyTemporal,Ot as codeNeedsLegacyAggNames,Wt as codeReadsColumn,qt as codeReadsColumnsByRoleOrPosition,At as collapseRepeatedAggPrefix,zt as columnsTheCodeReads,Tt as countryRegion,lr as createGenerateClient,er as createTelemetryClient,kn as credentialFields,Rn as dateLevelPart,xn as dateLevelYearAdmits,ln as decimalSeparatorOf,Vt as defaultAggregation,un as detectDecimalSeparator,St as detectFormatSignature,pt as detectGeo,rt as detectOrdinalDomain,tn as detectTextDatePattern,O as encodePayload,dn as engineTypeForSqlType,Nt as englishImplicitAggNames,oe as eventLogLine,Dn as fetchFields,tr as fetchTransport,Ie as foldName,wn as freemiumColumnCapRefusal,ye as freemiumColumnsOverCap,ge as freemiumDateHierarchyClauses,qe as gluedPrefixStems,yn as gzipWireText,_t as hasDefaultAggPrefix,Ge as hasUnsegmentedScript,rn as hostAggHint,mn as ingest,Dt as isAggregationAllowed,W as isBlankLike,it as isCityTableLoaded,je as isDeterministicRefusal,Zn as isEventLogCode,ut as isGeoPointAmbiguity,en as isIdentifierName,gt as isJoinGeoKind,hn as isNdjsonContentType,tt as isOrdinalFriendlyName,gn as keyedSigner,qn as leafCardinalityField,Ze as localMidnightDateColumns,Je as localMidnightToUtcDay,I as looksLikeCountryColumn,Ke as matchNameToken,Vn as maxNonMeasureCardinality,jt as measureCadence,Zt as measureSeriesCompleteness,k as messageSignature,xt as monthLookupFor,Ft as nameLooksIntensiveRate,It as nameLooksPositional,Fe as nameWords,st as normalizeCountry,et as normalizeLocalMidnightDates,Rt as normalizeMonthKey,D as normalizePlaceName,lt as normalizeZip5,zn as offeredShortlistFor,Ye as parseDateStable,Ln as parseGenerateResponse,cn as parseNumberText,Mn as parseQualifyResponse,_n as parseReviewVerdict,Bt as parseTemporalPoint,pn as payloadPreview,Jt as pickSeriesColumn,An as progressStageOf,Q as readGenerateStream,ke as readName,h as readWireField,ot as registerCityTable,bt as registerIso3Regions,M as resolveAdmin1,Ee as resolveFetchVersion,ct as resolveGeoPoint,Ne as resolveLanguage,Tn as resolvePointRoles,Wn as retryFields,nt as safeDistinctValuesToShip,xe as schemaIdentity,$n as schemaIdentityKey,Re as schemaTypeFamily,Xt as seriesKeyVerdict,Ut as shareOfTotalIsHonest,Se as shortlistIsStale,Mt as stripHostAggPrefix,Et as summarizeCountryRegions,Ct as summarizeGeoExtent,_e as supportedLanguage,yt as toGeoIso,Ve as unsegmentedRuns,Gn as viewportFields,$ as vocabularyLanguage,Qe as wholeDayFrame,Xe as wholeDayIso,Y as wireResponseFromFetch,Ue as wordEndsWith,te as zipMatchPct,q as zipPrefixCandidates,at as zipToPrefix3};
package/dist/testing.mjs CHANGED
@@ -1,7 +1,7 @@
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{f as A,h as g}from"./chunk-JF3BJI7F.mjs";import"./chunk-NFSQ4O5R.mjs";var S=class extends Error{contract;failures;constructor(e,s){super(`${e} conformance failed:
2
+ import{f as A,h as g}from"./chunk-ARZ2GRKS.mjs";import"./chunk-NFSQ4O5R.mjs";var $=class extends Error{contract;failures;constructor(e,s){super(`${e} conformance failed:
3
3
  - ${s.join(`
4
- - `)}`),this.name="ConformanceError",this.contract=e,this.failures=s}},m=class{constructor(e){this.contract=e}contract;failures=[];check(e,s){e||this.failures.push(s)}fail(e){this.failures.push(e)}throwIfFailed(){if(this.failures.length)throw new S(this.contract,this.failures.slice())}},$="H4sIAAAAAAAAA6tWyk0tSs5ITUxRslIqS8wpTVWqBQBL0RbkEwAAAA==",R="H4sIAAAAAAAAA6tWSkksSVSyUsrMyyrKz1OqBQBVrD9YEAAAAA==";function u(n){return n instanceof Error?`${n.name}: ${n.message}`:String(n)}function x(n){let e=new m("WireSigner");(!n||typeof n.sign!="function")&&(e.fail("the signer has no sign() method"),e.throwIfFailed());let s,d,l;try{s=n.sign($),d=n.sign($),l=n.sign(R)}catch(a){e.fail(`sign() threw on an ordinary encoded body: ${u(a)}`),e.throwIfFailed()}e.check(typeof s=="string",`sign() returned ${typeof s}, not a string`),e.check(typeof s!="string"||s.trim()!=="","sign() returned a blank signature"),e.check(s===d,"sign() is not deterministic: the same body signed twice gave two signatures"),e.check(s!==l,"sign() gave two different bodies the same signature"),e.throwIfFailed()}async function q(n){let e=new m("WireResponse"),s=new TextEncoder,d=[`{"type":"progress","stage":"Reading your data"}
4
+ - `)}`),this.name="ConformanceError",this.contract=e,this.failures=s}},k=class{constructor(e){this.contract=e}contract;failures=[];check(e,s){e||this.failures.push(s)}fail(e){this.failures.push(e)}throwIfFailed(){if(this.failures.length)throw new $(this.contract,this.failures.slice())}},v="H4sIAAAAAAAAA6tWyk0tSs5ITUxRslIqS8wpTVWqBQBL0RbkEwAAAA==",E="H4sIAAAAAAAAA6tWSkksSVSyUsrMyyrKz1OqBQBVrD9YEAAAAA==";function h(n){return n instanceof Error?`${n.name}: ${n.message}`:String(n)}function T(n){return n&&typeof n=="object"&&typeof n.name=="string"?n.name:""}function j(n){let e=new k("WireSigner");(!n||typeof n.sign!="function")&&(e.fail("the signer has no sign() method"),e.throwIfFailed());let s,d,l;try{s=n.sign(v),d=n.sign(v),l=n.sign(E)}catch(r){e.fail(`sign() threw on an ordinary encoded body: ${h(r)}`),e.throwIfFailed()}e.check(typeof s=="string",`sign() returned ${typeof s}, not a string`),e.check(typeof s!="string"||s.trim()!=="","sign() returned a blank signature"),e.check(s===d,"sign() is not deterministic: the same body signed twice gave two signatures"),e.check(s!==l,"sign() gave two different bodies the same signature"),e.throwIfFailed()}async function q(n){let e=new k("WireResponse"),s=new TextEncoder,d=[`{"type":"progress","stage":"Reading your data"}
5
5
  `,`{"type":"result","result":{"code":"x","version":2}}
6
- `],l=(a,r=!1)=>new ReadableStream({start(t){for(let o of a)t.enqueue(o);r?t.error(Object.assign(new Error("the connection dropped"),{name:"AbortError"})):t.close()}});try{let a=n(new Response(l(d.map(o=>s.encode(o))),{status:200,headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}}));e.check(a.status===200,`a streamed 200 reported status ${a.status}`),e.check(A(a.contentType),`a streamed response reported content type ${JSON.stringify(a.contentType)}`);let r=[],t=await g(a,o=>r.push(o));e.check(t?.code==="x"&&t?.version===2,"the stream's result line did not come back as the result"),e.check(r.join("|")==="Reading your data",`progress stages read as ${JSON.stringify(r)}`)}catch(a){e.fail(`reading an NDJSON stream threw: ${u(a)}`)}try{let a=n(new Response('{"code":"y","errorMessage":""}',{status:200,headers:{"Content-Type":"application/json"}}));e.check(!A(a.contentType),"a JSON response reported an NDJSON content type");let r=await g(a);e.check(r?.code==="y","a buffered JSON body did not come back as the result")}catch(a){e.fail(`reading a buffered JSON body threw: ${u(a)}`)}try{let a=n(new Response(l([s.encode(d[0])],!0),{status:200,headers:{"Content-Type":"application/x-ndjson"}})),r=null;try{await g(a)}catch(t){r=t}e.check(!!r,"a body that errored part-way was read as a success"),e.check(!r||r.name==="AbortError",`a body that errored part-way surfaced as ${r?.name}: ${r?.message}, not the body's own error`)}catch(a){e.fail(`adapting a response whose body errors threw before it was read: ${u(a)}`)}try{let a=n(new Response(null,{status:204}));e.check(a.status===204,`a 204 reported status ${a.status}`);let r=await a.text();e.check(r==="",`a 204's text() returned ${JSON.stringify(r)}`)}catch(a){e.fail(`a 204 with no body threw: ${u(a)}`)}e.throwIfFailed()}async function T(n,e){let s=n instanceof Request?n:new Request(String(n),e),d=e?.signal??s.signal??null;return{url:s.url,method:s.method,headers:s.headers,body:await s.text(),signal:d}}var k=()=>Object.assign(new Error("The operation was aborted."),{name:"AbortError"});async function w(n,e){let s,d=new Promise(l=>{s=setTimeout(()=>l({settled:!1}),e)});try{return await Promise.race([n.then(l=>({settled:!0,ok:!0,value:l}),l=>({settled:!0,ok:!1,error:l})),d])}finally{s&&clearTimeout(s)}}async function I(n){let e=new m("WireTransport"),s="https://service.example/api/route/?nocache=1",d="H4sIAAAAAAAAA6tWyk0tSs5ITUxRslIqS8wpTVWqBQBL0RbkEwAAAA==",l={"Content-Type":"text/plain","X-Signature":"12345"},a=40,r=1e3;try{let t=null,o=n(async(c,h)=>(t=await T(c,h),new Response('{"ok":true}',{status:200,headers:{"Content-Type":"application/json"}}))),i=await w(o.post(s,d,l,{timeoutMs:5e3}),r);if(!i.settled)e.fail("an ordinary post never settled");else if(i.ok===!1)e.fail(`an ordinary post rejected: ${u(i.error)}`);else{let c=t;e.check(!!c,"the adapter never called the fetch it was given"),c&&(e.check(c.url===s,`the request went to ${c.url}, not the URL it was given`),e.check(c.method==="POST",`the request was a ${c.method}, not a POST`),e.check(c.body===d,"the body did not reach the network as given"),e.check(c.headers.get("content-type")==="text/plain",`Content-Type reached the network as ${c.headers.get("content-type")}`),e.check(c.headers.get("x-signature")==="12345","a header the caller set did not reach the network")),e.check(i.value.status===200,`a 200 reported status ${i.value.status}`),e.check(A(i.value.contentType)===!1&&/json/.test(String(i.value.contentType)),`the response's content type read as ${JSON.stringify(i.value.contentType)}`),e.check(await i.value.text()==='{"ok":true}',"text() did not return the body")}}catch(t){e.fail(`an ordinary post threw: ${u(t)}`)}for(let t of[400,500,503])try{let o=n(async()=>new Response('{"message":"why"}',{status:t,headers:{"Content-Type":"application/json"}})),i=await w(o.post(s,d,l,{timeoutMs:5e3}),r);i.settled?i.ok===!1?e.fail(`an HTTP ${t} rejected (${u(i.error)}) - a status is an answer, not a transport failure`):(e.check(i.value.status===t,`an HTTP ${t} reported status ${i.value.status}`),e.check(await i.value.text()==='{"message":"why"}',`an HTTP ${t}'s body could not be read`)):e.fail(`an HTTP ${t} never settled`)}catch(o){e.fail(`an HTTP ${t} threw: ${u(o)}`)}try{let t=n(async()=>new Response(null,{status:204})),o=await w(t.post(s,d,l,{timeoutMs:5e3}),r);!o.settled||!o.ok?e.fail("a 204 did not resolve"):e.check(o.value.status===204,`a 204 reported status ${o.value.status}`)}catch(t){e.fail(`a 204 threw: ${u(t)}`)}try{let t=n(async()=>{throw new TypeError("Failed to fetch")}),o=await w(t.post(s,d,l,{timeoutMs:5e3}),r);e.check(o.settled&&!o.ok,"a failed connection did not reject")}catch(t){e.fail(`a failed connection threw synchronously: ${u(t)}`)}try{let t=null,o=n((h,f)=>new Promise((b,p)=>{T(h,f).then(y=>{t=y.signal,y.signal&&(y.signal.aborted?p(k()):y.signal.addEventListener("abort",()=>p(k()),{once:!0}))})})),i=await w(o.post(s,d,l,{timeoutMs:a}),r);e.check(i.settled&&!i.ok,`no answer inside a ${a} ms deadline did not reject within ${r} ms`);let c=t;e.check(!!c&&c.aborted,"the deadline passed but the request was not aborted - the socket would stay open")}catch(t){e.fail(`the deadline check threw synchronously: ${u(t)}`)}try{let t=null,o=new TextEncoder,i=n(async(h,f)=>{let b=await T(h,f);t=b.signal;let p,y=new ReadableStream({start(v){p=v}});return p.enqueue(o.encode(`{"type":"progress","stage":"Reading your data"}
7
- `)),b.signal?.addEventListener("abort",()=>{try{p.error(k())}catch{}},{once:!0}),new Response(y,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}),c=await w(i.post(s,d,l,{timeoutMs:a}),r);if(!c.settled||c.ok===!1)e.fail("headers that arrived in time did not resolve the post");else{let h=await w(g(c.value),r);e.check(h.settled&&h.ok===!1,`a body that stalled after its headers was still being read ${r} ms after a ${a} ms deadline`);let f=t;e.check(!!f&&f.aborted,"the deadline passed mid-body but the request was not aborted - the socket would stay open")}}catch(t){e.fail(`the body-deadline check threw synchronously: ${u(t)}`)}try{let t=new AbortController,i=n((h,f)=>new Promise((b,p)=>{T(h,f).then(y=>{y.signal&&(y.signal.aborted?p(k()):y.signal.addEventListener("abort",()=>p(k()),{once:!0}))})})).post(s,d,l,{timeoutMs:5e3,signal:t.signal});setTimeout(()=>t.abort(),10);let c=await w(i,r);e.check(c.settled&&!c.ok,"aborting the caller's signal did not reject the post")}catch(t){e.fail(`the caller-signal check threw synchronously: ${u(t)}`)}e.throwIfFailed()}export{S as ConformanceError,q as assertWireResponseConformance,x as assertWireSignerConformance,I as assertWireTransportConformance};
6
+ `],l=(r,a=!1)=>new ReadableStream({start(t){for(let i of r)t.enqueue(i);a?t.error(Object.assign(new Error("the connection dropped"),{name:"AbortError"})):t.close()}});try{let r=n(new Response(l(d.map(i=>s.encode(i))),{status:200,headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}}));e.check(r.status===200,`a streamed 200 reported status ${r.status}`),e.check(A(r.contentType),`a streamed response reported content type ${JSON.stringify(r.contentType)}`);let a=[],t=await g(r,i=>a.push(i));e.check(t?.code==="x"&&t?.version===2,"the stream's result line did not come back as the result"),e.check(a.join("|")==="Reading your data",`progress stages read as ${JSON.stringify(a)}`)}catch(r){e.fail(`reading an NDJSON stream threw: ${h(r)}`)}try{let r=n(new Response('{"code":"y","errorMessage":""}',{status:200,headers:{"Content-Type":"application/json"}}));e.check(!A(r.contentType),"a JSON response reported an NDJSON content type");let a=await g(r);e.check(a?.code==="y","a buffered JSON body did not come back as the result")}catch(r){e.fail(`reading a buffered JSON body threw: ${h(r)}`)}try{let r=n(new Response(l([s.encode(d[0])],!0),{status:200,headers:{"Content-Type":"application/x-ndjson"}})),a=null;try{await g(r)}catch(t){a=t}e.check(!!a,"a body that errored part-way was read as a success"),e.check(!a||a.name==="AbortError",`a body that errored part-way surfaced as ${a?.name}: ${a?.message}, not the body's own error`)}catch(r){e.fail(`adapting a response whose body errors threw before it was read: ${h(r)}`)}try{let r=n(new Response(null,{status:204}));e.check(r.status===204,`a 204 reported status ${r.status}`);let a=await r.text();e.check(a==="",`a 204's text() returned ${JSON.stringify(a)}`)}catch(r){e.fail(`a 204 with no body threw: ${h(r)}`)}e.throwIfFailed()}async function S(n,e){let s=n instanceof Request?n:new Request(String(n),e),d=e?.signal??s.signal??null;return{url:s.url,method:s.method,headers:s.headers,body:await s.text(),signal:d}}var m=()=>Object.assign(new Error("The operation was aborted."),{name:"AbortError"});async function w(n,e){let s,d=new Promise(l=>{s=setTimeout(()=>l({settled:!1}),e)});try{return await Promise.race([n.then(l=>({settled:!0,ok:!0,value:l}),l=>({settled:!0,ok:!1,error:l})),d])}finally{s&&clearTimeout(s)}}async function I(n){let e=new k("WireTransport"),s="https://service.example/api/route/?nocache=1",d="H4sIAAAAAAAAA6tWyk0tSs5ITUxRslIqS8wpTVWqBQBL0RbkEwAAAA==",l={"Content-Type":"text/plain","X-Signature":"12345"},r=40,a=1e3;try{let t=null,i=n(async(c,u)=>(t=await S(c,u),new Response('{"ok":true}',{status:200,headers:{"Content-Type":"application/json"}}))),o=await w(i.post(s,d,l,{timeoutMs:5e3}),a);if(!o.settled)e.fail("an ordinary post never settled");else if(o.ok===!1)e.fail(`an ordinary post rejected: ${h(o.error)}`);else{let c=t;e.check(!!c,"the adapter never called the fetch it was given"),c&&(e.check(c.url===s,`the request went to ${c.url}, not the URL it was given`),e.check(c.method==="POST",`the request was a ${c.method}, not a POST`),e.check(c.body===d,"the body did not reach the network as given"),e.check(c.headers.get("content-type")==="text/plain",`Content-Type reached the network as ${c.headers.get("content-type")}`),e.check(c.headers.get("x-signature")==="12345","a header the caller set did not reach the network")),e.check(o.value.status===200,`a 200 reported status ${o.value.status}`),e.check(A(o.value.contentType)===!1&&/json/.test(String(o.value.contentType)),`the response's content type read as ${JSON.stringify(o.value.contentType)}`),e.check(await o.value.text()==='{"ok":true}',"text() did not return the body")}}catch(t){e.fail(`an ordinary post threw: ${h(t)}`)}for(let t of[400,500,503])try{let i=n(async()=>new Response('{"message":"why"}',{status:t,headers:{"Content-Type":"application/json"}})),o=await w(i.post(s,d,l,{timeoutMs:5e3}),a);o.settled?o.ok===!1?e.fail(`an HTTP ${t} rejected (${h(o.error)}) - a status is an answer, not a transport failure`):(e.check(o.value.status===t,`an HTTP ${t} reported status ${o.value.status}`),e.check(await o.value.text()==='{"message":"why"}',`an HTTP ${t}'s body could not be read`)):e.fail(`an HTTP ${t} never settled`)}catch(i){e.fail(`an HTTP ${t} threw: ${h(i)}`)}try{let t=n(async()=>new Response(null,{status:204})),i=await w(t.post(s,d,l,{timeoutMs:5e3}),a);!i.settled||!i.ok?e.fail("a 204 did not resolve"):e.check(i.value.status===204,`a 204 reported status ${i.value.status}`)}catch(t){e.fail(`a 204 threw: ${h(t)}`)}try{let t=n(async()=>{throw new TypeError("Failed to fetch")}),i=await w(t.post(s,d,l,{timeoutMs:5e3}),a);e.check(i.settled&&!i.ok,"a failed connection did not reject")}catch(t){e.fail(`a failed connection threw synchronously: ${h(t)}`)}try{let t=null,i=n((u,f)=>new Promise((b,p)=>{S(u,f).then(y=>{t=y.signal,y.signal&&(y.signal.aborted?p(m()):y.signal.addEventListener("abort",()=>p(m()),{once:!0}))})})),o=await w(i.post(s,d,l,{timeoutMs:r}),a);e.check(o.settled&&!o.ok,`no answer inside a ${r} ms deadline did not reject within ${a} ms`),o.settled&&o.ok===!1&&e.check(T(o.error)==="TimeoutError",`the deadline's rejection was named ${JSON.stringify(T(o.error))}, not "TimeoutError" - a caller would read it as a dropped connection`);let c=t;e.check(!!c&&c.aborted,"the deadline passed but the request was not aborted - the socket would stay open")}catch(t){e.fail(`the deadline check threw synchronously: ${h(t)}`)}try{let t=null,i=new TextEncoder,o=n(async(u,f)=>{let b=await S(u,f);t=b.signal;let p,y=new ReadableStream({start(R){p=R}});return p.enqueue(i.encode(`{"type":"progress","stage":"Reading your data"}
7
+ `)),b.signal?.addEventListener("abort",()=>{try{p.error(m())}catch{}},{once:!0}),new Response(y,{status:200,headers:{"Content-Type":"application/x-ndjson"}})}),c=await w(o.post(s,d,l,{timeoutMs:r}),a);if(!c.settled||c.ok===!1)e.fail("headers that arrived in time did not resolve the post");else{let u=await w(g(c.value),a);e.check(u.settled&&u.ok===!1,`a body that stalled after its headers was still being read ${a} ms after a ${r} ms deadline`),u.settled&&u.ok===!1&&e.check(T(u.error)==="TimeoutError",`the deadline's body error was named ${JSON.stringify(T(u.error))}, not "TimeoutError" - a caller would read it as a dropped connection`);let f=t;e.check(!!f&&f.aborted,"the deadline passed mid-body but the request was not aborted - the socket would stay open")}}catch(t){e.fail(`the body-deadline check threw synchronously: ${h(t)}`)}try{let t=new AbortController,o=n((u,f)=>new Promise((b,p)=>{S(u,f).then(y=>{y.signal&&(y.signal.aborted?p(m()):y.signal.addEventListener("abort",()=>p(m()),{once:!0}))})})).post(s,d,l,{timeoutMs:5e3,signal:t.signal});setTimeout(()=>t.abort(),10);let c=await w(o,a);e.check(c.settled&&!c.ok,"aborting the caller's signal did not reject the post")}catch(t){e.fail(`the caller-signal check threw synchronously: ${h(t)}`)}e.throwIfFailed()}export{$ as ConformanceError,q as assertWireResponseConformance,j as assertWireSignerConformance,I as assertWireTransportConformance};
@@ -2,6 +2,7 @@ import type { WireTransport } from "./host/services";
2
2
  /** A platform fetch, or anything shaped like one. Called as a plain function. */
3
3
  export type FetchFunction = (input: string, init?: any) => Promise<{
4
4
  status?: number;
5
+ statusText?: string;
5
6
  headers?: {
6
7
  get(name: string): string | null;
7
8
  } | null;
@@ -0,0 +1,94 @@
1
+ import type { Clock, WireSigner, WireTransport } from "./host/services";
2
+ import { type OnStage } from "./wireStream";
3
+ /** The services a generate client needs - the wire-level subset every host that sends requests has. */
4
+ export interface GenerateClientServices {
5
+ signer: WireSigner;
6
+ transport: WireTransport;
7
+ clock: Clock;
8
+ }
9
+ /** Which call a request is. */
10
+ export type GenerateCall = "generate" | "qualify" | "review" | "sample";
11
+ export interface GenerateClientEnv {
12
+ /**
13
+ * The service's origin, with no trailing slash: "https://example.com". A function is read at every
14
+ * call, for a host whose target can change after the client is built.
15
+ */
16
+ baseUrl: string | (() => string);
17
+ /** The API prefix between the origin and the route. Default "/api". */
18
+ apiPath?: string;
19
+ /**
20
+ * The cache-busting value each URL carries as `nocache`, per call. Default: the clock's now(), in
21
+ * decimal. A host that stamps its URLs another way passes its own.
22
+ */
23
+ nocache?: ((call: GenerateCall) => string) | null;
24
+ }
25
+ /** How many characters of a non-2xx body an `http` outcome keeps. */
26
+ export declare const HTTP_BODY_START_CHARS = 300;
27
+ /** A 2xx whose body was read. */
28
+ export interface AnswerOutcome<T> {
29
+ kind: "answer";
30
+ status: number;
31
+ value: T;
32
+ }
33
+ /** A status outside 2xx. `statusText` is "" when the platform had no reason phrase (HTTP/2). */
34
+ export interface HttpOutcome {
35
+ kind: "http";
36
+ status: number;
37
+ statusText: string;
38
+ /** The first HTTP_BODY_START_CHARS characters of the body; "" when it was empty, unreadable or not read. */
39
+ bodyStart: string;
40
+ }
41
+ /**
42
+ * Nothing to read. `headersReceived` is true when a 2xx arrived and its body then broke off, timed out
43
+ * or did not parse. `cancelled` is true when the caller's signal was aborted; `timedOut` when the
44
+ * transport's deadline passed (an error named "TimeoutError") and the caller had not cancelled.
45
+ */
46
+ export interface TransportOutcome {
47
+ kind: "transport";
48
+ headersReceived: boolean;
49
+ timedOut: boolean;
50
+ cancelled: boolean;
51
+ error: unknown;
52
+ }
53
+ export type WireOutcome<T> = AnswerOutcome<T> | HttpOutcome | TransportOutcome;
54
+ export interface WireCallOptions {
55
+ /** The deadline for the whole exchange, in milliseconds - the headers and the body. */
56
+ timeoutMs: number;
57
+ /** Cancels the call at any point. */
58
+ signal?: AbortSignal | null;
59
+ /**
60
+ * Whether a non-2xx body is read for `bodyStart`. Default true. False leaves it unread (released,
61
+ * never awaited), for a host that never shows it and must not wait on it.
62
+ */
63
+ readErrorBody?: boolean;
64
+ }
65
+ export interface GenerateCallOptions extends WireCallOptions {
66
+ /** Each progress line of a streamed generate: its label and, from a newer server, its code. */
67
+ onStage?: OnStage | null;
68
+ }
69
+ export interface QualifyCallOptions extends WireCallOptions {
70
+ /** The route under the API prefix. Default "/LLMChart/qualify". */
71
+ route?: string;
72
+ }
73
+ export interface GenerateClient {
74
+ /**
75
+ * POST a generate request - or a fetch by version or by correlation, which ride the same route and
76
+ * differ only in the payload's fetch fields - as the signed envelope. The answer is the result the
77
+ * response carries, read by readGenerateStream.
78
+ */
79
+ generate(payload: unknown, opts: GenerateCallOptions): Promise<WireOutcome<Record<string, any>>>;
80
+ /** POST a what-fits request as the signed envelope. The answer is the parsed JSON body. */
81
+ qualify(payload: unknown, opts: QualifyCallOptions): Promise<WireOutcome<unknown>>;
82
+ /**
83
+ * POST one image-review call as PLAIN JSON, signed over that text - never the envelope: the review
84
+ * route reads and signs the raw body. The answer is the parsed JSON body.
85
+ */
86
+ review(wire: unknown, opts: WireCallOptions): Promise<WireOutcome<unknown>>;
87
+ /** POST an example-chart request as the signed envelope. The answer is the parsed JSON body. */
88
+ sample(payload: unknown, opts: WireCallOptions): Promise<WireOutcome<unknown>>;
89
+ }
90
+ /**
91
+ * Build a generate client over the host's services. A missing service or an unusable setting is a
92
+ * TypeError here, at construction, never a fallback at the first call.
93
+ */
94
+ export declare function createGenerateClient(services: GenerateClientServices, env: GenerateClientEnv): GenerateClient;
@@ -17,6 +17,12 @@ export interface WireSigner {
17
17
  */
18
18
  export interface WireResponse {
19
19
  status: number;
20
+ /**
21
+ * The status line's reason phrase ("Gateway Timeout"), as the platform reports it. Empty over
22
+ * HTTP/2, which has none, and absent from a transport that cannot see it. A host that words a
23
+ * failure from the phrase reads it here; nothing else should.
24
+ */
25
+ statusText?: string;
20
26
  /** The Content-Type header as sent, or null when the server sent none. */
21
27
  contentType: string | null;
22
28
  body: ReadableStream<Uint8Array> | null;
@@ -29,6 +35,8 @@ export interface WireResponse {
29
35
  * `timeoutMs` is the host's deadline for the whole exchange; `signal` lets a caller cancel
30
36
  * earlier. A timeout or an abort rejects the promise; an HTTP error status does NOT reject -
31
37
  * it resolves with that status, because a 4xx body carries the server's own explanation.
38
+ * A rejection (or a body error) caused by the deadline is an error named "TimeoutError", so a
39
+ * caller can tell the deadline from a dropped connection without knowing which transport ran.
32
40
  */
33
41
  export interface WireTransport {
34
42
  post(url: string, encodedBody: string, headers: Record<string, string>, opts: {
@@ -9,7 +9,7 @@ export type { SeriesCompleteness, SeriesCoverage, SeriesKeyCandidate, SeriesKeyV
9
9
  export { classifyForAggregation, allowedAggregations, defaultAggregation, isAggregationAllowed, shareOfTotalIsHonest, nameLooksIntensiveRate, nameLooksPositional, stripHostAggPrefix, hasDefaultAggPrefix, collapseRepeatedAggPrefix, codeNeedsLegacyAggNames, englishImplicitAggNames, INTENSIVE_WORD_TOKENS, INTENSIVE_SUFFIX_TOKENS, POSITIONAL_WORD_TOKENS, POSITIONAL_SUFFIX_TOKENS, } from "./aggregation";
10
10
  export type { AggKind, AggAdditivity, AggBasis, AggNature, AggregationClass, AggregationColumn, } from "./aggregation";
11
11
  export type { LLMColumnWithValue } from "./models";
12
- export type { LLMRequestModifier, SimpleColumn, VegaRendererPayload, LLMClientHints, LLMRequestCode, LLMQualifyResult, LLMRequestCodeResult, GetLicenseStatusResult, } from "./models";
12
+ export type { LLMRequestModifier, SimpleColumn, VegaRendererPayload, LLMClientHints, LLMRequestCode, LLMQualifyResult, LLMRequestCodeResult, LLMResultNotice, GetLicenseStatusResult, } from "./models";
13
13
  export { ROLE_MATCH_PCT, CITY_ROLE_MATCH_PCT, isBlankLike } from "./matchQuality";
14
14
  export { detectOrdinalDomain, safeDistinctValuesToShip, isOrdinalFriendlyName } from "./ordinalDetector";
15
15
  export { detectFormatSignature } from "./formatDetector";
@@ -44,8 +44,11 @@ export type { WireSigner, WireTransport, WireResponse, CredentialTriple, Credent
44
44
  export { encodePayload, gzipWireText, keyedSigner, messageSignature, readWireField } from "./wire";
45
45
  export type { GzipText } from "./wire";
46
46
  export { readGenerateStream, isNdjsonContentType, wireResponseFromFetch } from "./wireStream";
47
+ export type { OnStage } from "./wireStream";
47
48
  export { parseGenerateResponse, parseQualifyResponse, parseReviewVerdict } from "./wireParse";
48
- export type { ParsedGenerateResponse, ParsedQualifyResponse, ParsedQualifyChart, ParsedQualifyRefusal, ParsedReviewVerdict, WirePointBinding, WirePointColumns, } from "./wireParse";
49
+ export type { ParsedGenerateResponse, ParsedQualifyResponse, ParsedQualifyChart, ParsedQualifyRefusal, ParsedReviewVerdict, ParsedNotice, WirePointBinding, WirePointColumns, } from "./wireParse";
50
+ export { PROGRESS_STAGE_IDS, progressStageOf, FREEMIUM_ATTEMPT_SPENT, CLIENT_SECRET_MISMATCH, FREEMIUM_COLUMN_CAP, answerIsRetryable, } from "./messageCodes";
51
+ export type { ProgressStageId } from "./messageCodes";
49
52
  export { viewportFields, maxNonMeasureCardinality, credentialFields, resolveFetchVersion, fetchFields, capabilityFields, retryFields, leafCardinalityField, shortlistIsStale, offeredShortlistFor, } from "./wireBuild";
50
53
  export type { ViewportFields, CredentialFields, FetchRequest, FetchFields, CapabilityFields, RetryFields, } from "./wireBuild";
51
54
  export { schemaIdentity, schemaIdentityKey, schemaTypeFamily } from "./schemaIdentity";
@@ -56,3 +59,5 @@ export { createTelemetryClient } from "./telemetryClient";
56
59
  export type { TelemetryClient, TelemetryServices, TelemetryEnv, TelemetryFailure, TelemetryChannel } from "./telemetryClient";
57
60
  export { fetchTransport } from "./fetchTransport";
58
61
  export type { FetchFunction, FetchTransportOptions } from "./fetchTransport";
62
+ export { createGenerateClient, HTTP_BODY_START_CHARS } from "./generateClient";
63
+ export type { GenerateClient, GenerateClientServices, GenerateClientEnv, GenerateCall, WireOutcome, AnswerOutcome, HttpOutcome, TransportOutcome, WireCallOptions, GenerateCallOptions, QualifyCallOptions, } from "./generateClient";
@@ -0,0 +1,28 @@
1
+ /** The progress stages a generation reports, as the stream's `stageId`. `working` is the stage
2
+ * before the first milestone. */
3
+ export declare const PROGRESS_STAGE_IDS: readonly ["working", "analyze", "generate", "refine", "review"];
4
+ export type ProgressStageId = typeof PROGRESS_STAGE_IDS[number];
5
+ /**
6
+ * Which stage a progress line reports: its `stageId` when the server sent a known one, otherwise -
7
+ * an older server, which sends only the English label - the label read the way hosts always read it
8
+ * (`analyz`, `generat`, `refin`, `review`). null when neither says: a host then shows the label as
9
+ * it is. A known code always wins over the label, whatever language the label is in.
10
+ */
11
+ export declare function progressStageOf(stageId: string | null | undefined, stageLabel: string | null | undefined): ProgressStageId | null;
12
+ /** The freemium state that claims the attempt produced NO chart - the one message a chart already
13
+ * on screen contradicts. Every other freemium state (the limit reached, a warning) stays true with
14
+ * a chart painted. */
15
+ export declare const FREEMIUM_ATTEMPT_SPENT = "FREEMIUM_ATTEMPT_SPENT";
16
+ /** The licence answer for an account whose Client Secret Key is missing or does not match - the
17
+ * one a host answers by dropping a stale saved secret. */
18
+ export declare const CLIENT_SECRET_MISMATCH = "CLIENT_SECRET_MISMATCH";
19
+ /** The free tier's field cap: a wall that spent nothing (the historical `refusalCode`, kept). */
20
+ export declare const FREEMIUM_COLUMN_CAP = "FREEMIUM_COLUMN_CAP";
21
+ /**
22
+ * May the same request, sent again, answer differently? The server's `retryable` flag when it sent
23
+ * one; null when it did not (a success, or a server older than the flag) - the host then decides as
24
+ * it did before. Never read from the message text.
25
+ */
26
+ export declare function answerIsRetryable(answer: {
27
+ retryable?: boolean | null;
28
+ } | null | undefined): boolean | null;
@@ -262,6 +262,7 @@ export type LLMOfferedShortlist = {
262
262
  };
263
263
  export type LLMQualifyResult = {
264
264
  errorMessage?: string;
265
+ errorCode?: string;
265
266
  charts?: {
266
267
  name?: string;
267
268
  description?: string;
@@ -285,6 +286,7 @@ export type LLMQualifyResult = {
285
286
  refused?: {
286
287
  name?: string;
287
288
  reason?: string;
289
+ reasonCode?: string;
288
290
  isVeto?: boolean;
289
291
  }[];
290
292
  noFitSummary?: string;
@@ -298,6 +300,9 @@ export type LLMRequestCodeResult = {
298
300
  isServiceError: boolean;
299
301
  isRefusal?: boolean;
300
302
  refusalCode?: string;
303
+ errorCode?: string;
304
+ retryable?: boolean;
305
+ notices?: LLMResultNotice[];
301
306
  isRateLimited?: boolean;
302
307
  retryAfterSeconds?: number;
303
308
  isVersionNotFound?: boolean;
@@ -318,6 +323,7 @@ export type LLMRequestCodeResult = {
318
323
  freemiumPercentUsedRaw?: number;
319
324
  freemiumExhausted?: boolean;
320
325
  freemiumStatusMessage?: string;
326
+ freemiumStatusCode?: string;
321
327
  userReply?: string;
322
328
  userReplyOutcome?: string;
323
329
  improvementSuggestion?: string;
@@ -337,8 +343,15 @@ export type LLMRequestCodeResult = {
337
343
  destPointLonColumn?: string;
338
344
  destPointCountryColumn?: string;
339
345
  };
346
+ export type LLMResultNotice = {
347
+ code?: string;
348
+ severity?: string;
349
+ text?: string;
350
+ };
340
351
  export type GetLicenseStatusResult = {
341
352
  errorMessage: string;
353
+ errorCode?: string;
354
+ freemiumStatusCode?: string;
342
355
  canContinue: boolean;
343
356
  creditsLeft?: number;
344
357
  warnCredits: boolean;
@@ -27,9 +27,10 @@ export type FetchLike = (input: any, init?: any) => Promise<Response>;
27
27
  * that wires that client to the given fetch. Driven through what every transport meets: an ordinary
28
28
  * post (url, method, body and headers reach the network as given), an HTTP error (RESOLVES with its
29
29
  * status, and its body is still readable - a 4xx body carries the server's own explanation), a 204,
30
- * a network failure (rejects), no answer inside the deadline (rejects, and the request is aborted so
31
- * the socket drops), a body that stalls after headers that came in time (the deadline covers the
32
- * whole exchange, so the read ends in an error), and a caller's signal (rejects when it aborts). Uses
30
+ * a network failure (rejects), no answer inside the deadline (rejects with an error named
31
+ * TimeoutError, and the request is aborted so the socket drops), a body that stalls after headers
32
+ * that came in time (the deadline covers the whole exchange, so the read ends in a TimeoutError),
33
+ * and a caller's signal (rejects when it aborts). Uses
33
34
  * real timers and a deadline of a few tens of milliseconds.
34
35
  */
35
36
  export declare function assertWireTransportConformance(make: (fetch: FetchLike) => WireTransport): Promise<void>;
@@ -11,10 +11,31 @@ export interface WirePointColumns {
11
11
  export interface WirePointBinding extends WirePointColumns {
12
12
  dest?: WirePointColumns;
13
13
  }
14
+ /** One sentence of the composed warning, with the code that names it. */
15
+ export interface ParsedNotice {
16
+ /** Stable, kebab-case ("summed-rate", "pick-substituted", ...); "" when the server sent none. */
17
+ code: string;
18
+ /** "blocked" | "substituted" | "data" | "advisory", or "" when absent. */
19
+ severity: string;
20
+ text: string;
21
+ }
14
22
  /** A generate result's fields, typed. */
15
23
  export interface ParsedGenerateResponse {
16
24
  /** The server's own words when it declined. "" on a success. */
17
25
  errorMessage: string;
26
+ /** WHICH message errorMessage is, as a stable code; "" on a success and from an older server.
27
+ * Decide by this, never by the sentence (messageCodes.ts). */
28
+ errorCode: string;
29
+ /** Which refusal, when the server declined before any model ran; "" otherwise. */
30
+ refusalCode: string;
31
+ /** Whether the same request sent again can answer differently: true or false when the server
32
+ * said, null when it did not (a success, or an older server - decide as before). */
33
+ retryable: boolean | null;
34
+ /** The composed warning, sentence by sentence; [] when there is none or the server is older.
35
+ * Joining the texts in order gives warningMessage. */
36
+ notices: ParsedNotice[];
37
+ /** Which freemium state freemiumStatusMessage states; "" when absent. */
38
+ freemiumStatusCode: string;
18
39
  code: string;
19
40
  language: string;
20
41
  /** 0 when absent. */
@@ -95,6 +116,9 @@ export interface ParsedQualifyRefusal {
95
116
  name: string;
96
117
  /** A sentence naming one requirement the data fails; "" when the server could not name it. */
97
118
  reason: string;
119
+ /** Which gate wrote the reason, as a stable code; "" when there is no reason or the server is
120
+ * older. A host may word a code it knows itself; the sentence is the fallback. */
121
+ reasonCode: string;
98
122
  /**
99
123
  * True only when the server said so: a required channel is absent and no rebinding supplies
100
124
  * it. Absent, null or anything but true reads as a preference an explicit pick may override -
@@ -105,6 +129,8 @@ export interface ParsedQualifyRefusal {
105
129
  /** A qualify answer's fields, typed. */
106
130
  export interface ParsedQualifyResponse {
107
131
  errorMessage: string;
132
+ /** Which message errorMessage is; "" on success and from an older server. */
133
+ errorCode: string;
108
134
  /** In the server's order - it IS the ranking. null when the body carried no list at all. */
109
135
  charts: ParsedQualifyChart[] | null;
110
136
  refused: ParsedQualifyRefusal[];
@@ -126,6 +152,9 @@ export interface ParsedReviewVerdict {
126
152
  */
127
153
  fix: unknown;
128
154
  errorMessage: string | null;
155
+ /** Which message errorMessage is (a REVIEW_* or licence code); null when absent. A fix's own
156
+ * code is on the fix. */
157
+ errorCode: string | null;
129
158
  }
130
159
  /** A vision-review body -> its verdict. null for a null or non-object body. */
131
160
  export declare function parseReviewVerdict(data: unknown): ParsedReviewVerdict | null;
@@ -9,15 +9,21 @@ export declare function isNdjsonContentType(contentType: string | null | undefin
9
9
  */
10
10
  export declare function wireResponseFromFetch(res: {
11
11
  status?: number;
12
+ statusText?: string;
12
13
  headers?: {
13
14
  get(name: string): string | null;
14
15
  } | null;
15
16
  body?: ReadableStream<Uint8Array> | null;
16
17
  text(): Promise<string>;
17
18
  }): WireResponse;
19
+ /** A progress line: the stage's display text (never empty) and its code, undefined from an older
20
+ * server. */
21
+ export type OnStage = (stage: string, stageId?: string) => void;
18
22
  /**
19
23
  * The generate result a response carries, whether it streamed or not. `onStage` receives each
20
- * non-empty progress stage label as it arrives. Throws when there is no result (see the rules at
21
- * the top of this file for which error means what).
24
+ * progress line as it arrives: the stage label (display text) and, from a server that sends one,
25
+ * its `stageId` - the code a host picks its own waiting lines by (see `progressStageOf`), never the
26
+ * label. A line with no label is skipped, as it always was. Throws when there is no result (see the rules at the top
27
+ * of this file for which error means what).
22
28
  */
23
- export declare function readGenerateStream(res: WireResponse, onStage?: (stage: string) => void): Promise<Record<string, any>>;
29
+ export declare function readGenerateStream(res: WireResponse, onStage?: OnStage): Promise<Record<string, any>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bicharts/shape-core",
3
- "version": "0.6.35",
3
+ "version": "0.6.37",
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",
@@ -1,4 +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{u as c}from"./chunk-NFSQ4O5R.mjs";import{gzip as h}from"pako";var w=e=>h(e);function P(e){return x(w(JSON.stringify(e))).replace(/\//g,".")}function x(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function T(e){if(typeof e!="string"||e==="")throw new TypeError("keyedSigner needs the host's signing key");return{sign:t=>String(c(t+e))}}function W(e,t){let n=t.sign(e);if(typeof n!="string"||n.trim()==="")throw new TypeError("the host's signer returned a blank signature");return n}function u(e,t){if(e==null||typeof e!="object")return;let n=e,r=n[t];return r??n[t.charAt(0).toUpperCase()+t.slice(1)]}function m(e){return String(e??"").toLowerCase().includes("ndjson")}function C(e){let t=null;try{t=e.headers?.get?.("content-type")??null}catch{t=null}return{status:typeof e.status=="number"?e.status:0,contentType:t,body:e.body??null,text:()=>e.text()}}function S(e,t,n){let r=e.trim();if(!r)return{result:null,typed:!1,parsed:!1};let i;try{i=JSON.parse(r)}catch{return{result:null,typed:!1,parsed:!1}}return f(i,t,n)}function f(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))return{result:null,typed:!1,parsed:!0};let r=u(e,"type");if(r!=null){if(r==="progress"){let s=String(u(e,"stage")??"").trim();return s&&t?.(s),{result:null,typed:!0,parsed:!0}}if(r==="result"){let s=u(e,"result");return{result:s&&typeof s=="object"?s:null,typed:!0,parsed:!0}}return{result:null,typed:!0,parsed:!0}}return n?{result:u(e,"code")!==void 0||u(e,"errorMessage")!==void 0?e:null,typed:!1,parsed:!0}:{result:e,typed:!1,parsed:!0}}var a=class{constructor(t){this.onStage=t}onStage;result=null;anyParsed=!1;take(t){let n=S(t,this.onStage,!0);n.parsed&&(this.anyParsed=!0),n.result&&(n.typed||this.result===null)&&(this.result=n.result)}};function d(){return new Error("the generate response ended without a result")}async function R(e,t){let n=e.body;if(!n||typeof n.getReader!="function")return p(await e.text(),t,null);let r=n.getReader(),i=new TextDecoder,s=new a(t),o="";try{for(;;){let{done:y,value:g}=await r.read();if(y)break;o+=i.decode(g,{stream:!0});let l;for(;(l=o.indexOf(`
3
- `))>=0;)s.take(o.slice(0,l)),o=o.slice(l+1)}}finally{try{r.releaseLock?.()}catch{}}if(o+=i.decode(),s.take(o),!s.result)throw d();return s.result}function p(e,t,n){let r=new a(t);for(let i of e.split(`
4
- `))r.take(i);if(r.result)return r.result;throw!r.anyParsed&&n?n:d()}async function b(e,t){let n=await e.text(),r;try{r=JSON.parse(n)}catch(s){return p(n,t,s)}if(!r||typeof r!="object"||Array.isArray(r))throw new SyntaxError("the generate response was JSON but not a result object");let i=f(r,t,!1);if(i.result)return i.result;throw d()}async function N(e,t){return m(e.contentType)?R(e,t):b(e,t)}export{w as a,P as b,T as c,W as d,u as e,m as f,C as g,N as h};