@stackone/connect-sdk 1.23.1 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.mjs CHANGED
@@ -1 +1 @@
1
- import{StepFunctionsFactory as e,StepFunctionName as t,minifyCursor as o,AUTHENTICATION_SCHEMA as r,expandCursor as n}from"@stackone/core";import{safeEvaluate as s,safeEvaluateRecord as i}from"@stackone/expressions";import{isMissing as a,isObject as c,notMissing as p,isString as u}from"@stackone/utils";import{HttpClientManager as d,isSuccessStatusCode as l}from"@stackone/transport";import{match as y}from"path-to-regexp";import{parse as g}from"yaml";import{z as m}from"zod";const b=async({block:o,stepFunctionName:r,params:n,buildStepFunction:s=e.build})=>{const i=s({functionName:r}).fn,a=await i({block:o,params:n}),c=r===t.MAP_FIELDS?{[t.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...c}}},h=(e,t,r,n)=>{const s=a(e)?void 0:e.data;if(!c(e)||a(s)||(s?.length??0)<=t)return{result:e,next:null};const i=Object.keys(r).length+1,p=n?.remote?.[i].pageNumber??1,u=(p-1)*t,d=u+t,l=s.slice(u,d),y=s.length>d,g=a(n)?{remote:{[i]:{pageNumber:p+1}},version:2,timestamp:Date.now()}:{...n,remote:{...n.remote,[i]:{pageNumber:p+1}}};return{result:{...e,data:l},next:y?o(g):null}},f=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=h})=>await _({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),_=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=h})=>{const n=t.operation?.steps||{};let i={...t};const a=Object.keys(n);let u=!1,d=null;for(const e of a){const t=n[e],r=t.stepFunction,a=o({functionName:r.functionName,version:r.version,validateSchemas:!0}).fn;if(t.condition&&!s(t.condition,i)){i=v({block:i,stepId:e,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(u){i=v({block:i,stepId:e,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const c=await a({block:i,params:r.params});if(!1===c.successful){i=v({block:i,stepId:e,successful:!1,functionOutput:c});(t.ignoreError??!1)||(u=!0,d??=c.output?.statusCode??500)}else i=v({block:c.block,stepId:e,functionOutput:c})}const l=t.operation?.result?k(t.operation.result,i):void 0,y=t.operation?.cursor.enabled?r(l,t.operation.cursor.pageSize,n,i.nextCursor):void 0,g=!u,m=g?t.operation?.responses.success.statusCode??200:d??500,b=p(y)&&c(y.result)?{next:y.next,...y.result}:l;return{...i,outputs:b,response:{successful:g,statusCode:m,message:g?void 0:t.operation?.responses?.errors?.[m]?.description??"Error while processing the request"}}},k=(e,t)=>c(e)?i(e,t):s(e,t),v=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),C=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>d.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),w=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),I=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=E(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},S=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},E=(e,t,o)=>{const r=S(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=y(S(o))(S(r));if(!1!==n)return{path:e,params:n.params}}},F=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},j={key:m.string(),label:m.string(),required:m.boolean().optional().default(!1),secret:m.boolean().optional().default(!1),readOnly:m.boolean().optional().default(!1),placeholder:m.string().optional(),description:m.string().optional(),tooltip:m.string().optional()},O=m.discriminatedUnion("type",[m.object({...j,type:m.enum(["text","password"])}),m.object({...j,type:m.literal("select"),options:m.object({value:m.string(),label:m.string()}).array()})]),T=m.object({operationId:m.string(),categories:m.string().array(),operationType:m.enum(["list","get","create","update","delete","custom","unknown"]),schema:m.string().optional(),entrypointUrl:m.string().optional(),entrypointHttpMethod:m.string().optional(),description:m.string(),responses:m.object({statusCode:m.number(),description:m.string()}).array().optional(),inputs:m.object({name:m.string(),type:m.string(),required:m.boolean(),description:m.string(),in:m.string()}).array().optional(),cursor:m.object({enabled:m.boolean(),pageSize:m.number()}).optional(),fieldConfigs:m.object({targetFieldKey:m.string(),expression:m.string(),type:m.enum(["string","number","boolean","datetime_string","enum"]),isUnified:m.boolean(),enumMapper:m.object({matcher:m.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(m.object({matchExpression:m.string(),value:m.string()}).array())}).optional()}).array().optional(),steps:m.object({stepId:m.string(),description:m.string(),stepFunction:m.object({functionName:m.string(),version:m.string().optional(),parameters:m.record(m.string(),m.unknown())}),condition:m.string().optional(),ignoreError:m.boolean().optional()}).array(),result:m.string().or(m.record(m.string(),m.unknown())).optional()}),x=m.object({StackOne:m.string(),info:m.object({title:m.string(),version:m.string(),key:m.string(),description:m.string().optional()}),baseUrl:m.string(),authentication:m.record(m.string(),m.object({type:m.string(),label:m.string(),authorization:r,environments:m.object({key:m.string(),name:m.string()}).array(),support:m.object({link:m.string(),description:m.string().optional()}),configFields:O.array().optional(),setupFields:O.array().optional(),testOperationsIds:m.string().array().optional()})).array().optional(),operations:T.array().optional()});function N(e){try{const t=g(e),o=x.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=q(o),s={baseUrl:o.baseUrl,authentication:R(n)},i=$(o,s);return r.operations=i,r.authentication=n,p(i)&&(r.categories=U(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const R=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=R(a)}else t[o]=r;return t},U=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},q=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},$=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const r=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),n=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),s=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),i=(e=>{const t={success:F(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(l(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o);return e[r??n]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??s,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:i,cursor:z(o),inputs:o.inputs,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},M=(e,t)=>{if(!e.inputs)return{};const o=K(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},P=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=m.string();break;case"number":o=m.number();break;case"boolean":o=m.boolean();break;default:o=m.any()}t[e.name]=e.required?o:o.optional()})),m.object(t)},K=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return m.object({path:P(t).optional(),query:P(o).optional(),body:P(r).optional(),headers:P(n).optional()})},z=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class A extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,A)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class D extends A{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class H extends A{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class L extends A{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class V extends A{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const G=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:c,logger:p,parseConnector:d=N,getOperationFromUrlFn:l=I,parseOperationInputsFn:y=M,createBlockContextFn:g=w,createBlockFn:m=C,runStepOperationFn:b=f})=>{const h=e.authConfigKey,_=e.environment??"production",k=e.secureId,v=e.projectSecureId,S=e.credentials,E=g({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:h,environment:_,accountSecureId:k,projectSecureId:v});let F;try{F=u(t)?d(t):t}catch{throw new D(E,"Error while parsing connector")}const j=l(F,r,n);if(a(j))throw new H(E,"No matching operation found");E.operationType=j.operation.operationType,E.schema=j.operation.schema?.key;const O=W(s,E);let T;try{T=y(j.operation,{query:s,body:i,headers:c,path:j.params})}catch{throw new L(E,"Error while parsing operation inputs")}const x=await m({inputs:T,context:E,operation:j.operation,credentials:S,nextCursor:O,logger:p});return await b({block:x})},W=(e,t)=>{const o=e?.next,r=p(o)&&"list"===t.operationType?n(o):void 0;if(null===r)throw new V(t,"Invalid cursor.");return r};export{A as ConnectSDKError,C as createBlock,b as executeStepFunction,I as getOperationFromUrl,M as parseOperationInputs,N as parseYamlConnector,G as runConnectorOperation,f as runStepOperation};
1
+ import{StepFunctionsFactory as e,StepFunctionName as t,isCursorEmpty as o,minifyCursor as r,updateCursor as n,AUTHENTICATION_SCHEMA as s,expandCursor as i}from"@stackone/core";import{safeEvaluate as a,safeEvaluateRecord as c}from"@stackone/expressions";import{notMissing as p,isNumber as u,isMissing as d,isObject as l,isString as y}from"@stackone/utils";import{HttpClientManager as g,isSuccessStatusCode as m}from"@stackone/transport";import{match as b}from"path-to-regexp";import{parse as h}from"yaml";import{z as f}from"zod";const _=async({block:o,stepFunctionName:r,params:n,buildStepFunction:s=e.build})=>{const i=s({functionName:r}).fn,a=await i({block:o,params:n}),c=r===t.MAP_FIELDS?{[t.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...c}}},k=(e,t,s,i)=>{const a=d(e)?void 0:e.data,c=Object.keys(s).length+1,u=o({cursor:i,ignoreStepIndex:c});if(!l(e)||d(a)||(a?.length??0)<=t)return{result:e,next:p(i)&&!u?r(i):null};const y=i?.remote?.[c]?.pageNumber??1,g=(y-1)*t,m=g+t,b=a.slice(g,m),h=a.length>m||!u,f=n({cursor:i,stepIndex:c,pageNumber:y+1});return{result:{...e,data:b},next:h?r(f):null}},v=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>await C({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),C=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=k})=>{const s=t.operation?.steps||{};let i={...t};const c=Object.keys(s),d=((e,t)=>{const o=Number(e.inputs?.page_size);return p(e.inputs?.page_size)&&u(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let y=!1,g=null;for(const[e,t]of c.entries()){const r=s[t],c=r.stepFunction,p=o({functionName:c.functionName,version:c.version,validateSchemas:!0}).fn;if(r.condition&&!a(r.condition,i)){i=w({block:i,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(y){i=w({block:i,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const u=i.operation?.cursor.enabled?{...c.params,cursor:{token:i.nextCursor?.remote?.[e]?.providerPageCursor,position:i.nextCursor?.remote?.[e]?.position}}:c.params,d=await p({block:i,params:u});if(!1===d.successful){i=w({block:i,stepId:t,successful:!1,functionOutput:d});(r.ignoreError??!1)||(y=!0,g??=d.output?.statusCode??500)}else{const o=i.operation?.cursor.enabled?n({cursor:i.nextCursor,stepIndex:e,providerPageCursor:d.output?.next,position:d.output?.position}):void 0;i=w({block:{...d.block,nextCursor:o},stepId:t,functionOutput:d})}}const m=t.operation?.result?I(t.operation.result,i):void 0,b=t.operation?.cursor.enabled?r(m,d,s,i.nextCursor):void 0,h=!y,f=h?t.operation?.responses.success.statusCode??200:g??500,_=p(b)&&l(b.result)?{next:b.next,...b.result}:m;return{...i,outputs:_,response:{successful:h,statusCode:f,message:h?void 0:t.operation?.responses?.errors?.[f]?.description??"Error while processing the request"}}},I=(e,t)=>l(e)?c(e,t):a(e,t),w=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),S=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>g.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),x=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),E=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=j(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},F=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},j=(e,t,o)=>{const r=F(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=b(F(o))(F(r));if(!1!==n)return{path:e,params:n.params}}},O=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},T={key:f.string(),label:f.string(),required:f.boolean().optional().default(!1),secret:f.boolean().optional().default(!1),readOnly:f.boolean().optional().default(!1),placeholder:f.string().optional(),description:f.string().optional(),tooltip:f.string().optional()},N=f.discriminatedUnion("type",[f.object({...T,type:f.enum(["text","password"])}),f.object({...T,type:f.literal("select"),options:f.object({value:f.string(),label:f.string()}).array()})]),R=f.object({operationId:f.string(),categories:f.string().array(),operationType:f.enum(["list","get","create","update","delete","custom","unknown"]),schema:f.string().optional(),entrypointUrl:f.string().optional(),entrypointHttpMethod:f.string().optional(),description:f.string(),responses:f.object({statusCode:f.number(),description:f.string()}).array().optional(),inputs:f.object({name:f.string(),type:f.string(),required:f.boolean(),description:f.string(),in:f.string()}).array().optional(),cursor:f.object({enabled:f.boolean(),pageSize:f.number()}).optional(),fieldConfigs:f.object({targetFieldKey:f.string(),expression:f.string(),type:f.enum(["string","number","boolean","datetime_string","enum"]),isUnified:f.boolean(),enumMapper:f.object({matcher:f.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(f.object({matchExpression:f.string(),value:f.string()}).array())}).optional()}).array().optional(),steps:f.object({stepId:f.string(),description:f.string(),stepFunction:f.object({functionName:f.string(),version:f.string().optional(),parameters:f.record(f.string(),f.unknown())}),condition:f.string().optional(),ignoreError:f.boolean().optional()}).array(),result:f.string().or(f.record(f.string(),f.unknown())).optional()}),U=f.object({StackOne:f.string(),info:f.object({title:f.string(),version:f.string(),key:f.string(),description:f.string().optional()}),baseUrl:f.string(),authentication:f.record(f.string(),f.object({type:f.string(),label:f.string(),authorization:s,environments:f.object({key:f.string(),name:f.string()}).array(),support:f.object({link:f.string(),description:f.string().optional()}),configFields:N.array().optional(),setupFields:N.array().optional(),testOperationsIds:f.string().array().optional()})).array().optional(),operations:R.array().optional()});function q(e){try{const t=h(e),o=U.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=$(o),s={baseUrl:o.baseUrl,authentication:P(n)},i=M(o,s);return r.operations=i,r.authentication=n,p(i)&&(r.categories=z(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const P=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=P(a)}else t[o]=r;return t},z=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},$=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},M=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const r=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),n=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),s=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),i=(e=>{const t={success:O(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(m(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),a=L(o),c=o.inputs||[];return a.enabled&&c?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[r??n]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??s,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:i,cursor:a,inputs:c,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},K=(e,t)=>{if(!e.inputs)return{};const o=H(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},A=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=f.string();break;case"number":o=f.number();break;case"boolean":o=f.boolean();break;default:o=f.any()}t[e.name]=e.required?o:o.optional()})),f.object(t)},H=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return f.object({path:A(t).optional(),query:A(o).optional(),body:A(r).optional(),headers:A(n).optional()})},L=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class V extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,V)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class D extends V{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class G extends V{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class W extends V{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class B extends V{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const Y=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=q,getOperationFromUrlFn:u=E,parseOperationInputsFn:l=K,createBlockContextFn:g=x,createBlockFn:m=S,runStepOperationFn:b=v})=>{const h=e.authConfigKey,f=e.environment??"production",_=e.secureId,k=e.projectSecureId,C=e.credentials,I=g({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:h,environment:f,accountSecureId:_,projectSecureId:k});let w;try{w=y(t)?p(t):t}catch{throw new D(I,"Error while parsing connector")}const F=u(w,r,n);if(d(F))throw new G(I,"No matching operation found");I.operationType=F.operation.operationType,I.schema=F.operation.schema?.key;const j=J(s,I);let O;try{O=l(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new W(I,"Error while parsing operation inputs")}const T=await m({inputs:O,context:I,operation:F.operation,credentials:C,nextCursor:j,logger:c});return await b({block:T})},J=(e,t)=>{const o=e?.next,r=p(o)&&"list"===t.operationType?i(o):void 0;if(null===r)throw new B(t,"Invalid cursor.");return r};export{V as ConnectSDKError,S as createBlock,_ as executeStepFunction,E as getOperationFromUrl,K as parseOperationInputs,q as parseYamlConnector,Y as runConnectorOperation,v as runStepOperation};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("@stackone/core"),t=require("@stackone/expressions"),o=require("@stackone/utils"),r=require("@stackone/transport"),n=require("path-to-regexp"),s=require("yaml"),i=require("zod");const a=(t,r,n,s)=>{const i=o.isMissing(t)?void 0:t.data;if(!o.isObject(t)||o.isMissing(i)||(i?.length??0)<=r)return{result:t,next:null};const a=Object.keys(n).length+1,c=s?.remote?.[a].pageNumber??1,p=(c-1)*r,u=p+r,d=i.slice(p,u),l=i.length>u,y=o.isMissing(s)?{remote:{[a]:{pageNumber:c+1}},version:2,timestamp:Date.now()}:{...s,remote:{...s.remote,[a]:{pageNumber:c+1}}};return{result:{...t,data:d},next:l?e.minifyCursor(y):null}},c=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=a})=>await p({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),p=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=a})=>{const i=r.operation?.steps||{};let c={...r};const p=Object.keys(i);let l=!1,y=null;for(const e of p){const o=i[e],r=o.stepFunction,s=n({functionName:r.functionName,version:r.version,validateSchemas:!0}).fn;if(o.condition&&!t.safeEvaluate(o.condition,c)){c=d({block:c,stepId:e,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(l){c=d({block:c,stepId:e,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const a=await s({block:c,params:r.params});if(!1===a.successful){c=d({block:c,stepId:e,successful:!1,functionOutput:a});(o.ignoreError??!1)||(l=!0,y??=a.output?.statusCode??500)}else c=d({block:a.block,stepId:e,functionOutput:a})}const g=r.operation?.result?u(r.operation.result,c):void 0,b=r.operation?.cursor.enabled?s(g,r.operation.cursor.pageSize,i,c.nextCursor):void 0,m=!l,h=m?r.operation?.responses.success.statusCode??200:y??500,z=o.notMissing(b)&&o.isObject(b.result)?{next:b.next,...b.result}:g;return{...c,outputs:z,response:{successful:m,statusCode:h,message:m?void 0:r.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},u=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),d=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),l=async({inputs:e,context:t,operation:o,credentials:n,nextCursor:s,logger:i,getHttpClient:a=async()=>r.HttpClientManager.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:n,nextCursor:s,httpClient:await a(),logger:i}),y=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),g=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=m(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},b=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},m=(e,t,o)=>{const r=b(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(b(o))(b(r));if(!1!==s)return{path:e,params:s.params}}},h=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},z={key:i.z.string(),label:i.z.string(),required:i.z.boolean().optional().default(!1),secret:i.z.boolean().optional().default(!1),readOnly:i.z.boolean().optional().default(!1),placeholder:i.z.string().optional(),description:i.z.string().optional(),tooltip:i.z.string().optional()},f=i.z.discriminatedUnion("type",[i.z.object({...z,type:i.z.enum(["text","password"])}),i.z.object({...z,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),_=i.z.object({operationId:i.z.string(),categories:i.z.string().array(),operationType:i.z.enum(["list","get","create","update","delete","custom","unknown"]),schema:i.z.string().optional(),entrypointUrl:i.z.string().optional(),entrypointHttpMethod:i.z.string().optional(),description:i.z.string(),responses:i.z.object({statusCode:i.z.number(),description:i.z.string()}).array().optional(),inputs:i.z.object({name:i.z.string(),type:i.z.string(),required:i.z.boolean(),description:i.z.string(),in:i.z.string()}).array().optional(),cursor:i.z.object({enabled:i.z.boolean(),pageSize:i.z.number()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),isUnified:i.z.boolean(),enumMapper:i.z.object({matcher:i.z.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(i.z.object({matchExpression:i.z.string(),value:i.z.string()}).array())}).optional()}).array().optional(),steps:i.z.object({stepId:i.z.string(),description:i.z.string(),stepFunction:i.z.object({functionName:i.z.string(),version:i.z.string().optional(),parameters:i.z.record(i.z.string(),i.z.unknown())}),condition:i.z.string().optional(),ignoreError:i.z.boolean().optional()}).array(),result:i.z.string().or(i.z.record(i.z.string(),i.z.unknown())).optional()}),k=i.z.object({StackOne:i.z.string(),info:i.z.object({title:i.z.string(),version:i.z.string(),key:i.z.string(),description:i.z.string().optional()}),baseUrl:i.z.string(),authentication:i.z.record(i.z.string(),i.z.object({type:i.z.string(),label:i.z.string(),authorization:e.AUTHENTICATION_SCHEMA,environments:i.z.object({key:i.z.string(),name:i.z.string()}).array(),support:i.z.object({link:i.z.string(),description:i.z.string().optional()}),configFields:f.array().optional(),setupFields:f.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:_.array().optional()});function C(e){try{const t=s.parse(e),r=k.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=w(r),a={baseUrl:r.baseUrl,authentication:v(i)},c=F(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=S(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const v=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=v(a)}else t[o]=r;return t},S=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},w=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},F=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const n=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),s=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),i=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),a=(e=>{const t={success:h(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(r.isSuccessStatusCode(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o);return e[n??s]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??i,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:a,cursor:x(o),inputs:o.inputs,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},I=(e,t)=>{if(!e.inputs)return{};const o=O(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},E=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=i.z.string();break;case"number":o=i.z.number();break;case"boolean":o=i.z.boolean();break;default:o=i.z.any()}t[e.name]=e.required?o:o.optional()})),i.z.object(t)},O=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return i.z.object({path:E(t).optional(),query:E(o).optional(),body:E(r).optional(),headers:E(n).optional()})},x=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class j extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,j)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class T extends j{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class N extends j{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class R extends j{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class M extends j{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const q=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new M(r,"Invalid cursor.");return s};exports.ConnectSDKError=j,exports.createBlock=l,exports.executeStepFunction=async({block:t,stepFunctionName:o,params:r,buildStepFunction:n=e.StepFunctionsFactory.build})=>{const s=n({functionName:o}).fn,i=await s({block:t,params:r}),a=o===e.StepFunctionName.MAP_FIELDS?{[e.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:i.block.result},errors:i.errors,successful:i.successful}}:{};return{...i.block,steps:{...i?.block?.steps??{},...a}}},exports.getOperationFromUrl=g,exports.parseOperationInputs=I,exports.parseYamlConnector=C,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:p,logger:u,parseConnector:d=C,getOperationFromUrlFn:b=g,parseOperationInputsFn:m=I,createBlockContextFn:h=y,createBlockFn:z=l,runStepOperationFn:f=c})=>{const _=e.authConfigKey,k=e.environment??"production",v=e.secureId,S=e.projectSecureId,w=e.credentials,F=h({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:k,accountSecureId:v,projectSecureId:S});let E;try{E=o.isString(t)?d(t):t}catch{throw new T(F,"Error while parsing connector")}const O=b(E,n,s);if(o.isMissing(O))throw new N(F,"No matching operation found");F.operationType=O.operation.operationType,F.schema=O.operation.schema?.key;const x=q(i,F);let j;try{j=m(O.operation,{query:i,body:a,headers:p,path:O.params})}catch{throw new R(F,"Error while parsing operation inputs")}const M=await z({inputs:j,context:F,operation:O.operation,credentials:w,nextCursor:x,logger:u});return await f({block:M})},exports.runStepOperation=c;
1
+ "use strict";var e=require("@stackone/core"),t=require("@stackone/expressions"),o=require("@stackone/utils"),r=require("@stackone/transport"),n=require("path-to-regexp"),s=require("yaml"),i=require("zod");const a=(t,r,n,s)=>{const i=o.isMissing(t)?void 0:t.data,a=Object.keys(n).length+1,c=e.isCursorEmpty({cursor:s,ignoreStepIndex:a});if(!o.isObject(t)||o.isMissing(i)||(i?.length??0)<=r)return{result:t,next:o.notMissing(s)&&!c?e.minifyCursor(s):null};const u=s?.remote?.[a]?.pageNumber??1,p=(u-1)*r,d=p+r,l=i.slice(p,d),y=i.length>d||!c,g=e.updateCursor({cursor:s,stepIndex:a,pageNumber:u+1});return{result:{...t,data:l},next:y?e.minifyCursor(g):null}},c=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=a})=>await u({block:t,buildStepFunction:o,virtualPaginateResultFn:r}),u=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=a})=>{const i=r.operation?.steps||{};let c={...r};const u=Object.keys(i),l=((e,t)=>{const r=Number(e.inputs?.page_size);return o.notMissing(e.inputs?.page_size)&&o.isNumber(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??t})(r,25);let y=!1,g=null;for(const[o,r]of u.entries()){const s=i[r],a=s.stepFunction,u=n({functionName:a.functionName,version:a.version,validateSchemas:!0}).fn;if(s.condition&&!t.safeEvaluate(s.condition,c)){c=d({block:c,stepId:r,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(y){c=d({block:c,stepId:r,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const p=c.operation?.cursor.enabled?{...a.params,cursor:{token:c.nextCursor?.remote?.[o]?.providerPageCursor,position:c.nextCursor?.remote?.[o]?.position}}:a.params,l=await u({block:c,params:p});if(!1===l.successful){c=d({block:c,stepId:r,successful:!1,functionOutput:l});(s.ignoreError??!1)||(y=!0,g??=l.output?.statusCode??500)}else{const t=c.operation?.cursor.enabled?e.updateCursor({cursor:c.nextCursor,stepIndex:o,providerPageCursor:l.output?.next,position:l.output?.position}):void 0;c=d({block:{...l.block,nextCursor:t},stepId:r,functionOutput:l})}}const b=r.operation?.result?p(r.operation.result,c):void 0,m=r.operation?.cursor.enabled?s(b,l,i,c.nextCursor):void 0,h=!y,z=h?r.operation?.responses.success.statusCode??200:g??500,f=o.notMissing(m)&&o.isObject(m.result)?{next:m.next,...m.result}:b;return{...c,outputs:f,response:{successful:h,statusCode:z,message:h?void 0:r.operation?.responses?.errors?.[z]?.description??"Error while processing the request"}}},p=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),d=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),l=async({inputs:e,context:t,operation:o,credentials:n,nextCursor:s,logger:i,getHttpClient:a=async()=>r.HttpClientManager.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:n,nextCursor:s,httpClient:await a(),logger:i}),y=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),g=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=m(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},b=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},m=(e,t,o)=>{const r=b(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(b(o))(b(r));if(!1!==s)return{path:e,params:s.params}}},h=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},z={key:i.z.string(),label:i.z.string(),required:i.z.boolean().optional().default(!1),secret:i.z.boolean().optional().default(!1),readOnly:i.z.boolean().optional().default(!1),placeholder:i.z.string().optional(),description:i.z.string().optional(),tooltip:i.z.string().optional()},f=i.z.discriminatedUnion("type",[i.z.object({...z,type:i.z.enum(["text","password"])}),i.z.object({...z,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),_=i.z.object({operationId:i.z.string(),categories:i.z.string().array(),operationType:i.z.enum(["list","get","create","update","delete","custom","unknown"]),schema:i.z.string().optional(),entrypointUrl:i.z.string().optional(),entrypointHttpMethod:i.z.string().optional(),description:i.z.string(),responses:i.z.object({statusCode:i.z.number(),description:i.z.string()}).array().optional(),inputs:i.z.object({name:i.z.string(),type:i.z.string(),required:i.z.boolean(),description:i.z.string(),in:i.z.string()}).array().optional(),cursor:i.z.object({enabled:i.z.boolean(),pageSize:i.z.number()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),isUnified:i.z.boolean(),enumMapper:i.z.object({matcher:i.z.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(i.z.object({matchExpression:i.z.string(),value:i.z.string()}).array())}).optional()}).array().optional(),steps:i.z.object({stepId:i.z.string(),description:i.z.string(),stepFunction:i.z.object({functionName:i.z.string(),version:i.z.string().optional(),parameters:i.z.record(i.z.string(),i.z.unknown())}),condition:i.z.string().optional(),ignoreError:i.z.boolean().optional()}).array(),result:i.z.string().or(i.z.record(i.z.string(),i.z.unknown())).optional()}),C=i.z.object({StackOne:i.z.string(),info:i.z.object({title:i.z.string(),version:i.z.string(),key:i.z.string(),description:i.z.string().optional()}),baseUrl:i.z.string(),authentication:i.z.record(i.z.string(),i.z.object({type:i.z.string(),label:i.z.string(),authorization:e.AUTHENTICATION_SCHEMA,environments:i.z.object({key:i.z.string(),name:i.z.string()}).array(),support:i.z.object({link:i.z.string(),description:i.z.string().optional()}),configFields:f.array().optional(),setupFields:f.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:_.array().optional()});function k(e){try{const t=s.parse(e),r=C.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=x(r),a={baseUrl:r.baseUrl,authentication:v(i)},c=I(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=S(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const v=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=v(a)}else t[o]=r;return t},S=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},x=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},I=(e,t)=>{const o=e.operations?.reduce(((e,o)=>{const n=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(o),s=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(o),i=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(o),a=(e=>{const t={success:h(e.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},o=e.responses?.reduce(((e,t)=>(r.isSuccessStatusCode(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e)),t);return o??t})(o),c=O(o),u=o.inputs||[];return c.enabled&&u?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),e[n??s]={id:o.operationId,categories:o.categories,description:o.description,operationType:o.operationType,entrypointUrl:o.entrypointUrl??i,entrypointHttpMethod:o.entrypointHttpMethod??"get",responses:a,cursor:c,inputs:u,steps:o.steps.reduce(((e,r)=>(e[r.stepId]={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{..."request"===r.stepFunction.functionName||"paginated_request"===r.stepFunction.functionName?t:{},..."map_fields"===r.stepFunction.functionName||"typecast"===r.stepFunction.functionName?{fields:o.fieldConfigs}:{},...r.stepFunction.parameters}}},e)),{}),result:o.result},e}),{});return o},F=(e,t)=>{if(!e.inputs)return{};const o=E(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},w=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=i.z.string();break;case"number":o=i.z.number();break;case"boolean":o=i.z.boolean();break;default:o=i.z.any()}t[e.name]=e.required?o:o.optional()})),i.z.object(t)},E=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return i.z.object({path:w(t).optional(),query:w(o).optional(),body:w(r).optional(),headers:w(n).optional()})},O=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}};class j extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,j)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class N extends j{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class T extends j{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class R extends j{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class q extends j{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const M=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new q(r,"Invalid cursor.");return s};exports.ConnectSDKError=j,exports.createBlock=l,exports.executeStepFunction=async({block:t,stepFunctionName:o,params:r,buildStepFunction:n=e.StepFunctionsFactory.build})=>{const s=n({functionName:o}).fn,i=await s({block:t,params:r}),a=o===e.StepFunctionName.MAP_FIELDS?{[e.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:i.block.result},errors:i.errors,successful:i.successful}}:{};return{...i.block,steps:{...i?.block?.steps??{},...a}}},exports.getOperationFromUrl=g,exports.parseOperationInputs=F,exports.parseYamlConnector=k,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:u,logger:p,parseConnector:d=k,getOperationFromUrlFn:b=g,parseOperationInputsFn:m=F,createBlockContextFn:h=y,createBlockFn:z=l,runStepOperationFn:f=c})=>{const _=e.authConfigKey,C=e.environment??"production",v=e.secureId,S=e.projectSecureId,x=e.credentials,I=h({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:v,projectSecureId:S});let w;try{w=o.isString(t)?d(t):t}catch{throw new N(I,"Error while parsing connector")}const E=b(w,n,s);if(o.isMissing(E))throw new T(I,"No matching operation found");I.operationType=E.operation.operationType,I.schema=E.operation.schema?.key;const O=M(i,I);let j;try{j=m(E.operation,{query:i,body:a,headers:u,path:E.params})}catch{throw new R(I,"Error while parsing operation inputs")}const q=await z({inputs:j,context:I,operation:E.operation,credentials:x,nextCursor:O,logger:p});return await f({block:q})},exports.runStepOperation=c;
@@ -0,0 +1,2 @@
1
+ import { Block } from '@stackone/core';
2
+ export declare const getPageSize: (block: Block, defaultValue: number) => number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/connect-sdk",
3
- "version": "1.23.1",
3
+ "version": "1.24.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.es.mjs",