@stackone/connect-sdk 1.28.0 → 1.29.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 +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.es.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StepFunctionsFactory as e,StepFunctionName as t,COMPOSITE_ID_LATEST_VERSION as o,encodeCompositeId as r,isCursorEmpty as n,minifyCursor as s,updateCursor as i,AUTHENTICATION_SCHEMA as a,expandCursor as c}from"@stackone/core";import{safeEvaluate as p,safeEvaluateRecord as u}from"@stackone/expressions";import{isMissing as d,notMissing as l,isNumber as y,isObject as m,isString as g}from"@stackone/utils";import{HttpClientManager as b,isSuccessStatusCode as f}from"@stackone/transport";import{match as h}from"path-to-regexp";import{parse as _}from"yaml";import{z as v}from"zod";const k=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}}},C=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const o="data",r=e.outputs?.[o];if(d(r))return e;const n=Array.isArray(r)?r.map((e=>I(e,t))):I(r,t);return{...e,outputs:{...e.outputs??{},[o]:n}}},I=(e,t)=>{const n=t.version??o,s={};return t.fields?.forEach((t=>{const o={},i=[];t.components.forEach((t=>{t.alias&&(o[t.name]=t.alias),i.push({key:t.name,value:e[t.name]})}));const a=1===i.length?i[0]:{identifiers:i},c={version:n,aliases:Object.keys(o).length>0?o:void 0},p=r(a,c);s[t.targetFieldKey]=p,t.remote&&(s[`remote_${t.remote}`]=e[t.remote])})),{...e,...s}},F=(e,t,o,r)=>{const a=d(e)?void 0:e.data,c=Object.keys(o).length+1,p=n({cursor:r,ignoreStepIndex:c});if(!m(e)||d(a)||(a?.length??0)<=t)return{result:e,next:l(r)&&!p?s(r):null};const u=r?.remote?.[c]?.pageNumber??1,y=(u-1)*t,g=y+t,b=a.slice(y,g),f=a.length>g||!p,h=i({cursor:r,stepIndex:c,pageNumber:u+1});return{result:{...e,data:b},next:f?s(h):null}},w=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=F,encodeResultCompositeIds:n=C})=>n(await S({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),S=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=F})=>{const n=t.operation?.steps||{};let s={...t};const a=Object.keys(n),c=((e,t)=>{const o=Number(e.inputs?.page_size);return l(e.inputs?.page_size)&&y(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let u=!1,d=null;for(const[e,t]of a.entries()){const r=n[t],a=r.stepFunction,c=o({functionName:a.functionName,version:a.version,validateSchemas:!0}).fn;if(r.condition&&!p(r.condition,s)){s=E({block:s,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(u){s=E({block:s,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const l=s.operation?.cursor.enabled?{...a.params,cursor:{token:s.nextCursor?.remote?.[e]?.providerPageCursor,position:s.nextCursor?.remote?.[e]?.position}}:a.params,y=await c({block:s,params:l});if(!1===y.successful){s=E({block:s,stepId:t,successful:!1,functionOutput:y});(r.ignoreError??!1)||(u=!0,d??=y.output?.statusCode??500)}else{const o=s.operation?.cursor.enabled?i({cursor:s.nextCursor,stepIndex:e,providerPageCursor:y.output?.next,position:y.output?.position}):void 0;s=E({block:{...y.block,nextCursor:o},stepId:t,functionOutput:y})}}const g=t.operation?.result?x(t.operation.result,s):void 0,b=t.operation?.cursor.enabled?r(g,c,n,s.nextCursor):void 0,f=!u,h=f?t.operation?.responses.success.statusCode??200:d??500,_=l(b)&&m(b.result)?{next:b.next,...b.result}:g;return{...s,outputs:_,response:{successful:f,statusCode:h,message:f?void 0:t.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},x=(e,t)=>m(e)?u(e,t):p(e,t),E=({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}}}),j=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>b.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),O=({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}),T=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=R(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},N=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},R=(e,t,o)=>{const r=N(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=h(N(o))(N(r));if(!1!==n)return{path:e,params:n.params}}},K=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}`)}},U={key:v.string(),label:v.string(),required:v.boolean().optional().default(!1),secret:v.boolean().optional().default(!1),readOnly:v.boolean().optional().default(!1),placeholder:v.string().optional(),description:v.string().optional(),tooltip:v.string().optional()},q=v.discriminatedUnion("type",[v.object({...U,type:v.enum(["text","password"])}),v.object({...U,type:v.literal("select"),options:v.object({value:v.string(),label:v.string()}).array()})]),P=v.object({operationId:v.string(),categories:v.string().array(),operationType:v.enum(["list","get","create","update","delete","custom","unknown"]),schema:v.string().optional(),entrypointUrl:v.string().optional(),entrypointHttpMethod:v.string().optional(),description:v.string(),responses:v.object({statusCode:v.number(),description:v.string()}).array().optional(),inputs:v.object({name:v.string(),type:v.string(),required:v.boolean(),description:v.string(),in:v.string()}).array().optional(),cursor:v.object({enabled:v.boolean(),pageSize:v.number()}).optional(),compositeIdentifiers:v.object({enabled:v.boolean(),version:v.number().optional(),fields:v.object({targetFieldKey:v.string(),remote:v.string().optional(),components:v.string().array()}).array().optional()}).optional(),fieldConfigs:v.object({targetFieldKey:v.string(),alias:v.string().optional(),expression:v.string(),type:v.enum(["string","number","boolean","datetime_string","enum"]),custom:v.boolean().default(!1),hidden:v.boolean().default(!1),enumMapper:v.object({matcher:v.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(v.object({matchExpression:v.string(),value:v.string()}).array())}).optional()}).array().optional(),steps:v.object({stepId:v.string(),description:v.string(),stepFunction:v.object({functionName:v.string(),version:v.string().optional(),parameters:v.record(v.string(),v.unknown())}),condition:v.string().optional(),ignoreError:v.boolean().optional()}).array(),result:v.string().or(v.record(v.string(),v.unknown())).optional()}),$=v.object({StackOne:v.string(),info:v.object({title:v.string(),version:v.string(),key:v.string(),description:v.string().optional()}),baseUrl:v.string(),authentication:v.record(v.string(),v.object({type:v.string(),label:v.string(),authorization:a,environments:v.object({key:v.string(),name:v.string()}).array(),support:v.object({link:v.string(),description:v.string().optional()}),configFields:q.array().optional(),setupFields:q.array().optional(),testOperationsIds:v.string().array().optional()})).array().optional(),operations:P.array().optional()});function z(e){try{const t=_(e),o=$.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=H(o),s={baseUrl:o.baseUrl,authentication:A(n)},i=L(o,s);return r.operations=i,r.authentication=n,l(i)&&(r.categories=M(Object.values(i))),r}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const A=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]=A(a)}else t[o]=r;return t},M=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},H=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},L=(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:K(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)=>(f(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=W(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,compositeIdentifiers:B(o),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},V=(e,t)=>{if(!e.inputs)return{};const o=G(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},D=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=v.string();break;case"number":o=v.number();break;case"boolean":o=v.boolean();break;default:o=v.any()}t[e.name]=e.required?o:o.optional()})),v.object(t)},G=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 v.object({path:D(t).optional(),query:D(o).optional(),body:D(r).optional(),headers:D(n).optional()})},W=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},B=e=>{if(d(e.compositeIdentifiers)){const t=e.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),r=l(t)?[{targetFieldKey:t.targetFieldKey,remote:"id",components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:o,fields:r}}const t=[];for(const o of e.compositeIdentifiers?.fields??[]){const r=o.components.map((t=>{const o=e.fieldConfigs?.find((e=>e.targetFieldKey===t));return{name:t,alias:o?.alias}}));t.push({targetFieldKey:o.targetFieldKey,remote:o.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}};class Y extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,Y)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class J extends Y{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class Q extends Y{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class X extends Y{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class Z extends Y{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const ee=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=z,getOperationFromUrlFn:u=T,parseOperationInputsFn:l=V,createBlockContextFn:y=O,createBlockFn:m=j,runStepOperationFn:b=w})=>{const f=e.authConfigKey,h=e.environment??"production",_=e.secureId,v=e.projectSecureId,k=e.credentials,C=y({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:f,environment:h,accountSecureId:_,projectSecureId:v});let I;try{I=g(t)?p(t):t}catch{throw new J(C,"Error while parsing connector")}const F=u(I,r,n);if(d(F))throw new Q(C,"No matching operation found");C.operationType=F.operation.operationType,C.schema=F.operation.schema?.key;const S=te(s,C);let x;try{x=l(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new X(C,"Error while parsing operation inputs")}const E=await m({inputs:x,context:C,operation:F.operation,credentials:k,nextCursor:S,logger:c});return await b({block:E})},te=(e,t)=>{const o=e?.next,r=l(o)&&"list"===t.operationType?c(o):void 0;if(null===r)throw new Z(t,"Invalid cursor.");return r};export{Y as ConnectSDKError,j as createBlock,k as executeStepFunction,T as getOperationFromUrl,V as parseOperationInputs,z as parseYamlConnector,ee as runConnectorOperation,w as runStepOperation};
|
|
1
|
+
import{StepFunctionsFactory as e,StepFunctionName as t,COMPOSITE_ID_LATEST_VERSION as o,encodeCompositeId as r,isCompositeId as n,isCursorEmpty as s,minifyCursor as i,updateCursor as a,AUTHENTICATION_SCHEMA as c,expandCursor as p}from"@stackone/core";import{safeEvaluate as u,safeEvaluateRecord as d}from"@stackone/expressions";import{isMissing as l,isObject as y,isString as m,notMissing as g,isNumber as f}from"@stackone/utils";import{HttpClientManager as b,isSuccessStatusCode as h}from"@stackone/transport";import{match as _}from"path-to-regexp";import{parse as v}from"yaml";import{z as k}from"zod";const C=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}}},I="remote_",F=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const o="data",r=e.outputs?.[o];if(l(r))return e;const n=Array.isArray(r)?r.map((e=>w(e,t))):w(r,t);return{...e,outputs:{...e.outputs??{},[o]:n}}},w=(e,t)=>{const o=S(e,t),r=x(o);return{...e,...y(r)?r:{}}},S=(e,t)=>{const n=t.version??o,s={};return t.fields?.forEach((t=>{const o={},i=[];t.components.forEach((t=>{t.alias&&(o[t.name]=t.alias),i.push({key:t.name,value:e[t.name]})}));const a=1===i.length?i[0]:{identifiers:i},c={version:n,aliases:Object.keys(o).length>0?o:void 0},p=r(a,c);s[t.targetFieldKey]=p,t.remote&&(s[`${I}${t.remote}`]=e[t.remote])})),{...e,...s}},x=e=>{if(Array.isArray(e))return e.map((e=>x(e)));if(!y(e))return e;const t={...e};for(const[s,i]of Object.entries(e))if((y(i)||Array.isArray(i)&&i.length>0&&y(i[0]))&&(t[s]=x(i)),"id"===s||/.+_id(s)?$/.test(s))if(Array.isArray(i)&&i.every((e=>m(e)&&e.length>0))){const e=i.map((e=>{if(m(e)&&e.length>0&&!n(e))try{return r({key:s,value:e},{version:o})}catch{return e}return e}));t[s]=e,t[`${I}${s}`]=i}else if(m(i)&&i.length>0){if(n(i)||s.startsWith(I))continue;const e=r({key:s,value:i},{version:o});t[s]=e,t[`remote_${s}`]=i}return t},j=(e,t,o,r)=>{const n=l(e)?void 0:e.data,c=Object.keys(o).length+1,p=s({cursor:r,ignoreStepIndex:c});if(!y(e)||l(n)||(n?.length??0)<=t)return{result:e,next:g(r)&&!p?i(r):null};const u=r?.remote?.[c]?.pageNumber??1,d=(u-1)*t,m=d+t,f=n.slice(d,m),b=n.length>m||!p,h=a({cursor:r,stepIndex:c,pageNumber:u+1});return{result:{...e,data:f},next:b?i(h):null}},E=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=j,encodeResultCompositeIds:n=F})=>n(await O({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),O=async({block:t,buildStepFunction:o=e.build,virtualPaginateResultFn:r=j})=>{const n=t.operation?.steps||{};let s={...t};const i=Object.keys(n),c=((e,t)=>{const o=Number(e.inputs?.page_size);return g(e.inputs?.page_size)&&f(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25);let p=!1,d=null;for(const[e,t]of i.entries()){const r=n[t],i=r.stepFunction,c=o({functionName:i.functionName,version:i.version,validateSchemas:!0}).fn;if(r.condition&&!u(r.condition,s)){s=N({block:s,stepId:t,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(p){s=N({block:s,stepId:t,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const l=s.operation?.cursor.enabled?{...i.params,cursor:{token:s.nextCursor?.remote?.[e]?.providerPageCursor,position:s.nextCursor?.remote?.[e]?.position}}:i.params,y=await c({block:s,params:l});if(!1===y.successful){s=N({block:s,stepId:t,successful:!1,functionOutput:y});(r.ignoreError??!1)||(p=!0,d??=y.output?.statusCode??500)}else{const o=s.operation?.cursor.enabled?a({cursor:s.nextCursor,stepIndex:e,providerPageCursor:y.output?.next,position:y.output?.position}):void 0;s=N({block:{...y.block,nextCursor:o},stepId:t,functionOutput:y})}}const l=t.operation?.result?T(t.operation.result,s):void 0,m=t.operation?.cursor.enabled?r(l,c,n,s.nextCursor):void 0,b=!p,h=b?t.operation?.responses.success.statusCode??200:d??500,_=g(m)&&y(m.result)?{next:m.next,...m.result}:l;return{...s,outputs:_,response:{successful:b,statusCode:h,message:b?void 0:t.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},T=(e,t)=>y(e)?d(e,t):u(e,t),N=({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}}}),R=async({inputs:e,context:t,operation:o,credentials:r,nextCursor:n,logger:s,getHttpClient:i=async()=>b.getInstance()})=>({inputs:e,fieldConfigs:[],context:t,operation:o,credentials:r,nextCursor:n,httpClient:await i(),logger:s}),K=({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,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=U(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},A=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},U=(e,t,o)=>{const r=A(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),n=_(A(o))(A(r));if(!1!==n)return{path:e,params:n.params}}},q=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}`)}},P={key:k.string(),label:k.string(),required:k.boolean().optional().default(!1),secret:k.boolean().optional().default(!1),readOnly:k.boolean().optional().default(!1),placeholder:k.string().optional(),description:k.string().optional(),tooltip:k.string().optional()},z=k.discriminatedUnion("type",[k.object({...P,type:k.enum(["text","password"])}),k.object({...P,type:k.literal("select"),options:k.object({value:k.string(),label:k.string()}).array()})]),M=k.object({operationId:k.string(),categories:k.string().array(),operationType:k.enum(["list","get","create","update","delete","custom","unknown"]),schema:k.string().optional(),entrypointUrl:k.string().optional(),entrypointHttpMethod:k.string().optional(),description:k.string(),responses:k.object({statusCode:k.number(),description:k.string()}).array().optional(),inputs:k.object({name:k.string(),type:k.string(),required:k.boolean(),description:k.string(),in:k.string()}).array().optional(),cursor:k.object({enabled:k.boolean(),pageSize:k.number()}).optional(),compositeIdentifiers:k.object({enabled:k.boolean(),version:k.number().optional(),fields:k.object({targetFieldKey:k.string(),remote:k.string().optional(),components:k.string().array()}).array().optional()}).optional(),fieldConfigs:k.object({targetFieldKey:k.string(),alias:k.string().optional(),expression:k.string(),type:k.enum(["string","number","boolean","datetime_string","enum"]),custom:k.boolean().default(!1),hidden:k.boolean().default(!1),enumMapper:k.object({matcher:k.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(k.object({matchExpression:k.string(),value:k.string()}).array())}).optional()}).array().optional(),steps:k.object({stepId:k.string(),description:k.string(),stepFunction:k.object({functionName:k.string(),version:k.string().optional(),parameters:k.record(k.string(),k.unknown())}),condition:k.string().optional(),ignoreError:k.boolean().optional()}).array(),result:k.string().or(k.record(k.string(),k.unknown())).optional()}),H=k.object({StackOne:k.string(),info:k.object({title:k.string(),version:k.string(),key:k.string(),description:k.string().optional()}),baseUrl:k.string(),authentication:k.record(k.string(),k.object({type:k.string(),label:k.string(),authorization:c,environments:k.object({key:k.string(),name:k.string()}).array(),support:k.object({link:k.string(),description:k.string().optional()}),configFields:z.array().optional(),setupFields:z.array().optional(),testOperationsIds:k.string().array().optional()})).array().optional(),operations:M.array().optional()});function L(e){try{const t=v(e),o=H.parse(t),r={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},n=W(o),s={baseUrl:o.baseUrl,authentication:V(n)},i=G(o,s);return r.operations=i,r.authentication=n,g(i)&&(r.categories=D(Object.values(i))),r}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},D=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},G=(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:q(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)=>(h(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=Q(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,compositeIdentifiers:X(o),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},B=(e,t)=>{if(!e.inputs)return{};const o=J(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},Y=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=k.string();break;case"number":o=k.number();break;case"boolean":o=k.boolean();break;default:o=k.any()}t[e.name]=e.required?o:o.optional()})),k.object(t)},J=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 k.object({path:Y(t).optional(),query:Y(o).optional(),body:Y(r).optional(),headers:Y(n).optional()})},Q=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},X=e=>{if(l(e.compositeIdentifiers)){const t=e.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),r=g(t)?[{targetFieldKey:t.targetFieldKey,remote:"id",components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:o,fields:r}}const t=[];for(const o of e.compositeIdentifiers?.fields??[]){const r=o.components.map((t=>{const o=e.fieldConfigs?.find((e=>e.targetFieldKey===t));return{name:t,alias:o?.alias}}));t.push({targetFieldKey:o.targetFieldKey,remote:o.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}};class Z extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,Z)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class ee extends Z{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class te extends Z{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class oe extends Z{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class re extends Z{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const ne=async({account:e,connector:t,category:o,path:r,method:n="get",queryParams:s,body:i,headers:a,logger:c,parseConnector:p=L,getOperationFromUrlFn:u=$,parseOperationInputsFn:d=B,createBlockContextFn:y=K,createBlockFn:g=R,runStepOperationFn:f=E})=>{const b=e.authConfigKey,h=e.environment??"production",_=e.secureId,v=e.projectSecureId,k=e.credentials,C=y({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:b,environment:h,accountSecureId:_,projectSecureId:v});let I;try{I=m(t)?p(t):t}catch{throw new ee(C,"Error while parsing connector")}const F=u(I,r,n);if(l(F))throw new te(C,"No matching operation found");C.operationType=F.operation.operationType,C.schema=F.operation.schema?.key;const w=se(s,C);let S;try{S=d(F.operation,{query:s,body:i,headers:a,path:F.params})}catch{throw new oe(C,"Error while parsing operation inputs")}const x=await g({inputs:S,context:C,operation:F.operation,credentials:k,nextCursor:w,logger:c});return await f({block:x})},se=(e,t)=>{const o=e?.next,r=g(o)&&"list"===t.operationType?p(o):void 0;if(null===r)throw new re(t,"Invalid cursor.");return r};export{Z as ConnectSDKError,R as createBlock,C as executeStepFunction,$ as getOperationFromUrl,B as parseOperationInputs,L as parseYamlConnector,ne as runConnectorOperation,E 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=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const r="data",n=e.outputs?.[r];if(o.isMissing(n))return e;const s=Array.isArray(n)?n.map((e=>c(e,t))):c(n,t);return{...e,outputs:{...e.outputs??{},[r]:s}}},c=(t,o)=>{const r=o.version??e.COMPOSITE_ID_LATEST_VERSION,n={};return o.fields?.forEach((o=>{const s={},i=[];o.components.forEach((e=>{e.alias&&(s[e.name]=e.alias),i.push({key:e.name,value:t[e.name]})}));const a=1===i.length?i[0]:{identifiers:i},c={version:r,aliases:Object.keys(s).length>0?s:void 0},p=e.encodeCompositeId(a,c);n[o.targetFieldKey]=p,o.remote&&(n[`remote_${o.remote}`]=t[o.remote])})),{...t,...n}},p=(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 p=s?.remote?.[a]?.pageNumber??1,u=(p-1)*r,d=u+r,l=i.slice(u,d),y=i.length>d||!c,g=e.updateCursor({cursor:s,stepIndex:a,pageNumber:p+1});return{result:{...t,data:l},next:y?e.minifyCursor(g):null}},u=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=p,encodeResultCompositeIds:n=a})=>n(await d({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),d=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=p})=>{const i=r.operation?.steps||{};let a={...r};const c=Object.keys(i),u=((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 d=!1,g=null;for(const[o,r]of c.entries()){const s=i[r],c=s.stepFunction,p=n({functionName:c.functionName,version:c.version,validateSchemas:!0}).fn;if(s.condition&&!t.safeEvaluate(s.condition,a)){a=y({block:a,stepId:r,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(d){a=y({block:a,stepId:r,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const u=a.operation?.cursor.enabled?{...c.params,cursor:{token:a.nextCursor?.remote?.[o]?.providerPageCursor,position:a.nextCursor?.remote?.[o]?.position}}:c.params,l=await p({block:a,params:u});if(!1===l.successful){a=y({block:a,stepId:r,successful:!1,functionOutput:l});(s.ignoreError??!1)||(d=!0,g??=l.output?.statusCode??500)}else{const t=a.operation?.cursor.enabled?e.updateCursor({cursor:a.nextCursor,stepIndex:o,providerPageCursor:l.output?.next,position:l.output?.position}):void 0;a=y({block:{...l.block,nextCursor:t},stepId:r,functionOutput:l})}}const m=r.operation?.result?l(r.operation.result,a):void 0,b=r.operation?.cursor.enabled?s(m,u,i,a.nextCursor):void 0,f=!d,h=f?r.operation?.responses.success.statusCode??200:g??500,z=o.notMissing(b)&&o.isObject(b.result)?{next:b.next,...b.result}:m;return{...a,outputs:z,response:{successful:f,statusCode:h,message:f?void 0:r.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},l=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),y=({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}}}),g=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}),m=({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}),b=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=h(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},h=(e,t,o)=>{const r=f(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(f(o))(f(r));if(!1!==s)return{path:e,params:s.params}}},z=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}`)}},_={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()},C=i.z.discriminatedUnion("type",[i.z.object({..._,type:i.z.enum(["text","password"])}),i.z.object({..._,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),v=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(),compositeIdentifiers:i.z.object({enabled:i.z.boolean(),version:i.z.number().optional(),fields:i.z.object({targetFieldKey:i.z.string(),remote:i.z.string().optional(),components:i.z.string().array()}).array().optional()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),alias:i.z.string().optional(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),custom:i.z.boolean().default(!1),hidden:i.z.boolean().default(!1),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()}),I=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:C.array().optional(),setupFields:C.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:v.array().optional()});function k(e){try{const t=s.parse(e),r=I.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=E(r),a={baseUrl:r.baseUrl,authentication:S(i)},c=x(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=F(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const S=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]=S(a)}else t[o]=r;return t},F=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=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},x=(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:z(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=j(o),p=o.inputs||[];return c.enabled&&p?.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,compositeIdentifiers:N(o),inputs:p,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},O=(e,t)=>{if(!e.inputs)return{};const o=T(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)},T=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()})},j=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},N=t=>{if(o.isMissing(t.compositeIdentifiers)){const r=t.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),n=o.notMissing(r)?[{targetFieldKey:r.targetFieldKey,remote:"id",components:[{name:r.targetFieldKey,alias:r.alias}]}]:void 0;return{enabled:!0,version:e.COMPOSITE_ID_LATEST_VERSION,fields:n}}const r=[];for(const e of t.compositeIdentifiers?.fields??[]){const o=e.components.map((e=>{const o=t.fieldConfigs?.find((t=>t.targetFieldKey===e));return{name:e,alias:o?.alias}}));r.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:o})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:r.length>0?r:void 0}};class M extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,M)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class R extends M{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class q extends M{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class K extends M{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class U extends M{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const A=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new U(r,"Invalid cursor.");return s};exports.ConnectSDKError=M,exports.createBlock=g,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=b,exports.parseOperationInputs=O,exports.parseYamlConnector=k,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:c,logger:p,parseConnector:d=k,getOperationFromUrlFn:l=b,parseOperationInputsFn:y=O,createBlockContextFn:f=m,createBlockFn:h=g,runStepOperationFn:z=u})=>{const _=e.authConfigKey,C=e.environment??"production",v=e.secureId,I=e.projectSecureId,S=e.credentials,F=f({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:v,projectSecureId:I});let E;try{E=o.isString(t)?d(t):t}catch{throw new R(F,"Error while parsing connector")}const x=l(E,n,s);if(o.isMissing(x))throw new q(F,"No matching operation found");F.operationType=x.operation.operationType,F.schema=x.operation.schema?.key;const w=A(i,F);let T;try{T=y(x.operation,{query:i,body:a,headers:c,path:x.params})}catch{throw new K(F,"Error while parsing operation inputs")}const j=await h({inputs:T,context:F,operation:x.operation,credentials:S,nextCursor:w,logger:p});return await z({block:j})},exports.runStepOperation=u;
|
|
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="remote_",c=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const r="data",n=e.outputs?.[r];if(o.isMissing(n))return e;const s=Array.isArray(n)?n.map((e=>u(e,t))):u(n,t);return{...e,outputs:{...e.outputs??{},[r]:s}}},u=(e,t)=>{const r=p(e,t),n=d(r);return{...e,...o.isObject(n)?n:{}}},p=(t,o)=>{const r=o.version??e.COMPOSITE_ID_LATEST_VERSION,n={};return o.fields?.forEach((o=>{const s={},i=[];o.components.forEach((e=>{e.alias&&(s[e.name]=e.alias),i.push({key:e.name,value:t[e.name]})}));const c=1===i.length?i[0]:{identifiers:i},u={version:r,aliases:Object.keys(s).length>0?s:void 0},p=e.encodeCompositeId(c,u);n[o.targetFieldKey]=p,o.remote&&(n[`${a}${o.remote}`]=t[o.remote])})),{...t,...n}},d=t=>{if(Array.isArray(t))return t.map((e=>d(e)));if(!o.isObject(t))return t;const r={...t};for(const[n,s]of Object.entries(t))if((o.isObject(s)||Array.isArray(s)&&s.length>0&&o.isObject(s[0]))&&(r[n]=d(s)),"id"===n||/.+_id(s)?$/.test(n))if(Array.isArray(s)&&s.every((e=>o.isString(e)&&e.length>0))){const t=s.map((t=>{if(o.isString(t)&&t.length>0&&!e.isCompositeId(t))try{return e.encodeCompositeId({key:n,value:t},{version:e.COMPOSITE_ID_LATEST_VERSION})}catch{return t}return t}));r[n]=t,r[`${a}${n}`]=s}else if(o.isString(s)&&s.length>0){if(e.isCompositeId(s)||n.startsWith(a))continue;const t=e.encodeCompositeId({key:n,value:s},{version:e.COMPOSITE_ID_LATEST_VERSION});r[n]=t,r[`remote_${n}`]=s}return r},l=(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}},y=async({block:t,buildStepFunction:o=e.StepFunctionsFactory.build,virtualPaginateResultFn:r=l,encodeResultCompositeIds:n=c})=>n(await g({block:t,buildStepFunction:o,virtualPaginateResultFn:r})),g=async({block:r,buildStepFunction:n=e.StepFunctionsFactory.build,virtualPaginateResultFn:s=l})=>{const i=r.operation?.steps||{};let a={...r};const c=Object.keys(i),u=((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 p=!1,d=null;for(const[o,r]of c.entries()){const s=i[r],c=s.stepFunction,u=n({functionName:c.functionName,version:c.version,validateSchemas:!0}).fn;if(s.condition&&!t.safeEvaluate(s.condition,a)){a=b({block:a,stepId:r,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});continue}if(p){a=b({block:a,stepId:r,successful:!1,skipped:!0,message:"Step skipped due to previous error."});continue}const l=a.operation?.cursor.enabled?{...c.params,cursor:{token:a.nextCursor?.remote?.[o]?.providerPageCursor,position:a.nextCursor?.remote?.[o]?.position}}:c.params,y=await u({block:a,params:l});if(!1===y.successful){a=b({block:a,stepId:r,successful:!1,functionOutput:y});(s.ignoreError??!1)||(p=!0,d??=y.output?.statusCode??500)}else{const t=a.operation?.cursor.enabled?e.updateCursor({cursor:a.nextCursor,stepIndex:o,providerPageCursor:y.output?.next,position:y.output?.position}):void 0;a=b({block:{...y.block,nextCursor:t},stepId:r,functionOutput:y})}}const y=r.operation?.result?m(r.operation.result,a):void 0,g=r.operation?.cursor.enabled?s(y,u,i,a.nextCursor):void 0,f=!p,h=f?r.operation?.responses.success.statusCode??200:d??500,z=o.notMissing(g)&&o.isObject(g.result)?{next:g.next,...g.result}:y;return{...a,outputs:z,response:{successful:f,statusCode:h,message:f?void 0:r.operation?.responses?.errors?.[h]?.description??"Error while processing the request"}}},m=(e,r)=>o.isObject(e)?t.safeEvaluateRecord(e,r):t.safeEvaluate(e,r),b=({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}}}),f=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}),h=({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}),z=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=C(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},_=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},C=(e,t,o)=>{const r=_(e);for(const e of o)if(e.startsWith(t)){const o=e.replace(`${t} `,"").trim(),s=n.match(_(o))(_(r));if(!1!==s)return{path:e,params:s.params}}},v=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}`)}},I={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()},S=i.z.discriminatedUnion("type",[i.z.object({...I,type:i.z.enum(["text","password"])}),i.z.object({...I,type:i.z.literal("select"),options:i.z.object({value:i.z.string(),label:i.z.string()}).array()})]),k=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(),compositeIdentifiers:i.z.object({enabled:i.z.boolean(),version:i.z.number().optional(),fields:i.z.object({targetFieldKey:i.z.string(),remote:i.z.string().optional(),components:i.z.string().array()}).array().optional()}).optional(),fieldConfigs:i.z.object({targetFieldKey:i.z.string(),alias:i.z.string().optional(),expression:i.z.string(),type:i.z.enum(["string","number","boolean","datetime_string","enum"]),custom:i.z.boolean().default(!1),hidden:i.z.boolean().default(!1),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()}),O=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:S.array().optional(),setupFields:S.array().optional(),testOperationsIds:i.z.string().array().optional()})).array().optional(),operations:k.array().optional()});function E(e){try{const t=s.parse(e),r=O.parse(t),n={title:r.info.title,version:r.info.version,key:r.info.key,description:r.info.description},i=T(r),a={baseUrl:r.baseUrl,authentication:F(i)},c=j(r,a);return n.operations=c,n.authentication=i,o.notMissing(c)&&(n.categories=x(Object.values(c))),n}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const F=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]=F(a)}else t[o]=r;return t},x=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},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},j=(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:v(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=R(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,compositeIdentifiers:A(o),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},w=(e,t)=>{if(!e.inputs)return{};const o=M(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},N=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)},M=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:N(t).optional(),query:N(o).optional(),body:N(r).optional(),headers:N(n).optional()})},R=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},A=t=>{if(o.isMissing(t.compositeIdentifiers)){const r=t.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),n=o.notMissing(r)?[{targetFieldKey:r.targetFieldKey,remote:"id",components:[{name:r.targetFieldKey,alias:r.alias}]}]:void 0;return{enabled:!0,version:e.COMPOSITE_ID_LATEST_VERSION,fields:n}}const r=[];for(const e of t.compositeIdentifiers?.fields??[]){const o=e.components.map((e=>{const o=t.fieldConfigs?.find((t=>t.targetFieldKey===e));return{name:e,alias:o?.alias}}));r.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:o})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:r.length>0?r:void 0}};class q extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,q)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class K extends q{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class U extends q{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class $ extends q{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class P extends q{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const D=(t,r)=>{const n=t?.next,s=o.notMissing(n)&&"list"===r.operationType?e.expandCursor(n):void 0;if(null===s)throw new P(r,"Invalid cursor.");return s};exports.ConnectSDKError=q,exports.createBlock=f,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=z,exports.parseOperationInputs=w,exports.parseYamlConnector=E,exports.runConnectorOperation=async({account:e,connector:t,category:r,path:n,method:s="get",queryParams:i,body:a,headers:c,logger:u,parseConnector:p=E,getOperationFromUrlFn:d=z,parseOperationInputsFn:l=w,createBlockContextFn:g=h,createBlockFn:m=f,runStepOperationFn:b=y})=>{const _=e.authConfigKey,C=e.environment??"production",v=e.secureId,I=e.projectSecureId,S=e.credentials,k=g({category:r,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:C,accountSecureId:v,projectSecureId:I});let O;try{O=o.isString(t)?p(t):t}catch{throw new K(k,"Error while parsing connector")}const F=d(O,n,s);if(o.isMissing(F))throw new U(k,"No matching operation found");k.operationType=F.operation.operationType,k.schema=F.operation.schema?.key;const x=D(i,k);let T;try{T=l(F.operation,{query:i,body:a,headers:c,path:F.params})}catch{throw new $(k,"Error while parsing operation inputs")}const j=await m({inputs:T,context:k,operation:F.operation,credentials:S,nextCursor:x,logger:u});return await b({block:j})},exports.runStepOperation=y;
|