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