@graphysdk/agents-sdk 1.2.0-beta.1773662483280 → 1.2.0-beta.1773757233499

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 t=require("tslib"),e=require("zod");class r extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const i=t=>"progress"===t.type,o=t=>"complete"===t.type,s=t=>"error"===t.type;class n{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return i(t)}static isCompleteEvent(t){return o(t)}static isErrorEvent(t){return s(t)}stream(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(e,n,a,l){return t.__awaiter(this,void 0,void 0,function*(){var c,g,h,u,d;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const w=yield this.makeRequest(e,n,l),b=w.headers.get("content-type");if(null==b?void 0:b.includes("text/event-stream")){try{for(var y,f=!0,m=t.__asyncValues(this.parseSSE(w));!(c=(y=yield m.next()).done);f=!0){u=y.value,f=!1;const t=u;if(i(t)&&a&&a(t),o(t))return t.data;if(s(t)){const i=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${e} ${i}ms`,t.error),new r(t.error,{code:t.code,retryable:null!==(d=t.retryable)&&void 0!==d&&d})}}}catch(t){g={error:t}}finally{try{f||c||!(h=m.return)||(yield h.call(m))}finally{if(g)throw g.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${n}ms`),new r("Stream ended without completion")}return yield w.json()}catch(t){const i=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${i}ms`,t),t instanceof r)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${e} ${t}ms`)}})}ping(){return t.__awaiter(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t.__awaiter(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(e){return t.__asyncGenerator(this,arguments,function*(){if(!e.body)throw new r("Response body is null");const i=e.body.getReader(),o=new TextDecoder;let s="",n="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(i.read());if(e)break;s+=o.decode(r,{stream:!0});const l=s.split(/\r?\n/);s=l.pop()||"";for(const e of l)if(e.startsWith("event: "))n=e.slice(7).trim();else if(e.startsWith("data: "))a+=(a?"\n":"")+e.slice(6);else if(""===e.trim()&&a){try{const e=JSON.parse(a);let r;if("progress"===n){const t=e;r=Object.assign({type:"progress"},t)}else if("complete"===n)r={type:"complete",data:e};else{if("error"!==n){n="",a="";continue}{const t=e;r=Object.assign({type:"error"},t)}}if(yield yield t.__await(r),"complete"===n||"error"===n)return yield t.__await(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{i.releaseLock()}})}makeRequest(e,i,o){return t.__awaiter(this,arguments,void 0,function*(t,e,i,o=1,s="POST"){if(!t.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();i&&i.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:s,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:a.signal},"POST"===s&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new r(c,{status:l.status,code:a,retryable:n});if(n&&o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${o+1})`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}}const a=e.z.enum(["EN_GB","EN_US"]),l=e.z.custom(t=>null!=t&&"object"==typeof t),c=e.z.enum(["none","low","medium","high"]);e.z.object({callId:e.z.string(),locale:a.optional(),storytellingEffort:c.optional().default("low")});const g=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),h=e.z.object({dataPrepPrompt:e.z.string(),chartType:g,summary:e.z.string()}),u=e.z.object({title:e.z.string(),subtitle:e.z.string(),caption:e.z.string().nullable()}),d=e.z.object({config:l,suggestions:e.z.array(h),description:e.z.string().nullable()}),p=e.z.object({config:l,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()).optional()})}),y="/api/v0";exports.AiChartTypeEnum=g,exports.GenerateGraphNarrativeResponseSchema=u,exports.GenerateGraphResponseSchema=p,exports.GenerateGraphSuggestionsResponseSchema=d,exports.GraphyAiSdk=class{constructor(t){this.client=new n(t)}generateGraph(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:o}=e,s=t.__rest(e,["storytellingOptions"]),n=yield this.client.fetch(`${y}/generate`,s,r,i),a=p.parse(n);return this.stripStorytelling(a,o)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=e,o=t.__rest(e,["storytellingOptions"]),s=yield this.client.stream(`${y}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(s,i)})}generateNarrative(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/narrative`,e,r,i);return u.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/narrative`,e,r)})}generateSuggestions(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/suggestions`,e,r,i);return d.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/suggestions`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(e,r){return t.__asyncGenerator(this,arguments,function*(){var i,s,n,a;try{for(var l,c=!0,g=t.__asyncValues(e);!(i=(l=yield t.__await(g.next())).done);c=!0){a=l.value,c=!1;const e=a;if(o(e)){const i=this.stripStorytelling(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:i}))}else yield yield t.__await(e)}}catch(t){s={error:t}}finally{try{c||i||!(n=g.return)||(yield t.__await(n.call(g)))}finally{if(s)throw s.error}}})}},exports.GraphyApiError=r,exports.StorytellingEffortSchema=c,exports.SuggestionSchema=h,exports.isCompleteEvent=o,exports.isErrorEvent=s,exports.isGraphyApiError=t=>t instanceof r,exports.isProgressEvent=i;
1
+ "use strict";var t=require("tslib"),e=require("zod");class r extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const i=t=>"progress"===t.type,o=t=>"complete"===t.type,s=t=>"error"===t.type;class n{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return i(t)}static isCompleteEvent(t){return o(t)}static isErrorEvent(t){return s(t)}stream(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(e,n,a,l){return t.__awaiter(this,void 0,void 0,function*(){var c,g,h,u,d;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${e}`);try{const w=yield this.makeRequest(e,n,l),v=w.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var y,f=!0,m=t.__asyncValues(this.parseSSE(w));!(c=(y=yield m.next()).done);f=!0){u=y.value,f=!1;const t=u;if(i(t)&&a&&a(t),o(t))return t.data;if(s(t)){const i=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${e} ${i}ms`,t.error),new r(t.error,{code:t.code,retryable:null!==(d=t.retryable)&&void 0!==d&&d})}}}catch(t){g={error:t}}finally{try{f||c||!(h=m.return)||(yield h.call(m))}finally{if(g)throw g.error}}const n=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${e} ${n}ms`),new r("Stream ended without completion")}return yield w.json()}catch(t){const i=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${e} ${i}ms`,t),t instanceof r)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${e} ${t}ms`)}})}ping(){return t.__awaiter(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t.__awaiter(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(e){return t.__asyncGenerator(this,arguments,function*(){if(!e.body)throw new r("Response body is null");const i=e.body.getReader(),o=new TextDecoder;let s="",n="",a="";try{for(;;){const{done:e,value:r}=yield t.__await(i.read());if(e)break;s+=o.decode(r,{stream:!0});const l=s.split(/\r?\n/);s=l.pop()||"";for(const e of l)if(e.startsWith("event: "))n=e.slice(7).trim();else if(e.startsWith("data: "))a+=(a?"\n":"")+e.slice(6);else if(""===e.trim()&&a){try{const e=JSON.parse(a);let r;if("progress"===n){const t=e;r=Object.assign({type:"progress"},t)}else if("complete"===n)r={type:"complete",data:e};else{if("error"!==n){n="",a="";continue}{const t=e;r=Object.assign({type:"error"},t)}}if(yield yield t.__await(r),"complete"===n||"error"===n)return yield t.__await(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{i.releaseLock()}})}makeRequest(e,i,o){return t.__awaiter(this,arguments,void 0,function*(t,e,i,o=1,s="POST"){if(!t.startsWith("/"))throw new r("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new r("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();i&&i.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:s,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:a.signal},"POST"===s&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new r(c,{status:l.status,code:a,retryable:n});if(n&&o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${r}ms (attempt ${o+1})`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof r)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(o<this.retryConfig.attempts&&!(null==i?void 0:i.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${r}ms`),yield this.sleep(r),this.makeRequest(t,e,i,o+1,s)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new r("Network error",{retryable:!0})}finally{clearTimeout(l),i&&i.removeEventListener("abort",c)}})}}const a=e.z.enum(["EN_GB","EN_US"]),l=e.z.custom(t=>null!=t&&"object"==typeof t),c=e.z.enum(["none","low","medium","high"]);e.z.object({callId:e.z.string(),locale:a.optional(),storytellingEffort:c.optional().default("low")});const g=e.z.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),h=e.z.object({dataPrepPrompt:e.z.string(),chartType:g,summary:e.z.string()}),u=e.z.object({title:e.z.string(),subtitle:e.z.string(),caption:e.z.string().nullable()}),d=e.z.object({suggestions:e.z.array(h)}),p=e.z.object({config:l,response:e.z.object({message:e.z.string(),steps:e.z.array(e.z.string()).optional()})}),y="/api/v0";exports.AiChartTypeEnum=g,exports.GenerateGraphNarrativeResponseSchema=u,exports.GenerateGraphResponseSchema=p,exports.GenerateGraphSuggestionsResponseSchema=d,exports.GraphyAiSdk=class{constructor(t){this.client=new n(t)}generateGraph(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:o}=e,s=t.__rest(e,["storytellingOptions"]),n=yield this.client.fetch(`${y}/generate`,s,r,i),a=p.parse(n);return this.stripStorytelling(a,o)})}generateGraphStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:i}=e,o=t.__rest(e,["storytellingOptions"]),s=yield this.client.stream(`${y}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(s,i)})}generateNarrative(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/narrative`,e,r,i);return u.parse(t)})}generateNarrativeStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/narrative`,e,r)})}generateSuggestions(e,r,i){return t.__awaiter(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${y}/suggestions`,e,r,i);return d.parse(t)})}generateSuggestionsStream(e,r){return t.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${y}/suggestions`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(e,r){return t.__asyncGenerator(this,arguments,function*(){var i,s,n,a;try{for(var l,c=!0,g=t.__asyncValues(e);!(i=(l=yield t.__await(g.next())).done);c=!0){a=l.value,c=!1;const e=a;if(o(e)){const i=this.stripStorytelling(e.data,r);yield yield t.__await(Object.assign(Object.assign({},e),{data:i}))}else yield yield t.__await(e)}}catch(t){s={error:t}}finally{try{c||i||!(n=g.return)||(yield t.__await(n.call(g)))}finally{if(s)throw s.error}}})}},exports.GraphyApiError=r,exports.StorytellingEffortSchema=c,exports.SuggestionSchema=h,exports.isCompleteEvent=o,exports.isErrorEvent=s,exports.isGraphyApiError=t=>t instanceof r,exports.isProgressEvent=i;
package/dist/index.d.ts CHANGED
@@ -284,11 +284,11 @@ declare const GenerateGraphNarrativeResponseSchema: z.ZodObject<{
284
284
  }, z.core.$strip>;
285
285
  type GenerateGraphNarrativeResponse = z.infer<typeof GenerateGraphNarrativeResponseSchema>;
286
286
  type GenerateGraphSuggestionsParams = {
287
- data: string;
287
+ config: GraphConfig;
288
+ userPrompt: string;
288
289
  metadata?: Metadata;
289
290
  };
290
291
  declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
291
- config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
292
292
  suggestions: z.ZodArray<z.ZodObject<{
293
293
  dataPrepPrompt: z.ZodString;
294
294
  chartType: z.ZodEnum<{
@@ -312,7 +312,6 @@ declare const GenerateGraphSuggestionsResponseSchema: z.ZodObject<{
312
312
  }>;
313
313
  summary: z.ZodString;
314
314
  }, z.core.$strip>>;
315
- description: z.ZodNullable<z.ZodString>;
316
315
  }, z.core.$strip>;
317
316
  type GenerateGraphSuggestionsResponse = z.infer<typeof GenerateGraphSuggestionsResponseSchema>;
318
317
  interface StorytellingOptions {
@@ -421,39 +420,35 @@ declare class GraphyAiSdk {
421
420
  caption: string | null;
422
421
  }>>>;
423
422
  /**
424
- * Generates chart type and configuration suggestions from raw data.
423
+ * Generates chart type and prompt suggestions for a given chart configuration.
425
424
  *
426
- * @param data - Parameters including the raw data string.
425
+ * @param data - Parameters including the chart config and user prompt.
427
426
  * @param onProgress - Optional callback invoked with progress updates.
428
427
  * @param signal - Optional `AbortSignal` to cancel the request.
429
- * @returns Suggested chart configurations and descriptions.
428
+ * @returns Suggested chart types and data preparation prompts.
430
429
  * @throws {GraphyApiError} When the API returns an error or the network request fails.
431
430
  */
432
431
  generateSuggestions(data: GenerateGraphSuggestionsParams, onProgress?: ProgressHandler, signal?: AbortSignal): Promise<{
433
- config: _graphysdk_core_node.GraphConfig;
434
432
  suggestions: {
435
433
  dataPrepPrompt: string;
436
434
  chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "waterfall" | "table";
437
435
  summary: string;
438
436
  }[];
439
- description: string | null;
440
437
  }>;
441
438
  /**
442
439
  * Streams suggestion generation events via SSE.
443
440
  *
444
- * @param data - Parameters including the raw data string.
441
+ * @param data - Parameters including the chart config and user prompt.
445
442
  * @param signal - Optional `AbortSignal` to cancel the request.
446
443
  * @returns An async iterator yielding {@link SSEEvent} objects.
447
444
  * @throws {GraphyApiError} When the API returns an error or the network request fails.
448
445
  */
449
446
  generateSuggestionsStream(data: GenerateGraphSuggestionsParams, signal?: AbortSignal): Promise<AsyncIterableIterator<SSEEvent<{
450
- config: _graphysdk_core_node.GraphConfig;
451
447
  suggestions: {
452
448
  dataPrepPrompt: string;
453
449
  chartType: "line" | "bar" | "groupedBar" | "stackedBar" | "100StackedBar" | "column" | "groupedColumn" | "stackedColumn" | "100StackedColumn" | "combo" | "pie" | "donut" | "funnel" | "heatmap" | "scatter" | "waterfall" | "table";
454
450
  summary: string;
455
451
  }[];
456
- description: string | null;
457
452
  }>>>;
458
453
  private stripStorytelling;
459
454
  private wrapStreamWithStorytellingStripping;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as i,__rest as o}from"tslib";import{z as n}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,l=t=>"progress"===t.type,c=t=>"complete"===t.type,g=t=>"error"===t.type;class h{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return l(t)}static isCompleteEvent(t){return c(t)}static isErrorEvent(t){return g(t)}stream(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,i);return this.parseSSE(t)})}fetch(r,i,o,n){return t(this,void 0,void 0,function*(){var t,a,h,d,u;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,i,n),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var y,f=!0,m=e(this.parseSSE(b));!(t=(y=yield m.next()).done);f=!0){d=y.value,f=!1;const t=d;if(l(t)&&o&&o(t),c(t))return t.data;if(g(t)){const e=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error,{code:t.code,retryable:null!==(u=t.retryable)&&void 0!==u&&u})}}}catch(t){a={error:t}}finally{try{f||t||!(h=m.return)||(yield h.call(m))}finally{if(a)throw a.error}}const i=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${i}ms`),new s("Stream ended without completion")}return yield b.json()}catch(t){const e=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${r} ${t}ms`)}})}ping(){return t(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(t){return r(this,arguments,function*(){if(!t.body)throw new s("Response body is null");const e=t.body.getReader(),r=new TextDecoder;let o="",n="",a="";try{for(;;){const{done:t,value:s}=yield i(e.read());if(t)break;o+=r.decode(s,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let e;if("progress"===n){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===n)e={type:"complete",data:t};else{if("error"!==n){n="",a="";continue}{const r=t;e=Object.assign({type:"error"},r)}}if(yield yield i(e),"complete"===n||"error"===n)return yield i(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,i){return t(this,arguments,void 0,function*(t,e,r,i=1,o="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();r&&r.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:o,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:a.signal},"POST"===o&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(c,{status:l.status,code:a,retryable:n});if(n&&i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${n}ms (attempt ${i+1})`),yield this.sleep(n),this.makeRequest(t,e,r,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof s)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(i<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${n}ms`),yield this.sleep(n),this.makeRequest(t,e,r,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new s("Network error",{retryable:!0})}finally{clearTimeout(l),r&&r.removeEventListener("abort",c)}})}}const d=n.enum(["EN_GB","EN_US"]),u=n.custom(t=>null!=t&&"object"==typeof t),p=n.enum(["none","low","medium","high"]);n.object({callId:n.string(),locale:d.optional(),storytellingEffort:p.optional().default("low")});const y=n.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),f=n.object({dataPrepPrompt:n.string(),chartType:y,summary:n.string()}),m=n.object({title:n.string(),subtitle:n.string(),caption:n.string().nullable()}),b=n.object({config:u,suggestions:n.array(f),description:n.string().nullable()}),v=n.object({config:u,response:n.object({message:n.string(),steps:n.array(n.string()).optional()})}),w="/api/v0";class ${constructor(t){this.client=new h(t)}generateGraph(e,r,i){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,n=o(e,["storytellingOptions"]),s=yield this.client.fetch(`${w}/generate`,n,r,i),a=v.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,i=o(e,["storytellingOptions"]),n=yield this.client.stream(`${w}/generate`,i,r);return this.wrapStreamWithStorytellingStripping(n,t)})}generateNarrative(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${w}/narrative`,e,r,i);return m.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${w}/narrative`,e,r)})}generateSuggestions(e,r,i){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${w}/suggestions`,e,r,i);return b.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${w}/suggestions`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(t,o){return r(this,arguments,function*(){var r,n,s,a;try{for(var l,g=!0,h=e(t);!(r=(l=yield i(h.next())).done);g=!0){a=l.value,g=!1;const t=a;if(c(t)){const e=this.stripStorytelling(t.data,o);yield yield i(Object.assign(Object.assign({},t),{data:e}))}else yield yield i(t)}}catch(t){n={error:t}}finally{try{g||r||!(s=h.return)||(yield i(s.call(h)))}finally{if(n)throw n.error}}})}}export{y as AiChartTypeEnum,m as GenerateGraphNarrativeResponseSchema,v as GenerateGraphResponseSchema,b as GenerateGraphSuggestionsResponseSchema,$ as GraphyAiSdk,s as GraphyApiError,p as StorytellingEffortSchema,f as SuggestionSchema,c as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,l as isProgressEvent};
1
+ import{__awaiter as t,__asyncValues as e,__asyncGenerator as r,__await as o,__rest as i}from"tslib";import{z as n}from"zod";class s extends Error{constructor(t,e){var r;super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==e?void 0:e.status,this.code=null==e?void 0:e.code,this.retryable=null!==(r=null==e?void 0:e.retryable)&&void 0!==r&&r}}const a=t=>t instanceof s,l=t=>"progress"===t.type,c=t=>"complete"===t.type,g=t=>"error"===t.type;class h{constructor(t){if(this.tag="[GRAPHY]",!t.apiKey||0===t.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const e=new URL(t.baseUrl);if(!["http:","https:"].includes(e.protocol))throw new Error(`Invalid baseUrl protocol: ${e.protocol}. Only http(s) is allowed.`);this.apiKey=t.apiKey,this.baseUrl=e.origin+e.pathname.replace(/\/$/,""),this.timeout=t.timeout||6e4,this.retryConfig=t.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=t.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(t){return l(t)}static isCompleteEvent(t){return c(t)}static isErrorEvent(t){return g(t)}stream(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.makeRequest(e,r,o);return this.parseSSE(t)})}fetch(r,o,i,n){return t(this,void 0,void 0,function*(){var t,a,h,d,u;const p=Date.now();this.logger.debug(`${this.tag} Fetch: ${r}`);try{const b=yield this.makeRequest(r,o,n),v=b.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var y,f=!0,m=e(this.parseSSE(b));!(t=(y=yield m.next()).done);f=!0){d=y.value,f=!1;const t=d;if(l(t)&&i&&i(t),c(t))return t.data;if(g(t)){const e=Date.now()-p;throw this.logger.error(`${this.tag} Server error: ${r} ${e}ms`,t.error),new s(t.error,{code:t.code,retryable:null!==(u=t.retryable)&&void 0!==u&&u})}}}catch(t){a={error:t}}finally{try{f||t||!(h=m.return)||(yield h.call(m))}finally{if(a)throw a.error}}const o=Date.now()-p;throw this.logger.error(`${this.tag} Stream incomplete: ${r} ${o}ms`),new s("Stream ended without completion")}return yield b.json()}catch(t){const e=Date.now()-p;if(this.logger.error(`${this.tag} Fetch failed: ${r} ${e}ms`,t),t instanceof s)throw t;throw t}finally{const t=Date.now()-p;this.logger.debug(`${this.tag} Fetch completed: ${r} ${t}ms`)}})}ping(){return t(this,void 0,void 0,function*(){const t=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-t}}catch(e){return{ok:!1,latency:Date.now()-t}}})}sleep(e){return t(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}parseSSE(t){return r(this,arguments,function*(){if(!t.body)throw new s("Response body is null");const e=t.body.getReader(),r=new TextDecoder;let i="",n="",a="";try{for(;;){const{done:t,value:s}=yield o(e.read());if(t)break;i+=r.decode(s,{stream:!0});const l=i.split(/\r?\n/);i=l.pop()||"";for(const t of l)if(t.startsWith("event: "))n=t.slice(7).trim();else if(t.startsWith("data: "))a+=(a?"\n":"")+t.slice(6);else if(""===t.trim()&&a){try{const t=JSON.parse(a);let e;if("progress"===n){const r=t;e=Object.assign({type:"progress"},r)}else if("complete"===n)e={type:"complete",data:t};else{if("error"!==n){n="",a="";continue}{const r=t;e=Object.assign({type:"error"},r)}}if(yield yield o(e),"complete"===n||"error"===n)return yield o(void 0)}catch(t){this.logger.warn("Invalid SSE data format",a)}n="",a=""}}}finally{e.releaseLock()}})}makeRequest(e,r,o){return t(this,arguments,void 0,function*(t,e,r,o=1,i="POST"){if(!t.startsWith("/"))throw new s("Invalid endpoint: must start with /");const n=new URL(t,this.baseUrl);if(n.origin!==new URL(this.baseUrl).origin)throw new s("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${o}/${this.retryConfig.attempts}: ${n}`);const a=new AbortController,l=setTimeout(()=>a.abort(),this.timeout),c=()=>a.abort();r&&r.addEventListener("abort",c);try{const l=yield fetch(n,Object.assign({method:i,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:a.signal},"POST"===i&&{body:JSON.stringify(e)}));if(!l.ok){const n=l.status>=500||429===l.status;let a,c=`HTTP ${l.status}`;try{const t=yield l.json();if("object"==typeof t&&null!==t){const e=t;"string"==typeof e.message?c=e.message:"string"==typeof e.error&&(c=e.error),"string"==typeof e.code&&(a=e.code)}}catch(t){}const g=new s(c,{status:l.status,code:a,retryable:n});if(n&&o<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Retrying ${t} in ${n}ms (attempt ${o+1})`),yield this.sleep(n),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Request failed: ${t} (${l.status}) - ${c}`),g}return this.logger.debug(`${this.tag} Connected: ${t}`),l}catch(n){if(n instanceof s)throw n;if(n instanceof Error&&"AbortError"===n.name)throw this.logger.debug(`${this.tag} Aborted: ${t}`),n;if(o<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,o-1);return this.logger.warn(`${this.tag} Network error, retrying ${t} in ${n}ms`),yield this.sleep(n),this.makeRequest(t,e,r,o+1,i)}throw this.logger.error(`${this.tag} Network error: ${t}`,n),new s("Network error",{retryable:!0})}finally{clearTimeout(l),r&&r.removeEventListener("abort",c)}})}}const d=n.enum(["EN_GB","EN_US"]),u=n.custom(t=>null!=t&&"object"==typeof t),p=n.enum(["none","low","medium","high"]);n.object({callId:n.string(),locale:d.optional(),storytellingEffort:p.optional().default("low")});const y=n.enum(["line","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","waterfall","table"]),f=n.object({dataPrepPrompt:n.string(),chartType:y,summary:n.string()}),m=n.object({title:n.string(),subtitle:n.string(),caption:n.string().nullable()}),b=n.object({suggestions:n.array(f)}),v=n.object({config:u,response:n.object({message:n.string(),steps:n.array(n.string()).optional()})}),w="/api/v0";class ${constructor(t){this.client=new h(t)}generateGraph(e,r,o){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,n=i(e,["storytellingOptions"]),s=yield this.client.fetch(`${w}/generate`,n,r,o),a=v.parse(s);return this.stripStorytelling(a,t)})}generateGraphStream(e,r){return t(this,void 0,void 0,function*(){const{storytellingOptions:t}=e,o=i(e,["storytellingOptions"]),n=yield this.client.stream(`${w}/generate`,o,r);return this.wrapStreamWithStorytellingStripping(n,t)})}generateNarrative(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${w}/narrative`,e,r,o);return m.parse(t)})}generateNarrativeStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${w}/narrative`,e,r)})}generateSuggestions(e,r,o){return t(this,void 0,void 0,function*(){const t=yield this.client.fetch(`${w}/suggestions`,e,r,o);return b.parse(t)})}generateSuggestionsStream(e,r){return t(this,void 0,void 0,function*(){return this.client.stream(`${w}/suggestions`,e,r)})}stripStorytelling(t,e){return e&&t.config.content?Object.assign(Object.assign({},t),{config:Object.assign(Object.assign({},t.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},t.config.content),e.excludeTitle&&{title:void 0}),e.excludeSubtitle&&{subtitle:void 0}),e.excludeCaption&&{caption:void 0})})}):t}wrapStreamWithStorytellingStripping(t,i){return r(this,arguments,function*(){var r,n,s,a;try{for(var l,g=!0,h=e(t);!(r=(l=yield o(h.next())).done);g=!0){a=l.value,g=!1;const t=a;if(c(t)){const e=this.stripStorytelling(t.data,i);yield yield o(Object.assign(Object.assign({},t),{data:e}))}else yield yield o(t)}}catch(t){n={error:t}}finally{try{g||r||!(s=h.return)||(yield o(s.call(h)))}finally{if(n)throw n.error}}})}}export{y as AiChartTypeEnum,m as GenerateGraphNarrativeResponseSchema,v as GenerateGraphResponseSchema,b as GenerateGraphSuggestionsResponseSchema,$ as GraphyAiSdk,s as GraphyApiError,p as StorytellingEffortSchema,f as SuggestionSchema,c as isCompleteEvent,g as isErrorEvent,a as isGraphyApiError,l as isProgressEvent};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@graphysdk/agents-sdk",
3
3
  "author": "Graphy",
4
- "version": "1.2.0-beta.1773662483280",
4
+ "version": "1.2.0-beta.1773757233499",
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.2.0-beta.1773662483280"
21
+ "@graphysdk/core": "1.2.0-beta.1773757233499"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@rollup/plugin-commonjs": "^28.0.6",
@@ -32,7 +32,7 @@
32
32
  "rollup-plugin-dts": "^6.2.3",
33
33
  "rollup-plugin-node-externals": "^8.1.1",
34
34
  "tslib": "^2.8.1",
35
- "vitest": "^4.0.18",
35
+ "vitest": "^4.1.0",
36
36
  "@graphytools/eslint-config": "0.0.1",
37
37
  "@graphytools/typescript-config": "0.0.1",
38
38
  "@graphytools/vitest-config": "1.0.0"