@graphysdk/agents-sdk 1.6.0 → 1.6.1-beta.1780994924060

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const a=e=>"progress"===e.type,i=e=>"complete"===e.type,n=e=>"error"===e.type;class o{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return a(e)}static isCompleteEvent(e){return i(e)}static isErrorEvent(e){return n(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,p,d,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,o,c),z=b.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(h=yield y.next()).done);f=!0){d=h.value,f=!1;const e=d;if(a(e)&&s&&s(e),i(e))return e.data;if(n(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){l={error:e}}finally{try{f||m||!(p=y.return)||(yield p.call(y))}finally{if(l)throw l.error}}const o=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new r("Response body is null");const a=t.body.getReader(),i=new TextDecoder;let n="",o="",s="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;n+=i.decode(r,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))o=t.slice(7).trim();else if(t.startsWith("data: "))s+=(s?"\n":"")+t.slice(6);else if(""===t.trim()&&s){try{const t=JSON.parse(s);let r;if("progress"===o){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===o)r={type:"complete",data:t};else if("error"===o){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===o){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==o){o="",s="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===o||"error"===o)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}o="",s=""}}}finally{a.releaseLock()}})}makeRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1,n="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),m=()=>s.abort();a&&a.addEventListener("abort",m);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===n&&{body:JSON.stringify(t)}));if(!c.ok){const o=c.status>=500||429===c.status;let s,m=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?m=t.message:"string"==typeof t.error&&(m=t.error),"string"==typeof t.code&&(s=t.code)}}catch(e){}const l=new r(m,{status:c.status,code:s,retryable:o});if(o&&i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,a,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${m}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(o){if(o instanceof r)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;if(i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,a,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const s=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),p=t.z.enum(["agentic","fast"]),d=3e5,u=5e5,g=t.z.object({maxWallClockMs:t.z.number().positive().max(d).optional(),maxTotalTokens:t.z.number().int().positive().max(u).optional(),maxCostUsd:t.z.number().positive().max(10).optional()}),h=t.z.object({callId:t.z.string().max(256).optional(),locale:s.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:g.optional(),executionMode:p.optional(),enforceTableRowCap:t.z.boolean().optional()}),f=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),y=1e4,b=t.z.enum(["comparison","relationship","distribution","composition"]),z=t.z.object({config:c,userPrompt:t.z.string().max(y).optional().default(""),metadata:h.optional(),chartFamily:b.optional()}),x=z.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),v=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=t.z.object({dataPrepPrompt:t.z.string(),chartType:v,summary:t.z.string()}),_=z.extend({userPrompt:t.z.string().max(y),mutationReceipt:f.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),w=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),E=t.z.object({suggestions:t.z.array(S)}),T=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:b.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),C=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(T).describe("Child findings, sorted by quadrant score desc.")}),j=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(C)});z.extend({mutationReceipt:f.optional()});const A=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),R=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,mutationReceipt:f.optional(),warnings:t.z.array(t.z.string()).optional()}),$=t.z.enum(["explore","mutate","narrate","annotate"]),O=t.z.object({agent:$,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),k=z.extend({userPrompt:t.z.string().max(y),stages:t.z.array($).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),P=R.extend({reasoning:t.z.array(O),stories:t.z.array(C).optional()}),D=t.z.enum(["high","medium","low"]),M=t.z.object({confidence:D,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:D,quote:t.z.string().optional()})).optional()}),I=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),G=5e5,B=2097152,X=7340032,F=6291456,N=8388608,U=F,q=N,L=12582912;function K(e){return 4*Math.ceil(e/3)}const H=K(B),W=K(X),Y=K(F),J=K(N),V=K(U),Z=K(q),Q=K(L);function ee(e){return e.replace(/\s+/g,"")}function te(e){const t=ee(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const re=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=t.z.object({mimeType:t.z.string().min(1).refine(e=>re.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(H).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ie=t.z.enum(["image","document","spreadsheet"]),ne=ae.extend({kind:t.z.literal("image")}),oe=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(Y).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),se=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(V).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),ce=t.z.discriminatedUnion("kind",[ne,oe,se]),me=t.z.object({sourceText:t.z.string().max(G).default(""),images:t.z.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(ce).max(12).optional(),metadata:h.optional()}).superRefine((e,t)=>{var r,a;const i=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[],o=null!==(a=e.attachments)&&void 0!==a?a:[];if(n.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===n.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(n.length>0){n.reduce((e,t)=>e+ee(t.dataBase64).length,0)>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let s=0,c=0,m=0,l=0,p=0,d=0,u=0;for(const e of o){const t=ee(e.dataBase64).length;switch(u+=t,e.kind){case"image":s+=1,l+=t;break;case"document":c+=1,p+=t;break;case"spreadsheet":m+=1,d+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=s<=8&&c<=2&&m<=2;o.length>0&&g&&(l>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>J&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>Z&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>Q&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const le=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:M.nullable(),lastAccuracyEvaluation:I.optional()}),pe=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),de=E,ue=t.z.enum(["deal-breaker","pro","con","family","continuity"]),ge=t.z.object({kind:ue,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),he=t.z.enum(["ok","disqualified"]),fe=t.z.object({rank:t.z.number().int().positive(),type:v,score:t.z.number(),verdict:he,factors:t.z.array(ge)}),ye=t.z.object({config:c,chartFamily:b.optional(),metadata:h.optional()}),be=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),ze=t.z.object({kind:be,message:t.z.string()}),xe=t.z.enum(["sum","avg","count","min","max"]),ve=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:xe,chartType:v,score:t.z.number(),message:t.z.string()}),Se=t.z.object({ranking:t.z.array(fe),observations:t.z.array(ze).optional().default([]),suggestions:t.z.array(ve).optional().default([])}),_e=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),we=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:_e.optional(),userPrompt:t.z.string().optional(),metadata:h.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ee=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Te=t.z.enum(["info","low","medium","high"]),Ce=t.z.object({category:Ee,severity:Te,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),je=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ce)}),Ae=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Re=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),$e=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:je.nullable(),chartVisionAudit:Re.nullable().optional().default(null),rubricScores:Ae.nullable().optional().default(null)}),Oe="/api/v0";exports.AggregationFunctionSchema=xe,exports.AggregationSuggestionSchema=ve,exports.AiChartTypeEnum=v,exports.ChartCritiqueIssueCategorySchema=Ee,exports.ChartCritiqueIssueSchema=Ce,exports.ChartCritiqueIssueSeveritySchema=Te,exports.ChartCritiqueReportSchema=je,exports.ChartFamilySchema=b,exports.ChartFitEntrySchema=fe,exports.ChartFitFactorKindSchema=ue,exports.ChartFitFactorSchema=ge,exports.ChartFitVerdictSchema=he,exports.ChartJudgeRubricSchema=_e,exports.DataObservationKindSchema=be,exports.DataObservationSchema=ze,exports.EvaluateParamsSchema=ye,exports.EvaluateResponseSchema=Se,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=T,exports.ExploreStorySchema=C,exports.ExtractAccuracyEvaluationSchema=I,exports.ExtractAttachmentInputSchema=ce,exports.ExtractAttachmentKindSchema=ie,exports.ExtractConfidenceSchema=D,exports.ExtractFromProseParamsSchema=me,exports.ExtractFromProseResponseSchema=le,exports.ExtractMetaSchema=M,exports.GenerateAnnotationsResponseSchema=A,exports.GenerateExplorationResponseSchema=j,exports.GenerateGraphResponseSchema=pe,exports.GenerateGraphSuggestionsResponseSchema=de,exports.GenerateMutationResponseSchema=R,exports.GenerateNarrativeParamsSchema=_,exports.GenerateNarrativeResponseSchema=w,exports.GeneratePipelineParamsSchema=k,exports.GeneratePipelineResponseSchema=P,exports.GenerateSuggestionsParamsSchema=x,exports.GenerateSuggestionsResponseSchema=E,exports.GraphGenerationRequestSchema=z,exports.GraphyAiSdk=class{constructor(e){this.client=new o(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${Oe}/generate`,n,r,a),s=pe.parse(o);return this.stripStorytelling(s,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.stream(`${Oe}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/narrate`,t,r,a);return w.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/suggestions`,t,r,a);return E.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/explore`,t,r,a);return j.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/annotate`,t,r,a);return A.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/mutate`,t,r,a);return R.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/pipeline`,t,r,a);return P.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/evaluate`,t,void 0,r);return Se.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/judge`,t,void 0,r);return $e.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/extract`,t,r,a);return le.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/extract`,t,r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,r){return e.__asyncGenerator(this,arguments,function*(){var a,n,o,s;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){s=c.value,m=!1;const t=s;if(i(t)){const a=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){n={error:e}}finally{try{m||a||!(o=l.return)||(yield e.__await(o.call(l)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=m,exports.JudgeParamsSchema=we,exports.JudgeResponseSchema=$e,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=u,exports.MAX_BUDGET_WALL_CLOCK_MS=d,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=L,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=N,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=F,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=X,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=B,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=q,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=U,exports.MAX_SOURCE_TEXT_LENGTH=G,exports.MAX_USER_PROMPT_LENGTH=y,exports.MetadataSchema=h,exports.MutateNarrationReceiptSchema=f,exports.PipelineAgentNameSchema=$,exports.PipelineStageReasoningSchema=O,exports.RubricScoresSchema=Ae,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=S,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ee(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ee(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ee(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=n,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type;
1
+ "use strict";var e=require("tslib"),t=require("zod");class r extends Error{constructor(e,t){var r;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(r=null==t?void 0:t.retryable)&&void 0!==r&&r}}const a=e=>"progress"===e.type,i=e=>"complete"===e.type,n=e=>"error"===e.type;class o{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return a(e)}static isCompleteEvent(e){return i(e)}static isErrorEvent(e){return n(e)}stream(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,r,a);return this.parseSSE(e)})}fetch(t,o,s,c){return e.__awaiter(this,void 0,void 0,function*(){var m,l,p,d,u;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const b=yield this.makeRequest(t,o,c),z=b.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,y=e.__asyncValues(this.parseSSE(b));!(m=(h=yield y.next()).done);f=!0){d=h.value,f=!1;const e=d;if(a(e)&&s&&s(e),i(e))return e.data;if(n(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new r(e.error,{code:e.code,retryable:null!==(u=e.retryable)&&void 0!==u&&u})}}}catch(e){l={error:e}}finally{try{f||m||!(p=y.return)||(yield p.call(y))}finally{if(l)throw l.error}}const o=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${o}ms`),new r("Stream ended without completion")}return yield b.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof r)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new r("Response body is null");const a=t.body.getReader(),i=new TextDecoder;let n="",o="",s="";try{for(;;){const{done:t,value:r}=yield e.__await(a.read());if(t)break;n+=i.decode(r,{stream:!0});const c=n.split(/\r?\n/);n=c.pop()||"";for(const t of c)if(t.startsWith("event: "))o=t.slice(7).trim();else if(t.startsWith("data: "))s+=(s?"\n":"")+t.slice(6);else if(""===t.trim()&&s){try{const t=JSON.parse(s);let r;if("progress"===o){const e=t;r=Object.assign({type:"progress"},e)}else if("complete"===o)r={type:"complete",data:t};else if("error"===o){const e=t;r=Object.assign({type:"error"},e)}else if("preview"===o){const e=t;r=Object.assign(Object.assign({},e),{type:"preview"})}else{if("reasoning"!==o){o="",s="";continue}{const e=t;r=Object.assign(Object.assign({},e),{type:"reasoning"})}}if(yield yield e.__await(r),"complete"===o||"error"===o)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}o="",s=""}}}finally{a.releaseLock()}})}makeRequest(t,a,i){return e.__awaiter(this,arguments,void 0,function*(e,t,a,i=1,n="POST"){if(!e.startsWith("/"))throw new r("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${o}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),m=()=>s.abort();a&&a.addEventListener("abort",m);try{const c=yield fetch(o,Object.assign({method:n,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===n&&{body:JSON.stringify(t)}));if(!c.ok){let o,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const m=!("QUOTA_EXCEEDED"===o)&&(c.status>=500||429===c.status),l=new r(s,{status:c.status,code:o,retryable:m});if(m&&i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,a,i+1,n)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),l}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(o){if(o instanceof r)throw o;if(o instanceof Error&&"AbortError"===o.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),o;if(i<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,a,i+1,n)}throw this.logger.error(`${this.tag} Network error: ${e}`,o),new r("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",m)}})}}const s=t.z.enum(["EN_GB","EN_US"]),c=t.z.custom(e=>null!=e&&"object"==typeof e),m=t.z.enum(["low","medium","high"]),l=t.z.enum(["none","low","medium","high"]),p=t.z.enum(["agentic","fast"]),d=3e5,u=5e5,g=t.z.object({maxWallClockMs:t.z.number().positive().max(d).optional(),maxTotalTokens:t.z.number().int().positive().max(u).optional(),maxCostUsd:t.z.number().positive().max(10).optional()}),h=t.z.object({callId:t.z.string().max(256).optional(),locale:s.optional(),effort:m.optional(),storytellingEffort:l.optional().default("low"),budget:g.optional(),executionMode:p.optional(),enforceTableRowCap:t.z.boolean().optional()}),f=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),y=1e4,b=t.z.enum(["comparison","relationship","distribution","composition"]),z=t.z.object({config:c,userPrompt:t.z.string().max(y).optional().default(""),metadata:h.optional(),chartFamily:b.optional()}),x=z.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),v=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),S=t.z.object({dataPrepPrompt:t.z.string(),chartType:v,summary:t.z.string()}),_=z.extend({userPrompt:t.z.string().max(y),mutationReceipt:f.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),w=t.z.object({response:t.z.object({message:t.z.string()}),config:c}),E=t.z.object({suggestions:t.z.array(S)}),T=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:b.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),C=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(T).describe("Child findings, sorted by quadrant score desc.")}),j=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(C)});z.extend({mutationReceipt:f.optional()});const A=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c}),R=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:c,mutationReceipt:f.optional(),warnings:t.z.array(t.z.string()).optional()}),$=t.z.enum(["explore","mutate","narrate","annotate"]),O=t.z.object({agent:$,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),k=z.extend({userPrompt:t.z.string().max(y),stages:t.z.array($).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),D=R.extend({reasoning:t.z.array(O),stories:t.z.array(C).optional()}),P=t.z.enum(["high","medium","low"]),M=t.z.object({confidence:P,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:P,quote:t.z.string().optional()})).optional()}),I=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),G=5e5,B=2097152,X=7340032,F=6291456,N=8388608,U=F,q=N,L=12582912;function K(e){return 4*Math.ceil(e/3)}const H=K(B),W=K(X),Y=K(F),J=K(N),V=K(U),Q=K(q),Z=K(L);function ee(e){return e.replace(/\s+/g,"")}function te(e){const t=ee(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const re=/^image\/(png|jpeg|jpg|webp|gif)$/i,ae=t.z.object({mimeType:t.z.string().min(1).refine(e=>re.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(H).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ie=t.z.enum(["image","document","spreadsheet"]),ne=ae.extend({kind:t.z.literal("image")}),oe=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(Y).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),se=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(V).refine(te,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),ce=t.z.discriminatedUnion("kind",[ne,oe,se]),me=t.z.object({sourceText:t.z.string().max(G).default(""),images:t.z.array(ae).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(ce).max(12).optional(),metadata:h.optional()}).superRefine((e,t)=>{var r,a;const i=e.sourceText.trim(),n=null!==(r=e.images)&&void 0!==r?r:[],o=null!==(a=e.attachments)&&void 0!==a?a:[];if(n.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===i.length&&0===n.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(n.length>0){n.reduce((e,t)=>e+ee(t.dataBase64).length,0)>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let s=0,c=0,m=0,l=0,p=0,d=0,u=0;for(const e of o){const t=ee(e.dataBase64).length;switch(u+=t,e.kind){case"image":s+=1,l+=t;break;case"document":c+=1,p+=t;break;case"spreadsheet":m+=1,d+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const g=s<=8&&c<=2&&m<=2;o.length>0&&g&&(l>W&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>J&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>Q&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>Z&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const le=t.z.object({response:t.z.object({message:t.z.string()}),config:c,extractMeta:M.nullable(),lastAccuracyEvaluation:I.optional()}),pe=t.z.object({config:c,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())})}),de=E,ue=t.z.enum(["deal-breaker","pro","con","family","continuity"]),ge=t.z.object({kind:ue,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),he=t.z.enum(["ok","disqualified"]),fe=t.z.object({rank:t.z.number().int().positive(),type:v,score:t.z.number(),verdict:he,factors:t.z.array(ge)}),ye=t.z.object({config:c,chartFamily:b.optional(),metadata:h.optional()}),be=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),ze=t.z.object({kind:be,message:t.z.string()}),xe=t.z.enum(["sum","avg","count","min","max"]),ve=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:xe,chartType:v,score:t.z.number(),message:t.z.string()}),Se=t.z.object({ranking:t.z.array(fe),observations:t.z.array(ze).optional().default([]),suggestions:t.z.array(ve).optional().default([])}),_e=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),we=t.z.object({config:c.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:_e.optional(),userPrompt:t.z.string().optional(),metadata:h.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ee=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Te=t.z.enum(["info","low","medium","high"]),Ce=t.z.object({category:Ee,severity:Te,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),je=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ce)}),Ae=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Re=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),$e=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:je.nullable(),chartVisionAudit:Re.nullable().optional().default(null),rubricScores:Ae.nullable().optional().default(null)}),Oe="/api/v0";exports.AggregationFunctionSchema=xe,exports.AggregationSuggestionSchema=ve,exports.AiChartTypeEnum=v,exports.ChartCritiqueIssueCategorySchema=Ee,exports.ChartCritiqueIssueSchema=Ce,exports.ChartCritiqueIssueSeveritySchema=Te,exports.ChartCritiqueReportSchema=je,exports.ChartFamilySchema=b,exports.ChartFitEntrySchema=fe,exports.ChartFitFactorKindSchema=ue,exports.ChartFitFactorSchema=ge,exports.ChartFitVerdictSchema=he,exports.ChartJudgeRubricSchema=_e,exports.DataObservationKindSchema=be,exports.DataObservationSchema=ze,exports.EvaluateParamsSchema=ye,exports.EvaluateResponseSchema=Se,exports.ExecutionModeSchema=p,exports.ExploreFindingSchema=T,exports.ExploreStorySchema=C,exports.ExtractAccuracyEvaluationSchema=I,exports.ExtractAttachmentInputSchema=ce,exports.ExtractAttachmentKindSchema=ie,exports.ExtractConfidenceSchema=P,exports.ExtractFromProseParamsSchema=me,exports.ExtractFromProseResponseSchema=le,exports.ExtractMetaSchema=M,exports.GenerateAnnotationsResponseSchema=A,exports.GenerateExplorationResponseSchema=j,exports.GenerateGraphResponseSchema=pe,exports.GenerateGraphSuggestionsResponseSchema=de,exports.GenerateMutationResponseSchema=R,exports.GenerateNarrativeParamsSchema=_,exports.GenerateNarrativeResponseSchema=w,exports.GeneratePipelineParamsSchema=k,exports.GeneratePipelineResponseSchema=D,exports.GenerateSuggestionsParamsSchema=x,exports.GenerateSuggestionsResponseSchema=E,exports.GraphGenerationRequestSchema=z,exports.GraphyAiSdk=class{constructor(e){this.client=new o(e)}generateGraph(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=t,n=e.__rest(t,["storytellingOptions"]),o=yield this.client.fetch(`${Oe}/generate`,n,r,a),s=pe.parse(o);return this.stripStorytelling(s,i)})}generateGraphStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,i=e.__rest(t,["storytellingOptions"]),n=yield this.client.stream(`${Oe}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,a)})}generateNarrative(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/narrate`,t,r,a);return w.parse(e)})}generateNarrativeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/narrate`,t,r)})}generateSuggestions(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/suggestions`,t,r,a);return E.parse(e)})}generateSuggestionsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/suggestions`,t,r)})}generateExploration(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/explore`,t,r,a);return j.parse(e)})}generateExplorationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/explore`,t,r)})}generateAnnotations(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/annotate`,t,r,a);return A.parse(e)})}generateAnnotationsStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/annotate`,t,r)})}generateMutation(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/mutate`,t,r,a);return R.parse(e)})}generateMutationStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/mutate`,t,r)})}generatePipeline(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/pipeline`,t,r,a);return D.parse(e)})}generatePipelineStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/pipeline`,t,r)})}evaluate(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/evaluate`,t,void 0,r);return Se.parse(e)})}judge(t,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/judge`,t,void 0,r);return $e.parse(e)})}judgeStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/judge`,t,r)})}extractFromProse(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Oe}/extract`,t,r,a);return le.parse(e)})}extractFromProseStream(t,r){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Oe}/extract`,t,r)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,r){return e.__asyncGenerator(this,arguments,function*(){var a,n,o,s;try{for(var c,m=!0,l=e.__asyncValues(t);!(a=(c=yield e.__await(l.next())).done);m=!0){s=c.value,m=!1;const t=s;if(i(t)){const a=this.stripStorytelling(t.data,r);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){n={error:e}}finally{try{m||a||!(o=l.return)||(yield e.__await(o.call(l)))}finally{if(n)throw n.error}}})}},exports.GraphyApiError=r,exports.InvocationBudgetSchema=g,exports.InvocationEffortSchema=m,exports.JudgeParamsSchema=we,exports.JudgeResponseSchema=$e,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=u,exports.MAX_BUDGET_WALL_CLOCK_MS=d,exports.MAX_EXTRACT_ATTACHMENTS=12,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=L,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=N,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=F,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=X,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=B,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=q,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=U,exports.MAX_SOURCE_TEXT_LENGTH=G,exports.MAX_USER_PROMPT_LENGTH=y,exports.MetadataSchema=h,exports.MutateNarrationReceiptSchema=f,exports.PipelineAgentNameSchema=$,exports.PipelineStageReasoningSchema=O,exports.RubricScoresSchema=Ae,exports.StorytellingEffortSchema=l,exports.SuggestionSchema=S,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ee(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ee(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ee(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isCompleteEvent=i,exports.isErrorEvent=n,exports.isGraphyApiError=e=>e instanceof r,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type;
package/dist/index.d.ts CHANGED
@@ -41,7 +41,7 @@ interface ErrorEvent {
41
41
  type: 'error';
42
42
  /** Human-readable error description. */
43
43
  error: string;
44
- /** Machine-readable error code from the API (e.g. `"RATE_LIMIT_ERROR"`). */
44
+ /** Machine-readable error code from the API (e.g. `"RATE_LIMIT_ERROR"`, `"QUOTA_EXCEEDED"`). */
45
45
  code?: string;
46
46
  /** Whether the consumer should retry the request. */
47
47
  retryable?: boolean;
@@ -144,7 +144,7 @@ type ProgressHandler = (progress: ProgressEvent) => void;
144
144
  interface GraphyApiErrorOptions {
145
145
  /** HTTP status code from the server response (e.g. 401, 429, 500). */
146
146
  status?: number;
147
- /** Machine-readable error code from the API (e.g. `"RATE_LIMIT_ERROR"`, `"VALIDATION_ERROR"`). */
147
+ /** Machine-readable error code from the API (e.g. `"RATE_LIMIT_ERROR"`, `"QUOTA_EXCEEDED"`, `"VALIDATION_ERROR"`). */
148
148
  code?: string;
149
149
  /** Whether this request is safe to retry. Defaults to `false`. */
150
150
  retryable?: boolean;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as a}from"zod";class o extends Error{constructor(e,t){var i;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const s=e=>e instanceof o,c=e=>"progress"===e.type,l=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return m(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,a){return e(this,void 0,void 0,function*(){var e,s,d,u,g;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,n,a),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,y=t(this.parseSSE(b));!(e=(h=yield y.next()).done);f=!0){u=h.value,f=!1;const e=u;if(c(e)&&r&&r(e),l(e))return e.data;if(m(e)){const t=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new o(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){s={error:e}}finally{try{f||e||!(d=y.return)||(yield d.call(y))}finally{if(s)throw s.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new o("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof o)throw e;throw e}finally{const e=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${i} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new o("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",a="",s="";try{for(;;){const{done:e,value:o}=yield n(t.read());if(e)break;r+=i.decode(o,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))a=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=JSON.parse(s);let t;if("progress"===a){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===a)t={type:"complete",data:e};else if("error"===a){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===a){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==a){a="",s="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===a||"error"===a)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}a="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const a=new URL(e,this.baseUrl);if(a.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${a}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(a,Object.assign({method:r,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!c.ok){const a=c.status>=500||429===c.status;let s,l=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?l=t.message:"string"==typeof t.error&&(l=t.error),"string"==typeof t.code&&(s=t.code)}}catch(e){}const m=new o(l,{status:c.status,code:s,retryable:a});if(a&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${a}ms (attempt ${n+1})`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${l}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(a){if(a instanceof o)throw a;if(a instanceof Error&&"AbortError"===a.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),a;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${a}ms`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,a),new o("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const p=a.enum(["EN_GB","EN_US"]),h=a.custom(e=>null!=e&&"object"==typeof e),f=a.enum(["low","medium","high"]),y=a.enum(["none","low","medium","high"]),b=a.enum(["agentic","fast"]),v=3e5,w=5e5,x=10,j=a.object({maxWallClockMs:a.number().positive().max(v).optional(),maxTotalTokens:a.number().int().positive().max(w).optional(),maxCostUsd:a.number().positive().max(10).optional()}),$=a.object({callId:a.string().max(256).optional(),locale:p.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:j.optional(),executionMode:b.optional(),enforceTableRowCap:a.boolean().optional()}),S=a.object({steps:a.array(a.string()),postProcess:a.object({measureRelevance:a.enum(["prompt-named","derived","magnitude"]).optional(),grain:a.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:a.string().optional(),comparison:a.string().optional()}).optional(),droppedMeasures:a.array(a.string()).optional(),rowCount:a.number().int().nonnegative(),totalRowCountBeforeSlice:a.number().int().positive().optional(),displayedRowCount:a.number().int().nonnegative().optional(),columnKeys:a.array(a.string()),activeFilters:a.array(a.string()).optional(),grainSummary:a.string().optional()}),k=1e4,C=a.enum(["comparison","relationship","distribution","composition"]),T=a.object({config:h,userPrompt:a.string().max(k).optional().default(""),metadata:$.optional(),chartFamily:C.optional()}),O=T.extend({maxSuggestionCount:a.number().int().min(1).max(4).optional()}),R=a.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),P=a.object({dataPrepPrompt:a.string(),chartType:R,summary:a.string()}),I=T.extend({userPrompt:a.string().max(k),mutationReceipt:S.optional(),exploreFindingSummary:a.string().max(500).optional()}),E=a.object({response:a.object({message:a.string()}),config:h}),A=a.object({suggestions:a.array(P)}),B=a.object({finding:a.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:a.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:a.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:a.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:a.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:C.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:a.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),F=a.object({topic:a.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:a.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:a.number().int().min(1).describe("Number of findings in this story."),findings:a.array(B).describe("Child findings, sorted by quadrant score desc.")}),q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(F)});T.extend({mutationReceipt:S.optional()});const U=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h}),N=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:S.optional(),warnings:a.array(a.string()).optional()}),D=a.enum(["explore","mutate","narrate","annotate"]),K=a.object({agent:D,summary:a.string(),steps:a.array(a.string()).optional()}),M=T.extend({userPrompt:a.string().max(k),stages:a.array(D).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:a.string().max(500).optional()}),L=N.extend({reasoning:a.array(K),stories:a.array(F).optional()}),G=a.enum(["high","medium","low"]),W=a.object({confidence:G,needsUserInput:a.boolean(),warnings:a.array(a.string()),cellConfidence:a.array(a.object({rowIndex:a.number().int().nonnegative(),columnKey:a.string(),confidence:G,quote:a.string().optional()})).optional()}),_=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),z=5e5,H=8,J=2097152,V=7340032,X=2,Y=6291456,Z=8388608,Q=2,ee=Y,te=Z,ie=12582912,ne=12;function re(e){return 4*Math.ceil(e/3)}const ae=re(J),oe=re(V),se=re(Y),ce=re(Z),le=re(ee),me=re(te),de=re(ie);function ue(e){return e.replace(/\s+/g,"")}function ge(e){const t=ue(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const pe=/^image\/(png|jpeg|jpg|webp|gif)$/i,he=a.object({mimeType:a.string().min(1).refine(e=>pe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:a.string().min(1).max(ae).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),fe=a.enum(["image","document","spreadsheet"]),ye=he.extend({kind:a.literal("image")}),be=a.object({kind:a.literal("document"),mimeType:a.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:a.string().min(1).max(se).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ve=a.object({kind:a.literal("spreadsheet"),mimeType:a.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:a.string().min(1).max(le).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:a.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),we=a.discriminatedUnion("kind",[ye,be,ve]),xe=a.object({sourceText:a.string().max(z).default(""),images:a.array(he).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:a.array(we).max(12).optional(),metadata:$.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),a=null!==(i=e.images)&&void 0!==i?i:[],o=null!==(n=e.attachments)&&void 0!==n?n:[];if(a.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length>0){a.reduce((e,t)=>e+ue(t.dataBase64).length,0)>oe&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let s=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of o){const t=ue(e.dataBase64).length;switch(g+=t,e.kind){case"image":s+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const p=s<=8&&c<=2&&l<=2;o.length>0&&p&&(m>oe&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>de&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function je(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}}function $e(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}}function Se(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ue(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const ke=a.object({response:a.object({message:a.string()}),config:h,extractMeta:W.nullable(),lastAccuracyEvaluation:_.optional()}),Ce=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())})}),Te=A,Oe=a.enum(["deal-breaker","pro","con","family","continuity"]),Re=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Pe=a.enum(["ok","disqualified"]),Ie=a.object({rank:a.number().int().positive(),type:R,score:a.number(),verdict:Pe,factors:a.array(Re)}),Ee=a.object({config:h,chartFamily:C.optional(),metadata:$.optional()}),Ae=a.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Be=a.object({kind:Ae,message:a.string()}),Fe=a.enum(["sum","avg","count","min","max"]),qe=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Fe,chartType:R,score:a.number(),message:a.string()}),Ue=a.object({ranking:a.array(Ie),observations:a.array(Be).optional().default([]),suggestions:a.array(qe).optional().default([])}),Ne=a.object({prompt:a.string(),datasetSummary:a.string().optional(),mustShow:a.array(a.string()).optional(),unacceptable:a.array(a.string()).optional(),acceptableChartFamilies:a.array(a.string()).optional()}),De=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:Ne.optional(),userPrompt:a.string().optional(),metadata:$.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ke=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Me=a.enum(["info","low","medium","high"]),Le=a.object({category:Ke,severity:Me,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),Ge=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(Le)}),We=a.object({dataFidelity:a.number().min(0).max(1),promptRelevance:a.number().min(0).max(1),chartTypeAppropriateness:a.number().min(0).max(1),readability:a.number().min(0).max(1),honesty:a.number().min(0).max(1),composite:a.number().min(0).max(1),rationale:a.string().optional()}),_e=a.object({capturedAt:a.string(),chartId:a.string()}),ze=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:Ge.nullable(),chartVisionAudit:_e.nullable().optional().default(null),rubricScores:We.nullable().optional().default(null)}),He="/api/v0";class Je{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,a=r(t,["storytellingOptions"]),o=yield this.client.fetch(`${He}/generate`,a,i,n),s=Ce.parse(o);return this.stripStorytelling(s,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),a=yield this.client.stream(`${He}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(a,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/narrate`,t,i,n);return E.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/suggestions`,t,i,n);return A.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/explore`,t,i,n);return q.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/annotate`,t,i,n);return U.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/mutate`,t,i,n);return N.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/mutate`,t,i)})}generatePipeline(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/pipeline`,t,i,n);return L.parse(e)})}generatePipelineStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/pipeline`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/evaluate`,t,void 0,i);return Ue.parse(e)})}judge(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/judge`,t,void 0,i);return ze.parse(e)})}judgeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/judge`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/extract`,t,i,n);return ke.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/extract`,t,i)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,r){return i(this,arguments,function*(){var i,a,o,s;try{for(var c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){s=c.value,m=!1;const e=s;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){a={error:e}}finally{try{m||i||!(o=d.return)||(yield n(o.call(d)))}finally{if(a)throw a.error}}})}}export{Fe as AggregationFunctionSchema,qe as AggregationSuggestionSchema,R as AiChartTypeEnum,Ke as ChartCritiqueIssueCategorySchema,Le as ChartCritiqueIssueSchema,Me as ChartCritiqueIssueSeveritySchema,Ge as ChartCritiqueReportSchema,C as ChartFamilySchema,Ie as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Re as ChartFitFactorSchema,Pe as ChartFitVerdictSchema,Ne as ChartJudgeRubricSchema,Ae as DataObservationKindSchema,Be as DataObservationSchema,Ee as EvaluateParamsSchema,Ue as EvaluateResponseSchema,b as ExecutionModeSchema,B as ExploreFindingSchema,F as ExploreStorySchema,_ as ExtractAccuracyEvaluationSchema,we as ExtractAttachmentInputSchema,fe as ExtractAttachmentKindSchema,G as ExtractConfidenceSchema,xe as ExtractFromProseParamsSchema,ke as ExtractFromProseResponseSchema,W as ExtractMetaSchema,U as GenerateAnnotationsResponseSchema,q as GenerateExplorationResponseSchema,Ce as GenerateGraphResponseSchema,Te as GenerateGraphSuggestionsResponseSchema,N as GenerateMutationResponseSchema,I as GenerateNarrativeParamsSchema,E as GenerateNarrativeResponseSchema,M as GeneratePipelineParamsSchema,L as GeneratePipelineResponseSchema,O as GenerateSuggestionsParamsSchema,A as GenerateSuggestionsResponseSchema,T as GraphGenerationRequestSchema,Je as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,De as JudgeParamsSchema,ze as JudgeResponseSchema,x as MAX_BUDGET_COST_USD,w as MAX_BUDGET_TOTAL_TOKENS,v as MAX_BUDGET_WALL_CLOCK_MS,ne as MAX_EXTRACT_ATTACHMENTS,ie as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,X as MAX_EXTRACT_DOCUMENTS,Z as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,Y as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,H as MAX_EXTRACT_IMAGES,V as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,J as MAX_EXTRACT_IMAGE_DECODED_BYTES,Q as MAX_EXTRACT_SPREADSHEETS,te as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,ee as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,z as MAX_SOURCE_TEXT_LENGTH,k as MAX_USER_PROMPT_LENGTH,$ as MetadataSchema,S as MutateNarrationReceiptSchema,D as PipelineAgentNameSchema,K as PipelineStageReasoningSchema,We as RubricScoresSchema,y as StorytellingEffortSchema,P as SuggestionSchema,je as buildImageAttachment,$e as buildPdfAttachment,Se as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
1
+ import{__awaiter as e,__asyncValues as t,__asyncGenerator as i,__await as n,__rest as r}from"tslib";import{z as a}from"zod";class o extends Error{constructor(e,t){var i;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(i=null==t?void 0:t.retryable)&&void 0!==i&&i}}const s=e=>e instanceof o,c=e=>"progress"===e.type,l=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type;class g{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return c(e)}static isCompleteEvent(e){return l(e)}static isErrorEvent(e){return m(e)}stream(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,i,n);return this.parseSSE(e)})}fetch(i,n,r,a){return e(this,void 0,void 0,function*(){var e,s,d,u,g;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${i}`);try{const b=yield this.makeRequest(i,n,a),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,y=t(this.parseSSE(b));!(e=(h=yield y.next()).done);f=!0){u=h.value,f=!1;const e=u;if(c(e)&&r&&r(e),l(e))return e.data;if(m(e)){const t=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${i} ${t}ms`,e.error),new o(e.error,{code:e.code,retryable:null!==(g=e.retryable)&&void 0!==g&&g})}}}catch(e){s={error:e}}finally{try{f||e||!(d=y.return)||(yield d.call(y))}finally{if(s)throw s.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${i} ${n}ms`),new o("Stream ended without completion")}return yield b.json()}catch(e){const t=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${i} ${t}ms`,e),e instanceof o)throw e;throw e}finally{const e=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${i} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return i(this,arguments,function*(){if(!e.body)throw new o("Response body is null");const t=e.body.getReader(),i=new TextDecoder;let r="",a="",s="";try{for(;;){const{done:e,value:o}=yield n(t.read());if(e)break;r+=i.decode(o,{stream:!0});const c=r.split(/\r?\n/);r=c.pop()||"";for(const e of c)if(e.startsWith("event: "))a=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=JSON.parse(s);let t;if("progress"===a){const i=e;t=Object.assign({type:"progress"},i)}else if("complete"===a)t={type:"complete",data:e};else if("error"===a){const i=e;t=Object.assign({type:"error"},i)}else if("preview"===a){const i=e;t=Object.assign(Object.assign({},i),{type:"preview"})}else{if("reasoning"!==a){a="",s="";continue}{const i=e;t=Object.assign(Object.assign({},i),{type:"reasoning"})}}if(yield yield n(t),"complete"===a||"error"===a)return yield n(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}a="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,i,n){return e(this,arguments,void 0,function*(e,t,i,n=1,r="POST"){if(!e.startsWith("/"))throw new o("Invalid endpoint: must start with /");const a=new URL(e,this.baseUrl);if(a.origin!==new URL(this.baseUrl).origin)throw new o("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${n}/${this.retryConfig.attempts}: ${a}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();i&&i.addEventListener("abort",l);try{const c=yield fetch(a,Object.assign({method:r,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===r&&{body:JSON.stringify(t)}));if(!c.ok){let a,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(a=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===a)&&(c.status>=500||429===c.status),m=new o(s,{status:c.status,code:a,retryable:l});if(l&&n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${a}ms (attempt ${n+1})`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(a){if(a instanceof o)throw a;if(a instanceof Error&&"AbortError"===a.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),a;if(n<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const a=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,n-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${a}ms`),yield this.sleep(a),this.makeRequest(e,t,i,n+1,r)}throw this.logger.error(`${this.tag} Network error: ${e}`,a),new o("Network error",{retryable:!0})}finally{clearTimeout(c),i&&i.removeEventListener("abort",l)}})}}const p=a.enum(["EN_GB","EN_US"]),h=a.custom(e=>null!=e&&"object"==typeof e),f=a.enum(["low","medium","high"]),y=a.enum(["none","low","medium","high"]),b=a.enum(["agentic","fast"]),v=3e5,w=5e5,x=10,j=a.object({maxWallClockMs:a.number().positive().max(v).optional(),maxTotalTokens:a.number().int().positive().max(w).optional(),maxCostUsd:a.number().positive().max(10).optional()}),$=a.object({callId:a.string().max(256).optional(),locale:p.optional(),effort:f.optional(),storytellingEffort:y.optional().default("low"),budget:j.optional(),executionMode:b.optional(),enforceTableRowCap:a.boolean().optional()}),S=a.object({steps:a.array(a.string()),postProcess:a.object({measureRelevance:a.enum(["prompt-named","derived","magnitude"]).optional(),grain:a.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:a.string().optional(),comparison:a.string().optional()}).optional(),droppedMeasures:a.array(a.string()).optional(),rowCount:a.number().int().nonnegative(),totalRowCountBeforeSlice:a.number().int().positive().optional(),displayedRowCount:a.number().int().nonnegative().optional(),columnKeys:a.array(a.string()),activeFilters:a.array(a.string()).optional(),grainSummary:a.string().optional()}),k=1e4,C=a.enum(["comparison","relationship","distribution","composition"]),T=a.object({config:h,userPrompt:a.string().max(k).optional().default(""),metadata:$.optional(),chartFamily:C.optional()}),O=T.extend({maxSuggestionCount:a.number().int().min(1).max(4).optional()}),E=a.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),R=a.object({dataPrepPrompt:a.string(),chartType:E,summary:a.string()}),P=T.extend({userPrompt:a.string().max(k),mutationReceipt:S.optional(),exploreFindingSummary:a.string().max(500).optional()}),I=a.object({response:a.object({message:a.string()}),config:h}),A=a.object({suggestions:a.array(R)}),B=a.object({finding:a.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:a.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:a.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:a.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:a.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:C.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:a.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),F=a.object({topic:a.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:a.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:a.number().int().min(1).describe("Number of findings in this story."),findings:a.array(B).describe("Child findings, sorted by quadrant score desc.")}),U=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),stories:a.array(F)});T.extend({mutationReceipt:S.optional()});const q=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h}),D=a.object({response:a.object({message:a.string(),steps:a.array(a.string())}),config:h,mutationReceipt:S.optional(),warnings:a.array(a.string()).optional()}),N=a.enum(["explore","mutate","narrate","annotate"]),K=a.object({agent:N,summary:a.string(),steps:a.array(a.string()).optional()}),M=T.extend({userPrompt:a.string().max(k),stages:a.array(N).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:a.string().max(500).optional()}),L=D.extend({reasoning:a.array(K),stories:a.array(F).optional()}),G=a.enum(["high","medium","low"]),W=a.object({confidence:G,needsUserInput:a.boolean(),warnings:a.array(a.string()),cellConfidence:a.array(a.object({rowIndex:a.number().int().nonnegative(),columnKey:a.string(),confidence:G,quote:a.string().optional()})).optional()}),_=a.object({score:a.number().min(0).max(1),issues:a.array(a.string()),sufficient:a.boolean(),summary:a.string()}),z=5e5,H=8,J=2097152,X=7340032,Q=2,V=6291456,Y=8388608,Z=2,ee=V,te=Y,ie=12582912,ne=12;function re(e){return 4*Math.ceil(e/3)}const ae=re(J),oe=re(X),se=re(V),ce=re(Y),le=re(ee),me=re(te),de=re(ie);function ue(e){return e.replace(/\s+/g,"")}function ge(e){const t=ue(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const pe=/^image\/(png|jpeg|jpg|webp|gif)$/i,he=a.object({mimeType:a.string().min(1).refine(e=>pe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:a.string().min(1).max(ae).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),fe=a.enum(["image","document","spreadsheet"]),ye=he.extend({kind:a.literal("image")}),be=a.object({kind:a.literal("document"),mimeType:a.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:a.string().min(1).max(se).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ve=a.object({kind:a.literal("spreadsheet"),mimeType:a.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:a.string().min(1).max(le).refine(ge,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:a.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),we=a.discriminatedUnion("kind",[ye,be,ve]),xe=a.object({sourceText:a.string().max(z).default(""),images:a.array(he).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:a.array(we).max(12).optional(),metadata:$.optional()}).superRefine((e,t)=>{var i,n;const r=e.sourceText.trim(),a=null!==(i=e.images)&&void 0!==i?i:[],o=null!==(n=e.attachments)&&void 0!==n?n:[];if(a.length>0&&o.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===o.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length>0){a.reduce((e,t)=>e+ue(t.dataBase64).length,0)>oe&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let s=0,c=0,l=0,m=0,d=0,u=0,g=0;for(const e of o){const t=ue(e.dataBase64).length;switch(g+=t,e.kind){case"image":s+=1,m+=t;break;case"document":c+=1,d+=t;break;case"spreadsheet":l+=1,u+=t}}s>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),c>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),l>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const p=s<=8&&c<=2&&l<=2;o.length>0&&p&&(m>oe&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),u>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>de&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function je(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}}function $e(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}}function Se(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ue(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const ke=a.object({response:a.object({message:a.string()}),config:h,extractMeta:W.nullable(),lastAccuracyEvaluation:_.optional()}),Ce=a.object({config:h,response:a.object({message:a.string(),steps:a.array(a.string())})}),Te=A,Oe=a.enum(["deal-breaker","pro","con","family","continuity"]),Ee=a.object({kind:Oe,label:a.string(),weight:a.number(),reason:a.string()}),Re=a.enum(["ok","disqualified"]),Pe=a.object({rank:a.number().int().positive(),type:E,score:a.number(),verdict:Re,factors:a.array(Ee)}),Ie=a.object({config:h,chartFamily:C.optional(),metadata:$.optional()}),Ae=a.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Be=a.object({kind:Ae,message:a.string()}),Fe=a.enum(["sum","avg","count","min","max"]),Ue=a.object({dimensionName:a.string(),dimensionLabel:a.string(),measureName:a.string().nullable(),measureLabel:a.string().nullable(),fn:Fe,chartType:E,score:a.number(),message:a.string()}),qe=a.object({ranking:a.array(Pe),observations:a.array(Be).optional().default([]),suggestions:a.array(Ue).optional().default([])}),De=a.object({prompt:a.string(),datasetSummary:a.string().optional(),mustShow:a.array(a.string()).optional(),unacceptable:a.array(a.string()).optional(),acceptableChartFamilies:a.array(a.string()).optional()}),Ne=a.object({config:h.optional(),chartImage:a.string().optional(),data:a.unknown().optional(),rubric:De.optional(),userPrompt:a.string().optional(),metadata:$.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ke=a.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Me=a.enum(["info","low","medium","high"]),Le=a.object({category:Ke,severity:Me,observation:a.string(),rationale:a.string().optional(),suggestedChange:a.string().optional(),configPaths:a.array(a.string()).optional()}),Ge=a.object({overallSummary:a.string(),overallSeverity:a.enum(["none","low","medium","high"]).optional(),issues:a.array(Le)}),We=a.object({dataFidelity:a.number().min(0).max(1),promptRelevance:a.number().min(0).max(1),chartTypeAppropriateness:a.number().min(0).max(1),readability:a.number().min(0).max(1),honesty:a.number().min(0).max(1),composite:a.number().min(0).max(1),rationale:a.string().optional()}),_e=a.object({capturedAt:a.string(),chartId:a.string()}),ze=a.object({response:a.object({message:a.string(),steps:a.array(a.string()),critiqueCommitted:a.boolean()}),critiqueReport:Ge.nullable(),chartVisionAudit:_e.nullable().optional().default(null),rubricScores:We.nullable().optional().default(null)}),He="/api/v0";class Je{constructor(e){this.client=new g(e)}generateGraph(t,i,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,a=r(t,["storytellingOptions"]),o=yield this.client.fetch(`${He}/generate`,a,i,n),s=Ce.parse(o);return this.stripStorytelling(s,e)})}generateGraphStream(t,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,n=r(t,["storytellingOptions"]),a=yield this.client.stream(`${He}/generate`,n,i);return this.wrapStreamWithStorytellingStripping(a,e)})}generateNarrative(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/narrate`,t,i,n);return I.parse(e)})}generateNarrativeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/narrate`,t,i)})}generateSuggestions(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/suggestions`,t,i,n);return A.parse(e)})}generateSuggestionsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/suggestions`,t,i)})}generateExploration(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/explore`,t,i,n);return U.parse(e)})}generateExplorationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/explore`,t,i)})}generateAnnotations(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/annotate`,t,i,n);return q.parse(e)})}generateAnnotationsStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/annotate`,t,i)})}generateMutation(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/mutate`,t,i,n);return D.parse(e)})}generateMutationStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/mutate`,t,i)})}generatePipeline(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/pipeline`,t,i,n);return L.parse(e)})}generatePipelineStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/pipeline`,t,i)})}evaluate(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/evaluate`,t,void 0,i);return qe.parse(e)})}judge(t,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/judge`,t,void 0,i);return ze.parse(e)})}judgeStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/judge`,t,i)})}extractFromProse(t,i,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${He}/extract`,t,i,n);return ke.parse(e)})}extractFromProseStream(t,i){return e(this,void 0,void 0,function*(){return this.client.stream(`${He}/extract`,t,i)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,r){return i(this,arguments,function*(){var i,a,o,s;try{for(var c,m=!0,d=t(e);!(i=(c=yield n(d.next())).done);m=!0){s=c.value,m=!1;const e=s;if(l(e)){const t=this.stripStorytelling(e.data,r);yield yield n(Object.assign(Object.assign({},e),{data:t}))}else yield yield n(e)}}catch(e){a={error:e}}finally{try{m||i||!(o=d.return)||(yield n(o.call(d)))}finally{if(a)throw a.error}}})}}export{Fe as AggregationFunctionSchema,Ue as AggregationSuggestionSchema,E as AiChartTypeEnum,Ke as ChartCritiqueIssueCategorySchema,Le as ChartCritiqueIssueSchema,Me as ChartCritiqueIssueSeveritySchema,Ge as ChartCritiqueReportSchema,C as ChartFamilySchema,Pe as ChartFitEntrySchema,Oe as ChartFitFactorKindSchema,Ee as ChartFitFactorSchema,Re as ChartFitVerdictSchema,De as ChartJudgeRubricSchema,Ae as DataObservationKindSchema,Be as DataObservationSchema,Ie as EvaluateParamsSchema,qe as EvaluateResponseSchema,b as ExecutionModeSchema,B as ExploreFindingSchema,F as ExploreStorySchema,_ as ExtractAccuracyEvaluationSchema,we as ExtractAttachmentInputSchema,fe as ExtractAttachmentKindSchema,G as ExtractConfidenceSchema,xe as ExtractFromProseParamsSchema,ke as ExtractFromProseResponseSchema,W as ExtractMetaSchema,q as GenerateAnnotationsResponseSchema,U as GenerateExplorationResponseSchema,Ce as GenerateGraphResponseSchema,Te as GenerateGraphSuggestionsResponseSchema,D as GenerateMutationResponseSchema,P as GenerateNarrativeParamsSchema,I as GenerateNarrativeResponseSchema,M as GeneratePipelineParamsSchema,L as GeneratePipelineResponseSchema,O as GenerateSuggestionsParamsSchema,A as GenerateSuggestionsResponseSchema,T as GraphGenerationRequestSchema,Je as GraphyAiSdk,o as GraphyApiError,j as InvocationBudgetSchema,f as InvocationEffortSchema,Ne as JudgeParamsSchema,ze as JudgeResponseSchema,x as MAX_BUDGET_COST_USD,w as MAX_BUDGET_TOTAL_TOKENS,v as MAX_BUDGET_WALL_CLOCK_MS,ne as MAX_EXTRACT_ATTACHMENTS,ie as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,Q as MAX_EXTRACT_DOCUMENTS,Y as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,V as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,H as MAX_EXTRACT_IMAGES,X as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,J as MAX_EXTRACT_IMAGE_DECODED_BYTES,Z as MAX_EXTRACT_SPREADSHEETS,te as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,ee as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,z as MAX_SOURCE_TEXT_LENGTH,k as MAX_USER_PROMPT_LENGTH,$ as MetadataSchema,S as MutateNarrationReceiptSchema,N as PipelineAgentNameSchema,K as PipelineStageReasoningSchema,We as RubricScoresSchema,y as StorytellingEffortSchema,R as SuggestionSchema,je as buildImageAttachment,$e as buildPdfAttachment,Se as buildSpreadsheetAttachment,l as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,d as isPreviewEvent,c as isProgressEvent,u as isReasoningEvent};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.6.0",
4
+ "version": "1.6.1-beta.1780994924060",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "files": [
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "zod": "^4.3.6",
21
- "@graphysdk/core": "1.6.0"
21
+ "@graphysdk/core": "1.6.1-beta.1780994924060"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",