@stackone/connect-sdk 1.56.0 → 1.56.2

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.js CHANGED
@@ -3,4 +3,4 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
3
3
  `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},v=(e,t)=>{let n=[];for(let r of e)if(y(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=b(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},y=e=>e.includes(`$ref:`),b=(e,t)=>{let n=(0,u.resolve)((0,u.join)(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=(0,l.readFileSync)(n,`utf8`);return e.split(`
4
4
  `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},x=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.keys(e.operations),a=C(t,r,i);if(a)return{operation:e.operations?.[a.path],params:a.params}},S=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},C=(e,t,n)=>{let r=S(e);for(let e of n)if(e.startsWith(t)){let n=e.replace(`${t} `,``).trim(),i=(0,d.match)(S(n)),a=i(S(r));if(a!==!1)return{path:e,params:a.params}}},w=(e,t)=>{let n=Object.keys(e.operations??{}).find(n=>e.operations?.[n]?.id===t);if((0,c.notMissing)(n))return e.operations?.[n]};var T=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},E=class extends T{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},D=class extends T{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},O=class extends T{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},k=class extends T{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const A=25,ee=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},te=()=>{let e={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.`}};return e},j={key:c.z.string(),label:c.z.string(),required:c.z.boolean().optional().default(!1),secret:c.z.boolean().optional().default(!1),readOnly:c.z.boolean().optional().default(!1),placeholder:c.z.string().optional(),description:c.z.string().optional(),tooltip:c.z.string().optional()},M=c.z.discriminatedUnion(`type`,[(0,c.zStrictObject)({...j,type:c.z.enum([`text`,`password`])}),(0,c.zStrictObject)({...j,type:c.z.literal(`select`),options:(0,c.zStrictObject)({value:c.z.string(),label:c.z.string()}).array()})]),N=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.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((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>N).array().optional()}),P=(0,c.zStrictObject)({name:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:c.z.boolean(),description:c.z.string(),array:c.z.boolean().optional().default(!1),in:c.z.enum([`body`,`query`,`path`,`headers`]),properties:c.z.lazy(()=>P.omit({in:!0})).array().optional()}),F=(0,c.zStrictObject)({operationId:c.z.string(),categories:c.z.string().array(),operationType:c.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:c.z.string().optional(),schemaType:c.z.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:c.z.string().optional(),entrypointHttpMethod:c.z.string().optional(),label:c.z.string(),description:c.z.string(),tags:c.z.string().array().optional(),context:c.z.string().optional(),responses:(0,c.zStrictObject)({statusCode:c.z.number(),description:c.z.string()}).array().optional(),inputs:P.array().optional(),cursor:(0,c.zStrictObject)({enabled:c.z.boolean(),pageSize:c.z.number()}).optional(),compositeIdentifiers:(0,c.zStrictObject)({enabled:c.z.boolean(),version:c.z.number().optional(),fields:(0,c.zStrictObject)({targetFieldKey:c.z.string(),remote:c.z.string().optional(),components:c.z.string().array()}).array().optional()}).optional(),scheduledJobs:(0,c.zStrictObject)({enabled:c.z.boolean(),type:c.z.enum([`data_sync`]),schedule:c.z.string(),description:c.z.string(),requestParams:(0,c.zStrictObject)({fields:c.z.string().array().optional(),expand:c.z.string().array().optional(),filter:c.z.record(c.z.string(),c.z.string()).optional()}).optional(),syncFilter:(0,c.zStrictObject)({name:c.z.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:c.z.string(),incrementalLoopbackPeriod:c.z.string()}).optional()}).array().optional(),fieldConfigs:N.array().optional(),steps:(0,c.zStrictObject)({stepId:c.z.string(),description:c.z.string(),stepFunction:(0,c.zStrictObject)({functionName:c.z.string(),version:c.z.string().optional(),parameters:c.z.record(c.z.string(),c.z.unknown())}),condition:c.z.string().optional(),ignoreError:c.z.boolean().optional()}).array(),result:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).optional()}),ne=(0,c.zStrictObject)({schedule:c.z.string().optional(),operation:F.extend({operationType:c.z.literal(`refresh_token`)})}),re=(0,c.zStrictObject)({mainRatelimit:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),rateLimit:c.z.number()})).optional(),mappedRateLimitErrors:c.z.array((0,c.zStrictObject)({errorStatus:c.z.number(),errorMessage:c.z.string(),errorMessagePath:c.z.string().optional(),retryAfterPath:c.z.string().optional(),retryAfterUnit:c.z.union([c.z.literal(`seconds`),c.z.literal(`milliseconds`),c.z.literal(`date`)]).optional(),retryAfterValue:c.z.number().optional()})).optional()}),ie=(0,c.zStrictObject)({mainMaxConcurrency:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),maxConcurrency:c.z.number()})).optional()}),ae=(0,c.zStrictObject)({StackOne:c.z.string(),info:(0,c.zStrictObject)({title:c.z.string(),version:c.z.string(),key:c.z.string(),assets:(0,c.zStrictObject)({icon:c.z.string()}),description:c.z.string().optional()}),context:c.z.string().optional(),baseUrl:c.z.string(),authentication:c.z.record(c.z.string(),(0,c.zStrictObject)({type:c.z.string(),label:c.z.string(),authorization:f.AUTHENTICATION_SCHEMA,environments:(0,c.zStrictObject)({key:c.z.string(),name:c.z.string()}).array(),support:(0,c.zStrictObject)({link:c.z.string(),description:c.z.string().optional()}),configFields:M.array().optional(),setupFields:M.array().optional(),refreshAuthentication:ne.optional(),testOperations:(0,c.zStrictObject)({operation:c.z.string().or(F),condition:c.z.string().optional(),required:c.z.boolean().default(!0)}).array().optional()})).array().optional(),operations:F.array().optional(),rateLimit:re.optional(),concurrency:ie.optional()}).strict();function I(e){try{let t=(0,m.parse)(e),n=xe(ae,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},i=ce(n),a={baseUrl:n.baseUrl,authentication:L(i)},o=me(n,a);return r.operations=o,oe(i,o,a),r.authentication=i,(0,c.notMissing)(o)&&(r.categories=se(Object.values(o))),r}catch(e){if(e instanceof T)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new E(r,t)}}const L=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=L(c)}else t[n]=r;return t},oe=(e,t,n)=>{if(!(!e||!t))for(let r of Object.values(e))for(let e of Object.values(r)){let r=e.testOperations;e.testOperations=r?.map(e=>{if((0,c.notMissing)(e.operation))if(typeof e.operation==`string`){let n=e.operation,r=Object.values(t).find(e=>e.id===n);if(r)return{...e,operation:r}}else{let t=R(e.operation,n);return{...e,operation:t}}return e})}},se=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},ce=e=>{let t={};for(let n of e.authentication??[]){let[e]=Object.keys(n),r=n[e].environments.reduce((t,r)=>{let{key:i,name:a}=r,{environments:o,refreshAuthentication:s,testOperations:l,...u}=n[e],d=(0,c.notMissing)(s)?{schedule:s.schedule,operation:R(s.operation)}:void 0;return t[i]={...u,refreshAuthentication:d,envKey:i,envName:a,testOperations:l},t},{});t[e]=r}return t},le=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,ue=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,de=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},fe=e=>{if(!(e.operationType===`refresh_token`||(0,c.isMissing)(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},pe=e=>{let t={success:ee(e.operationType),errors:te()},n=e.responses?.reduce((e,t)=>{let n=(0,p.isSuccessStatusCode)(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},me=(e,t)=>{let n=e.operations?.reduce((e,n)=>{let r=le(n),i=ue(n);return e[r??i]=R(n,t),e},{});return n},R=(e,t)=>{let n=fe(e),r=pe(e),i=_e(e),a=e.inputs||[];i.enabled&&a?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1});let o=de(e);return{id:e.operationId,categories:e.categories,label:e.label,description:e.description,operationType:e.operationType,schemaType:e.schemaType??`native`,entrypointUrl:e.entrypointUrl??n,entrypointHttpMethod:o,tags:e.tags,context:e.context,responses:r,cursor:i,compositeIdentifiers:ve(e),scheduledJobs:ye(e),inputs:a,steps:e.steps.reduce((n,r)=>{let i={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...r.stepFunction.parameters,...be(r.stepFunction.functionName,t,r.stepFunction.parameters),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:r.stepFunction.parameters.fields??e.fieldConfigs}:{}}}};return he(e.operationId,i),n[r.stepId]=i,n},{}),result:e.result}},he=(e,t)=>{let n=t.stepFunction.version??`1`,r=f.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new O(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Se(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},z=(e,t)=>{if(!e.inputs)return{};let n=ge(e.inputs),r=n.parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},B=e=>{let t={};return e.forEach(e=>{let n;switch(e.type.toLowerCase()){case`string`:n=c.z.string();break;case`number`:n=c.z.number();break;case`boolean`:n=c.z.boolean();break;case`datetime_string`:n=c.z.string().refine(e=>!isNaN(Date.parse(e)),{message:`Invalid datetime string`});break;case`object`:n=e.properties?B(e.properties):c.z.record(c.z.string(),c.z.any());break;default:n=c.z.any()}let r=e.array?c.z.array(n):n;t[e.name]=e.required?r:r.optional()}),c.z.object(t)},ge=e=>{let t=e.filter(e=>e.in===`path`),n=e.filter(e=>e.in===`query`),r=e.filter(e=>e.in===`body`),i=e.filter(e=>e.in===`headers`);return c.z.object({path:B(t).optional(),query:B(n).optional(),body:B(r).optional(),headers:B(i).optional()})},_e=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:A};return{enabled:n.enabled&&t,pageSize:n.pageSize}},ve=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if((0,c.isMissing)(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=(0,c.notMissing)(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:f.COMPOSITE_ID_LATEST_VERSION,fields:n}}let t=[];for(let n of e.compositeIdentifiers?.fields??[]){let r=n.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});t.push({targetFieldKey:n.targetFieldKey,remote:n.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},ye=e=>{if(!(0,c.isMissing)(e.scheduledJobs))return e.scheduledJobs},be=(e,t,n={})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n.customErrors&&Array.isArray(n.customErrors)?n.customErrors:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},xe=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new D(e,`Invalid connector schema`)}},Se=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new k(n,r,i,a,e)}},V=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if((0,c.notMissing)(r))return{operation:r,params:{}}},Ce=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=V(e,t,n);return(0,c.notMissing)(r)},we=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Te=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Ee=e=>{try{return I(e),{success:!0}}catch(t){if(t instanceof D){let n=t.issues,r=[];return n.forEach(t=>{let n=t?.keys?.[0],i=(0,c.isMissing)(n)?t.path:[...t.path,n],a=De(i,e);r.push({line:a,message:t.message,field:i.join(`.`)})}),{success:!1,errors:r}}else if(t instanceof E)return{success:!1,errors:[{line:t.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(t instanceof O){let n=H(t.operationId,t.stepId,t.functionName,!1,e);return{success:!1,errors:[{line:n,message:t.message,field:void 0}]}}else if(t instanceof k){let n=t.issues,r=[];return n.forEach(n=>{let i=n?.keys?.[0],a=(0,c.isMissing)(i)?n.path:[...n.path,i],o=H(t.operationId,t.stepId,t.functionName,!0,e);r.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:r}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},De=(e,t)=>{let n=t.split(`
5
5
  `),r=0,i=-1,a=0;for(let t=0;t<n.length;t++){let o=n[t],s=o.match(/^(\s*)/)?.[1]?.length||0,l=o.replace(`- `,``).trim();if(l.startsWith(`#`)||l===``||s<=i)continue;let u=(0,c.notMissing)(e[r])?`${String(e[r])}`:``;if((0,c.isMissing)(u))return a+1;if(isNaN(Number(u))){if(l.startsWith(`${u}:`)){if(r===e.length-1)return t+1;i=s,a=t,r++}}else{let e=parseInt(u,10),i=-1;for(let o=t;o<n.length;o++){let s=n[o],c=s.trim();if(c.startsWith(`-`)&&i++,i===e){r++,a=t,t--;break}else t++}}}return a+1},H=(e,t,n,r,i)=>{let a=i.split(`
6
- `),o=1,s=null,l=null;for(let i=0;i<a.length;i++){let u=a[i],d=u.trim();if((0,c.isMissing)(s)&&d===`- operationId: ${e}`){s=e,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.isMissing)(l)&&d===`- stepId: ${t}`){l=t,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.notMissing)(l)&&!r&&d.startsWith(`functionName: ${n}`)||(0,c.notMissing)(s)&&(0,c.notMissing)(l)&&r&&d===`parameters:`)return o=i+1,o}return o};var U=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},W=class extends U{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},G=class extends U{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},K=class extends U{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},q=class extends U{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Oe=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.description,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},ke=(e,t)=>e.map(e=>Oe(e,t)),Ae=`stackone://internal//`,je=`${Ae}refresh_token`,Me=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=f.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===f.StepFunctionName.MAP_FIELDS?{[f.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},J=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ne=e=>{let t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||(0,c.isMissing)(n))return e;let r=t.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),i={version:t.version??f.COMPOSITE_ID_LATEST_VERSION,aliases:r};return Y(n,i,e.logger),{...e,inputs:n}},Y=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))ze(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)Y(e,t,n);else typeof i==`object`&&i&&Y(i,t,n)}},Pe=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,f.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Fe=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Ie=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},Le=(e,t,n,r,i)=>{n.every(Ie)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},Re=(e,t,n)=>{e instanceof f.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},ze=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=Pe(o,t,r,i);Fe(n,t,s,a),Le(n,t,s,c,a)}catch(e){Re(e,t,i)}},X=`remote_`,Be=e=>{let t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;let n=`data`,r=e.outputs?.[n];if((0,c.isMissing)(r))return e;let i=Array.isArray(r)?r.map(e=>Ve(e,t)):Ve(r,t);return{...e,outputs:{...e.outputs??{},[n]:i}}},Ve=(e,t)=>{let n=He(e,t),r=Z(n);return{...e,...(0,c.isObject)(r)?r:{}}},He=(e,t)=>{let n=t.version??f.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=(0,f.encodeCompositeId)(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${X}${t.remote}`]=e[t.remote])}),{...e,...r}},Ue=e=>e===`id`||/.+_id(s)?$/.test(e),We=e=>Array.isArray(e)&&e.every(e=>(0,c.isString)(e)&&e.length>0),Ge=(e,t)=>(0,f.isCompositeId)(e)||t.startsWith(X),Ke=(e,t)=>{try{return(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},qe=(e,t,n)=>{let r=t.map(t=>(0,c.isString)(t)&&t.length>0&&!(0,f.isCompositeId)(t)?Ke(e,t):t);n[e]=r,n[`${X}${e}`]=t},Je=(e,t,n)=>{if(Ge(t,e))return;let r=(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION});n[e]=r,n[`remote_${e}`]=t},Ye=(e,t,n)=>{We(t)?qe(e,t,n):(0,c.isString)(t)&&t.length>0&&Je(e,t,n)},Z=e=>{if(Array.isArray(e))return e.map(e=>Z(e));if(!(0,c.isObject)(e))return e;let t={...e};for(let[n,r]of Object.entries(e))((0,c.isObject)(r)||Array.isArray(r)&&r.length>0&&(0,c.isObject)(r[0]))&&(t[n]=Z(r)),Ue(n)&&Ye(n,r,t);return t},Xe=(e,t)=>{let n=Number(e.inputs?.page_size),r=(0,c.notMissing)(e.inputs?.page_size)&&(0,c.isNumber)(n)&&!Number.isNaN(n)?n:e.operation?.cursor?.pageSize??t;return r},Ze=(e,t,n,r)=>{let i=(0,c.isMissing)(e)?void 0:e.data,a=Object.keys(n).length+1,o=(0,f.isCursorEmpty)({cursor:r,ignoreStepIndex:a});if(!(0,c.isObject)(e)||(0,c.isMissing)(i)||(i?.length??0)<=t)return{result:e,next:(0,c.notMissing)(r)&&!o?(0,f.minifyCursor)(r):null};let s=r?.remote?.[a]?.pageNumber??1,l=(s-1)*t,u=l+t,d=i.slice(l,u),p=i.length>u||!o,m=(0,f.updateCursor)({cursor:r,stepIndex:a,pageNumber:s+1});return{result:{...e,data:d},next:p?(0,f.minifyCursor)(m):null}},Q=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=Ze,encodeResultCompositeIds:r=Be,decodeInputCompositeIds:i=Ne})=>{let a=i(e),o=await rt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},Qe=(e,t)=>e.condition?!(0,h.safeEvaluate)(e.condition,t):!1,$e=(e,t,n)=>{let r=e.stepFunction;return t.operation?.cursor.enabled?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},et=(e,t,n,r,i)=>{let a=$({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},tt=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(Qe(o,r))return $({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return $({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=$e(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return et(r,e,u,o,i);let d=r.operation?.cursor.enabled?(0,f.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return $({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},nt=(e,t,n,r,i)=>{let a=!n.hasFatalError,o=a?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,s=(0,c.notMissing)(i)&&(0,c.isObject)(i.result)?{next:i.next,...i.result}:r;return{...t,outputs:s,response:{successful:a,statusCode:o,message:a?void 0:e.operation?.responses?.errors?.[o]?.description??p.HttpErrorMessages?.[o]??`Error while processing the request`}}},rt=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=Ze})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=Xe(e,A),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await tt(t,e,r,i,s,c);let l=e.operation?.result?it(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return nt(e,i,s,l,u)},it=(e,t)=>(0,c.isObject)(e)?(0,h.safeEvaluateRecord)(e,t):(0,h.safeEvaluate)(e,t),$=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),at=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:l,parseConnector:u=I,parseOperationInputsFn:d=z,createBlockContextFn:f=J,createBlockFn:p=g,runStepOperationFn:m=Q})=>{let h=t.authConfigKey,_=t.environment??`production`,v=t.secureId,y=t.projectSecureId,b=t.credentials,x=f({category:`action`,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:h,environment:_,accountSecureId:v,projectSecureId:y}),S;try{S=(0,c.isString)(n)?u(n):n}catch{throw new W(x,`Error while parsing connector`)}let C=w(n,e);if((0,c.isMissing)(C))throw new G(x,`No matching operation found`);x.operationType=C.operationType,x.schema=C.schema?.key;let T=ot(i,x),E;try{E=d(C,{path:r,query:i,body:a,headers:o})}catch{throw new K(x,`Error while parsing operation inputs`)}let D=await p({connector:S,inputs:E,context:x,operation:C,credentials:b,nextCursor:T,logger:s,getHttpClient:l});return await m({block:D})},ot=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new q(t,`Invalid cursor.`);return r},st=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:l,getHttpClient:u,parseConnector:d=I,getOperationFromUrlFn:f=x,getOperationForRefreshAuthenticationFn:p=V,parseOperationInputsFn:m=z,createBlockContextFn:h=J,createBlockFn:_=g,runStepOperationFn:v=Q})=>{let y=e.authConfigKey,b=e.environment??`production`,S=e.secureId,C=e.projectSecureId,w=e.credentials,T=h({category:n,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:y,environment:b,accountSecureId:S,projectSecureId:C}),E;try{E=(0,c.isString)(t)?d(t):t}catch{throw new W(T,`Error while parsing connector`)}let D=lt(r)?p(E,y,b):f(E,r,i);if((0,c.isMissing)(D))throw new G(T,`No matching operation found`);T.operationType=D.operation.operationType,T.schema=D.operation.schema?.key;let O=ct(a,T),k;try{k=m(D.operation,{query:a,body:o,headers:s,path:D.params})}catch{throw new K(T,`Error while parsing operation inputs`)}let A=await _({connector:E,inputs:k,context:T,operation:D.operation,credentials:w,nextCursor:O,logger:l,getHttpClient:u});return await v({block:A})},ct=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new q(t,`Invalid cursor.`);return r},lt=e=>e===je,ut=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,dt=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=I,getTestOperationsFn:a=ut,createBlockContextFn:o=J,createBlockFn:s=g,runStepOperationFn:l=Q})=>{let u=e.authConfigKey,d=e.environment??`production`,f=e.secureId,p=e.projectSecureId,m=e.credentials,_=o({category:`internal`,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:u,environment:d,accountSecureId:f,projectSecureId:p}),v;try{v=(0,c.isString)(t)?i(t):t}catch{throw new W(_,`Error while parsing connector`)}let y=a(v,u,d);if((0,c.isMissing)(y)||y.length===0)return!0;_.operationType=`test`;for(let e of y){let t=await s({connector:v,inputs:void 0,context:_,operation:e.operation,credentials:m,nextCursor:void 0,logger:n,getHttpClient:r}),i=(0,c.notMissing)(e.condition)?(0,h.evaluate)(e.condition,t):!0;if(!i)continue;let a=await l({block:t});if(((0,c.isMissing)(a?.response?.successful)||!a.response.successful)&&e.required)return n?.error({code:`TestOperationFailed`,message:`Test operation "${e.operation.id}" failed with error: ${a?.response?.message}`}),!1}return!0};exports.ConnectSDKError=U,exports.REFRESH_TOKEN_OPERATION_PATH=je,exports.buildActionsMetaFromConfig=Oe,exports.createBlock=g,exports.executeStepFunction=Me,exports.getActionsMetaFromConfigs=ke,exports.getOperationFromUrl=x,exports.getRefreshTokenExpiresIn=Te,exports.getTokenExpiresIn=we,exports.loadConnector=_,exports.parseOperationInputs=z,exports.parseYamlConnector=I,exports.runConnectorAction=at,exports.runConnectorOperation=st,exports.runStepOperation=Q,exports.runTestOperations=dt,exports.supportsRefreshAuthentication=Ce,exports.validateYamlConnector=Ee;
6
+ `),o=1,s=null,l=null;for(let i=0;i<a.length;i++){let u=a[i],d=u.trim();if((0,c.isMissing)(s)&&d===`- operationId: ${e}`){s=e,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.isMissing)(l)&&d===`- stepId: ${t}`){l=t,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.notMissing)(l)&&!r&&d.startsWith(`functionName: ${n}`)||(0,c.notMissing)(s)&&(0,c.notMissing)(l)&&r&&d===`parameters:`)return o=i+1,o}return o};var U=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},W=class extends U{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},G=class extends U{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},K=class extends U{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},q=class extends U{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Oe=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.description,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},ke=(e,t)=>e.map(e=>Oe(e,t)),Ae=`stackone://internal//`,je=`${Ae}refresh_token`,Me=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=f.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===f.StepFunctionName.MAP_FIELDS?{[f.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},J=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ne=e=>{let t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||(0,c.isMissing)(n))return e;let r=t.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),i={version:t.version??f.COMPOSITE_ID_LATEST_VERSION,aliases:r};return Y(n,i,e.logger),{...e,inputs:n}},Y=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))ze(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)Y(e,t,n);else typeof i==`object`&&i&&Y(i,t,n)}},Pe=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,f.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Fe=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Ie=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},Le=(e,t,n,r,i)=>{n.every(Ie)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},Re=(e,t,n)=>{e instanceof f.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},ze=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=Pe(o,t,r,i);Fe(n,t,s,a),Le(n,t,s,c,a)}catch(e){Re(e,t,i)}},X=`remote_`,Be=e=>{let t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;let n=`data`,r=e.outputs?.[n];if((0,c.isMissing)(r))return e;let i=Array.isArray(r)?r.map(e=>Ve(e,t)):Ve(r,t);return{...e,outputs:{...e.outputs??{},[n]:i}}},Ve=(e,t)=>{let n=He(e,t),r=Z(n);return{...e,...(0,c.isObject)(r)?r:{}}},He=(e,t)=>{let n=t.version??f.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=(0,f.encodeCompositeId)(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${X}${t.remote}`]=e[t.remote])}),{...e,...r}},Ue=e=>e===`id`||/.+_id(s)?$/.test(e),We=e=>Array.isArray(e)&&e.every(e=>(0,c.isString)(e)&&e.length>0),Ge=(e,t)=>(0,f.isCompositeId)(e)||t.startsWith(X),Ke=(e,t)=>{try{return(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},qe=(e,t,n)=>{let r=t.map(t=>(0,c.isString)(t)&&t.length>0&&!(0,f.isCompositeId)(t)?Ke(e,t):t);n[e]=r,n[`${X}${e}`]=t},Je=(e,t,n)=>{if(Ge(t,e))return;let r=(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION});n[e]=r,n[`remote_${e}`]=t},Ye=(e,t,n)=>{We(t)?qe(e,t,n):(0,c.isString)(t)&&t.length>0&&Je(e,t,n)},Z=e=>{if(Array.isArray(e))return e.map(e=>Z(e));if(!(0,c.isObject)(e))return e;let t={...e};for(let[n,r]of Object.entries(e))((0,c.isObject)(r)||Array.isArray(r)&&r.length>0&&(0,c.isObject)(r[0]))&&(t[n]=Z(r)),Ue(n)&&Ye(n,r,t);return t},Xe=(e,t)=>{let n=Number(e.inputs?.page_size),r=(0,c.notMissing)(e.inputs?.page_size)&&(0,c.isNumber)(n)&&!Number.isNaN(n)?n:e.operation?.cursor?.pageSize??t;return r},Ze=(e,t,n,r)=>{let i=(0,c.isMissing)(e)?void 0:e.data,a=Object.keys(n).length+1,o=(0,f.isCursorEmpty)({cursor:r,ignoreStepIndex:a});if(!(0,c.isObject)(e)||(0,c.isMissing)(i)||(i?.length??0)<=t)return{result:e,next:(0,c.notMissing)(r)&&!o?(0,f.minifyCursor)(r):null};let s=r?.remote?.[a]?.pageNumber??1,l=(s-1)*t,u=l+t,d=i.slice(l,u),p=i.length>u||!o,m=(0,f.updateCursor)({cursor:r,stepIndex:a,pageNumber:s+1});return{result:{...e,data:d},next:p?(0,f.minifyCursor)(m):null}},Q=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=Ze,encodeResultCompositeIds:r=Be,decodeInputCompositeIds:i=Ne})=>{let a=i(e),o=await rt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},Qe=(e,t)=>e.condition?!(0,h.safeEvaluate)(e.condition,t):!1,$e=(e,t,n)=>{let r=e.stepFunction,i=f.StepFunctionsRegistry[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],a=(0,c.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&a?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},et=(e,t,n,r,i)=>{let a=$({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},tt=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(Qe(o,r))return $({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return $({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=$e(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return et(r,e,u,o,i);let d=r.operation?.cursor.enabled?(0,f.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return $({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},nt=(e,t,n,r,i)=>{let a=!n.hasFatalError,o=a?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,s=(0,c.notMissing)(i)&&(0,c.isObject)(i.result)?{next:i.next,...i.result}:r;return{...t,outputs:s,response:{successful:a,statusCode:o,message:a?void 0:e.operation?.responses?.errors?.[o]?.description??p.HttpErrorMessages?.[o]??`Error while processing the request`}}},rt=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=Ze})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=Xe(e,A),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await tt(t,e,r,i,s,c);let l=e.operation?.result?it(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return nt(e,i,s,l,u)},it=(e,t)=>(0,c.isObject)(e)?(0,h.safeEvaluateRecord)(e,t):(0,h.safeEvaluate)(e,t),$=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),at=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:l,parseConnector:u=I,parseOperationInputsFn:d=z,createBlockContextFn:f=J,createBlockFn:p=g,runStepOperationFn:m=Q})=>{let h=t.authConfigKey,_=t.environment??`production`,v=t.secureId,y=t.projectSecureId,b=t.credentials,x=f({category:`action`,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:h,environment:_,accountSecureId:v,projectSecureId:y}),S;try{S=(0,c.isString)(n)?u(n):n}catch{throw new W(x,`Error while parsing connector`)}let C=w(n,e);if((0,c.isMissing)(C))throw new G(x,`No matching operation found`);x.operationType=C.operationType,x.schema=C.schema?.key;let T=ot(i,x),E;try{E=d(C,{path:r,query:i,body:a,headers:o})}catch{throw new K(x,`Error while parsing operation inputs`)}let D=await p({connector:S,inputs:E,context:x,operation:C,credentials:b,nextCursor:T,logger:s,getHttpClient:l});return await m({block:D})},ot=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new q(t,`Invalid cursor.`);return r},st=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:l,getHttpClient:u,parseConnector:d=I,getOperationFromUrlFn:f=x,getOperationForRefreshAuthenticationFn:p=V,parseOperationInputsFn:m=z,createBlockContextFn:h=J,createBlockFn:_=g,runStepOperationFn:v=Q})=>{let y=e.authConfigKey,b=e.environment??`production`,S=e.secureId,C=e.projectSecureId,w=e.credentials,T=h({category:n,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:y,environment:b,accountSecureId:S,projectSecureId:C}),E;try{E=(0,c.isString)(t)?d(t):t}catch{throw new W(T,`Error while parsing connector`)}let D=lt(r)?p(E,y,b):f(E,r,i);if((0,c.isMissing)(D))throw new G(T,`No matching operation found`);T.operationType=D.operation.operationType,T.schema=D.operation.schema?.key;let O=ct(a,T),k;try{k=m(D.operation,{query:a,body:o,headers:s,path:D.params})}catch{throw new K(T,`Error while parsing operation inputs`)}let A=await _({connector:E,inputs:k,context:T,operation:D.operation,credentials:w,nextCursor:O,logger:l,getHttpClient:u});return await v({block:A})},ct=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new q(t,`Invalid cursor.`);return r},lt=e=>e===je,ut=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,dt=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=I,getTestOperationsFn:a=ut,createBlockContextFn:o=J,createBlockFn:s=g,runStepOperationFn:l=Q})=>{let u=e.authConfigKey,d=e.environment??`production`,f=e.secureId,p=e.projectSecureId,m=e.credentials,_=o({category:`internal`,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:u,environment:d,accountSecureId:f,projectSecureId:p}),v;try{v=(0,c.isString)(t)?i(t):t}catch{throw new W(_,`Error while parsing connector`)}let y=a(v,u,d);if((0,c.isMissing)(y)||y.length===0)return!0;_.operationType=`test`;for(let e of y){let t=await s({connector:v,inputs:void 0,context:_,operation:e.operation,credentials:m,nextCursor:void 0,logger:n,getHttpClient:r}),i=(0,c.notMissing)(e.condition)?(0,h.evaluate)(e.condition,t):!0;if(!i)continue;let a=await l({block:t});if(((0,c.isMissing)(a?.response?.successful)||!a.response.successful)&&e.required)return n?.error({code:`TestOperationFailed`,message:`Test operation "${e.operation.id}" failed with error: ${a?.response?.message}`}),!1}return!0};exports.ConnectSDKError=U,exports.REFRESH_TOKEN_OPERATION_PATH=je,exports.buildActionsMetaFromConfig=Oe,exports.createBlock=g,exports.executeStepFunction=Me,exports.getActionsMetaFromConfigs=ke,exports.getOperationFromUrl=x,exports.getRefreshTokenExpiresIn=Te,exports.getTokenExpiresIn=we,exports.loadConnector=_,exports.parseOperationInputs=z,exports.parseYamlConnector=I,exports.runConnectorAction=at,exports.runConnectorOperation=st,exports.runStepOperation=Q,exports.runTestOperations=dt,exports.supportsRefreshAuthentication=Ce,exports.validateYamlConnector=Ee;
package/dist/index.mjs CHANGED
@@ -3,4 +3,4 @@ import{isMissing as e,isNumber as t,isObject as n,isString as r,notMissing as i,
3
3
  `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},re=(e,t)=>{let n=[];for(let r of e)if(ie(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=ae(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},ie=e=>e.includes(`$ref:`),ae=(e,t)=>{let n=u(l(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=s(n,`utf8`);return e.split(`
4
4
  `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},oe=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.keys(e.operations),a=se(t,r,i);if(a)return{operation:e.operations?.[a.path],params:a.params}},A=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},se=(e,t,n)=>{let r=A(e);for(let e of n)if(e.startsWith(t)){let n=e.replace(`${t} `,``).trim(),i=d(A(n)),a=i(A(r));if(a!==!1)return{path:e,params:a.params}}},ce=(e,t)=>{let n=Object.keys(e.operations??{}).find(n=>e.operations?.[n]?.id===t);if(i(n))return e.operations?.[n]};var j=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},le=class extends j{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},M=class extends j{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},N=class extends j{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},P=class extends j{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const F=25,ue=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`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},de=()=>{let e={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.`}};return e},fe={key:a.string(),label:a.string(),required:a.boolean().optional().default(!1),secret:a.boolean().optional().default(!1),readOnly:a.boolean().optional().default(!1),placeholder:a.string().optional(),description:a.string().optional(),tooltip:a.string().optional()},pe=a.discriminatedUnion(`type`,[o({...fe,type:a.enum([`text`,`password`])}),o({...fe,type:a.literal(`select`),options:o({value:a.string(),label:a.string()}).array()})]),me=o({targetFieldKey:a.string(),alias:a.string().optional(),expression:a.string().optional(),values:a.unknown().optional(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:a.boolean().default(!1),custom:a.boolean().default(!1),hidden:a.boolean().default(!1),enumMapper:o({matcher:a.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(o({matchExpression:a.string(),value:a.string()}).array())}).optional(),properties:a.lazy(()=>me).array().optional()}),he=o({name:a.string(),type:a.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:a.boolean(),description:a.string(),array:a.boolean().optional().default(!1),in:a.enum([`body`,`query`,`path`,`headers`]),properties:a.lazy(()=>he.omit({in:!0})).array().optional()}),I=o({operationId:a.string(),categories:a.string().array(),operationType:a.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:a.string().optional(),schemaType:a.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:a.string().optional(),entrypointHttpMethod:a.string().optional(),label:a.string(),description:a.string(),tags:a.string().array().optional(),context:a.string().optional(),responses:o({statusCode:a.number(),description:a.string()}).array().optional(),inputs:he.array().optional(),cursor:o({enabled:a.boolean(),pageSize:a.number()}).optional(),compositeIdentifiers:o({enabled:a.boolean(),version:a.number().optional(),fields:o({targetFieldKey:a.string(),remote:a.string().optional(),components:a.string().array()}).array().optional()}).optional(),scheduledJobs:o({enabled:a.boolean(),type:a.enum([`data_sync`]),schedule:a.string(),description:a.string(),requestParams:o({fields:a.string().array().optional(),expand:a.string().array().optional(),filter:a.record(a.string(),a.string()).optional()}).optional(),syncFilter:o({name:a.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:a.string(),incrementalLoopbackPeriod:a.string()}).optional()}).array().optional(),fieldConfigs:me.array().optional(),steps:o({stepId:a.string(),description:a.string(),stepFunction:o({functionName:a.string(),version:a.string().optional(),parameters:a.record(a.string(),a.unknown())}),condition:a.string().optional(),ignoreError:a.boolean().optional()}).array(),result:a.string().or(a.record(a.string(),a.unknown())).optional()}),ge=o({schedule:a.string().optional(),operation:I.extend({operationType:a.literal(`refresh_token`)})}),_e=o({mainRatelimit:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),rateLimit:a.number()})).optional(),mappedRateLimitErrors:a.array(o({errorStatus:a.number(),errorMessage:a.string(),errorMessagePath:a.string().optional(),retryAfterPath:a.string().optional(),retryAfterUnit:a.union([a.literal(`seconds`),a.literal(`milliseconds`),a.literal(`date`)]).optional(),retryAfterValue:a.number().optional()})).optional()}),ve=o({mainMaxConcurrency:a.number(),subPools:a.array(o({subPoolKey:a.string(),urlPattern:a.string(),maxConcurrency:a.number()})).optional()}),ye=o({StackOne:a.string(),info:o({title:a.string(),version:a.string(),key:a.string(),assets:o({icon:a.string()}),description:a.string().optional()}),context:a.string().optional(),baseUrl:a.string(),authentication:a.record(a.string(),o({type:a.string(),label:a.string(),authorization:f,environments:o({key:a.string(),name:a.string()}).array(),support:o({link:a.string(),description:a.string().optional()}),configFields:pe.array().optional(),setupFields:pe.array().optional(),refreshAuthentication:ge.optional(),testOperations:o({operation:a.string().or(I),condition:a.string().optional(),required:a.boolean().default(!0)}).array().optional()})).array().optional(),operations:I.array().optional(),rateLimit:_e.optional(),concurrency:ve.optional()}).strict();function L(e){try{let t=ee(e),n=Ie(ye,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},a=Ce(n),o={baseUrl:n.baseUrl,authentication:be(a)},s=ke(n,o);return r.operations=s,xe(a,s,o),r.authentication=a,i(s)&&(r.categories=Se(Object.values(s))),r}catch(e){if(e instanceof j)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new le(r,t)}}const be=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=be(c)}else t[n]=r;return t},xe=(e,t,n)=>{if(!(!e||!t))for(let r of Object.values(e))for(let e of Object.values(r)){let r=e.testOperations;e.testOperations=r?.map(e=>{if(i(e.operation))if(typeof e.operation==`string`){let n=e.operation,r=Object.values(t).find(e=>e.id===n);if(r)return{...e,operation:r}}else{let t=R(e.operation,n);return{...e,operation:t}}return e})}},Se=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},Ce=e=>{let t={};for(let n of e.authentication??[]){let[e]=Object.keys(n),r=n[e].environments.reduce((t,r)=>{let{key:a,name:o}=r,{environments:s,refreshAuthentication:c,testOperations:l,...u}=n[e],d=i(c)?{schedule:c.schedule,operation:R(c.operation)}:void 0;return t[a]={...u,refreshAuthentication:d,envKey:a,envName:o,testOperations:l},t},{});t[e]=r}return t},we=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,Te=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,Ee=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},De=t=>{if(!(t.operationType===`refresh_token`||e(t.schema)))return t.operationType===`list`?`/${t.schema}`:`/${t.schema}/:id`},Oe=e=>{let t={success:ue(e.operationType),errors:de()},n=e.responses?.reduce((e,t)=>{let n=E(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},ke=(e,t)=>{let n=e.operations?.reduce((e,n)=>{let r=we(n),i=Te(n);return e[r??i]=R(n,t),e},{});return n},R=(e,t)=>{let n=De(e),r=Oe(e),i=Me(e),a=e.inputs||[];i.enabled&&a?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1});let o=Ee(e);return{id:e.operationId,categories:e.categories,label:e.label,description:e.description,operationType:e.operationType,schemaType:e.schemaType??`native`,entrypointUrl:e.entrypointUrl??n,entrypointHttpMethod:o,tags:e.tags,context:e.context,responses:r,cursor:i,compositeIdentifiers:Ne(e),scheduledJobs:Pe(e),inputs:a,steps:e.steps.reduce((n,r)=>{let i={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...r.stepFunction.parameters,...Fe(r.stepFunction.functionName,t,r.stepFunction.parameters),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:r.stepFunction.parameters.fields??e.fieldConfigs}:{}}}};return Ae(e.operationId,i),n[r.stepId]=i,n},{}),result:e.result}},Ae=(e,t)=>{let n=t.stepFunction.version??`1`,r=_[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new N(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Le(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},z=(e,t)=>{if(!e.inputs)return{};let n=je(e.inputs),r=n.parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},B=e=>{let t={};return e.forEach(e=>{let n;switch(e.type.toLowerCase()){case`string`:n=a.string();break;case`number`:n=a.number();break;case`boolean`:n=a.boolean();break;case`datetime_string`:n=a.string().refine(e=>!isNaN(Date.parse(e)),{message:`Invalid datetime string`});break;case`object`:n=e.properties?B(e.properties):a.record(a.string(),a.any());break;default:n=a.any()}let r=e.array?a.array(n):n;t[e.name]=e.required?r:r.optional()}),a.object(t)},je=e=>{let t=e.filter(e=>e.in===`path`),n=e.filter(e=>e.in===`query`),r=e.filter(e=>e.in===`body`),i=e.filter(e=>e.in===`headers`);return a.object({path:B(t).optional(),query:B(n).optional(),body:B(r).optional(),headers:B(i).optional()})},Me=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:F};return{enabled:n.enabled&&t,pageSize:n.pageSize}},Ne=t=>{if(t.operationType===`refresh_token`)return{enabled:!1};if(e(t.compositeIdentifiers)){let e=t.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=i(e)?[{targetFieldKey:e.targetFieldKey,remote:`id`,components:[{name:e.targetFieldKey,alias:e.alias}]}]:void 0;return{enabled:!0,version:p,fields:n}}let n=[];for(let e of t.compositeIdentifiers?.fields??[]){let r=e.components.map(e=>{let n=t.fieldConfigs?.find(t=>t.targetFieldKey===e);return{name:e,alias:n?.alias}});n.push({targetFieldKey:e.targetFieldKey,remote:e.remote,components:r})}return{enabled:t.compositeIdentifiers.enabled,version:t.compositeIdentifiers.version,fields:n.length>0?n:void 0}},Pe=t=>{if(!e(t.scheduledJobs))return t.scheduledJobs},Fe=(e,t,n={})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n.customErrors&&Array.isArray(n.customErrors)?n.customErrors:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ie=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new M(e,`Invalid connector schema`)}},Le=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new P(n,r,i,a,e)}},V=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if(i(r))return{operation:r,params:{}}},Re=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=V(e,t,n);return i(r)},ze=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Be=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Ve=t=>{try{return L(t),{success:!0}}catch(n){if(n instanceof M){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=e(r)?n.path:[...n.path,r],o=He(a,t);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof le)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof N){let e=H(n.operationId,n.stepId,n.functionName,!1,t);return{success:!1,errors:[{line:e,message:n.message,field:void 0}]}}else if(n instanceof P){let r=n.issues,i=[];return r.forEach(r=>{let a=r?.keys?.[0],o=e(a)?r.path:[...r.path,a],s=H(n.operationId,n.stepId,n.functionName,!0,t);i.push({line:s,message:r.message,field:o.join(`.`)})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},He=(t,n)=>{let r=n.split(`
5
5
  `),a=0,o=-1,s=0;for(let n=0;n<r.length;n++){let c=r[n],l=c.match(/^(\s*)/)?.[1]?.length||0,u=c.replace(`- `,``).trim();if(u.startsWith(`#`)||u===``||l<=o)continue;let d=i(t[a])?`${String(t[a])}`:``;if(e(d))return s+1;if(isNaN(Number(d))){if(u.startsWith(`${d}:`)){if(a===t.length-1)return n+1;o=l,s=n,a++}}else{let e=parseInt(d,10),t=-1;for(let i=n;i<r.length;i++){let o=r[i],c=o.trim();if(c.startsWith(`-`)&&t++,t===e){a++,s=n,n--;break}else n++}}}return s+1},H=(t,n,r,a,o)=>{let s=o.split(`
6
- `),c=1,l=null,u=null;for(let o=0;o<s.length;o++){let d=s[o],f=d.trim();if(e(l)&&f===`- operationId: ${t}`){l=t,c=o+1;continue}if(i(l)&&e(u)&&f===`- stepId: ${n}`){u=n,c=o+1;continue}if(i(l)&&i(u)&&!a&&f.startsWith(`functionName: ${r}`)||i(l)&&i(u)&&a&&f===`parameters:`)return c=o+1,c}return c};var U=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},W=class extends U{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},G=class extends U{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},K=class extends U{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Ue=class extends U{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const We=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.description,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Ge=(e,t)=>e.map(e=>We(e,t)),Ke=`stackone://internal//`,qe=`${Ke}refresh_token`,Je=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=g.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===h.MAP_FIELDS?{[h.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},q=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ye=t=>{let n=t.operation?.compositeIdentifiers,r={...t.inputs??{}};if(!n?.enabled||e(r))return t;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),a={version:n.version??p,aliases:i};return J(r,a,t.logger),{...t,inputs:r}},J=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))tt(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)J(e,t,n);else typeof i==`object`&&i&&J(i,t,n)}},Xe=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=v(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Ze=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Qe=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},$e=(e,t,n,r,i)=>{n.every(Qe)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},et=(e,t,n)=>{e instanceof m&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},tt=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=Xe(o,t,r,i);Ze(n,t,s,a),$e(n,t,s,c,a)}catch(e){et(e,t,i)}},Y=`remote_`,nt=t=>{let n=t.operation?.compositeIdentifiers;if(!n?.enabled)return t;let r=`data`,i=t.outputs?.[r];if(e(i))return t;let a=Array.isArray(i)?i.map(e=>X(e,n)):X(i,n);return{...t,outputs:{...t.outputs??{},[r]:a}}},X=(e,t)=>{let r=rt(e,t),i=Z(r);return{...e,...n(i)?i:{}}},rt=(e,t)=>{let n=t.version??p,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=y(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${Y}${t.remote}`]=e[t.remote])}),{...e,...r}},it=e=>e===`id`||/.+_id(s)?$/.test(e),at=e=>Array.isArray(e)&&e.every(e=>r(e)&&e.length>0),ot=(e,t)=>x(e)||t.startsWith(Y),st=(e,t)=>{try{return y({key:e,value:t},{version:p})}catch{return t}},ct=(e,t,n)=>{let i=t.map(t=>r(t)&&t.length>0&&!x(t)?st(e,t):t);n[e]=i,n[`${Y}${e}`]=t},lt=(e,t,n)=>{if(ot(t,e))return;let r=y({key:e,value:t},{version:p});n[e]=r,n[`remote_${e}`]=t},ut=(e,t,n)=>{at(t)?ct(e,t,n):r(t)&&t.length>0&&lt(e,t,n)},Z=e=>{if(Array.isArray(e))return e.map(e=>Z(e));if(!n(e))return e;let t={...e};for(let[r,i]of Object.entries(e))(n(i)||Array.isArray(i)&&i.length>0&&n(i[0]))&&(t[r]=Z(i)),it(r)&&ut(r,i,t);return t},dt=(e,n)=>{let r=Number(e.inputs?.page_size),a=i(e.inputs?.page_size)&&t(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??n;return a},ft=(t,r,a,o)=>{let s=e(t)?void 0:t.data,c=Object.keys(a).length+1,l=S({cursor:o,ignoreStepIndex:c});if(!n(t)||e(s)||(s?.length??0)<=r)return{result:t,next:i(o)&&!l?C(o):null};let u=o?.remote?.[c]?.pageNumber??1,d=(u-1)*r,f=d+r,p=s.slice(d,f),m=s.length>f||!l,h=w({cursor:o,stepIndex:c,pageNumber:u+1});return{result:{...t,data:p},next:m?C(h):null}},Q=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=ft,encodeResultCompositeIds:r=nt,decodeInputCompositeIds:i=Ye})=>{let a=i(e),o=await vt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},pt=(e,t)=>e.condition?!O(e.condition,t):!1,mt=(e,t,n)=>{let r=e.stepFunction;return t.operation?.cursor.enabled?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},ht=(e,t,n,r,i)=>{let a=$({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},gt=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(pt(o,r))return $({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return $({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=mt(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return ht(r,e,u,o,i);let d=r.operation?.cursor.enabled?w({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return $({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},_t=(e,t,r,a,o)=>{let s=!r.hasFatalError,c=s?e.operation?.responses.success.statusCode??200:r.errorStatusCode??500,l=i(o)&&n(o.result)?{next:o.next,...o.result}:a;return{...t,outputs:l,response:{successful:s,statusCode:c,message:s?void 0:e.operation?.responses?.errors?.[c]?.description??T?.[c]??`Error while processing the request`}}},vt=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=ft})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=dt(e,F),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await gt(t,e,r,i,s,c);let l=e.operation?.result?yt(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return _t(e,i,s,l,u)},yt=(e,t)=>n(e)?te(e,t):O(e,t),$=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),bt=async({operationId:t,account:n,connector:i,pathParams:a={},queryParams:o={},body:s={},headers:c={},logger:l,getHttpClient:u,parseConnector:d=L,parseOperationInputsFn:f=z,createBlockContextFn:p=q,createBlockFn:m=k,runStepOperationFn:h=Q})=>{let g=n.authConfigKey,_=n.environment??`production`,v=n.secureId,y=n.projectSecureId,b=n.credentials,x=p({category:`action`,connectorKey:n.providerKey,connectorVersion:n.providerVersion,authConfigKey:g,environment:_,accountSecureId:v,projectSecureId:y}),S;try{S=r(i)?d(i):i}catch{throw new W(x,`Error while parsing connector`)}let C=ce(i,t);if(e(C))throw new G(x,`No matching operation found`);x.operationType=C.operationType,x.schema=C.schema?.key;let w=xt(o,x),T;try{T=f(C,{path:a,query:o,body:s,headers:c})}catch{throw new K(x,`Error while parsing operation inputs`)}let E=await m({connector:S,inputs:T,context:x,operation:C,credentials:b,nextCursor:w,logger:l,getHttpClient:u});return await h({block:E})},xt=(e,t)=>{let n=e?.next,r=i(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Ue(t,`Invalid cursor.`);return r},St=async({account:t,connector:n,category:i,path:a,method:o=`get`,queryParams:s={},body:c,headers:l,logger:u,getHttpClient:d,parseConnector:f=L,getOperationFromUrlFn:p=oe,getOperationForRefreshAuthenticationFn:m=V,parseOperationInputsFn:h=z,createBlockContextFn:g=q,createBlockFn:_=k,runStepOperationFn:v=Q})=>{let y=t.authConfigKey,b=t.environment??`production`,x=t.secureId,S=t.projectSecureId,C=t.credentials,w=g({category:i,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:y,environment:b,accountSecureId:x,projectSecureId:S}),T;try{T=r(n)?f(n):n}catch{throw new W(w,`Error while parsing connector`)}let E=wt(a)?m(T,y,b):p(T,a,o);if(e(E))throw new G(w,`No matching operation found`);w.operationType=E.operation.operationType,w.schema=E.operation.schema?.key;let ee=Ct(s,w),D;try{D=h(E.operation,{query:s,body:c,headers:l,path:E.params})}catch{throw new K(w,`Error while parsing operation inputs`)}let O=await _({connector:T,inputs:D,context:w,operation:E.operation,credentials:C,nextCursor:ee,logger:u,getHttpClient:d});return await v({block:O})},Ct=(e,t)=>{let n=e?.next,r=i(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Ue(t,`Invalid cursor.`);return r},wt=e=>e===qe,Tt=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Et=async({account:t,connector:n,logger:a,getHttpClient:o,parseConnector:s=L,getTestOperationsFn:c=Tt,createBlockContextFn:l=q,createBlockFn:u=k,runStepOperationFn:d=Q})=>{let f=t.authConfigKey,p=t.environment??`production`,m=t.secureId,h=t.projectSecureId,g=t.credentials,_=l({category:`internal`,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:f,environment:p,accountSecureId:m,projectSecureId:h}),v;try{v=r(n)?s(n):n}catch{throw new W(_,`Error while parsing connector`)}let y=c(v,f,p);if(e(y)||y.length===0)return!0;_.operationType=`test`;for(let t of y){let n=await u({connector:v,inputs:void 0,context:_,operation:t.operation,credentials:g,nextCursor:void 0,logger:a,getHttpClient:o}),r=i(t.condition)?D(t.condition,n):!0;if(!r)continue;let s=await d({block:n});if((e(s?.response?.successful)||!s.response.successful)&&t.required)return a?.error({code:`TestOperationFailed`,message:`Test operation "${t.operation.id}" failed with error: ${s?.response?.message}`}),!1}return!0};export{U as ConnectSDKError,qe as REFRESH_TOKEN_OPERATION_PATH,We as buildActionsMetaFromConfig,k as createBlock,Je as executeStepFunction,Ge as getActionsMetaFromConfigs,oe as getOperationFromUrl,Be as getRefreshTokenExpiresIn,ze as getTokenExpiresIn,ne as loadConnector,z as parseOperationInputs,L as parseYamlConnector,bt as runConnectorAction,St as runConnectorOperation,Q as runStepOperation,Et as runTestOperations,Re as supportsRefreshAuthentication,Ve as validateYamlConnector};
6
+ `),c=1,l=null,u=null;for(let o=0;o<s.length;o++){let d=s[o],f=d.trim();if(e(l)&&f===`- operationId: ${t}`){l=t,c=o+1;continue}if(i(l)&&e(u)&&f===`- stepId: ${n}`){u=n,c=o+1;continue}if(i(l)&&i(u)&&!a&&f.startsWith(`functionName: ${r}`)||i(l)&&i(u)&&a&&f===`parameters:`)return c=o+1,c}return c};var U=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},W=class extends U{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},G=class extends U{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},K=class extends U{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Ue=class extends U{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const We=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.description,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Ge=(e,t)=>e.map(e=>We(e,t)),Ke=`stackone://internal//`,qe=`${Ke}refresh_token`,Je=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=g.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===h.MAP_FIELDS?{[h.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},q=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i}),Ye=t=>{let n=t.operation?.compositeIdentifiers,r={...t.inputs??{}};if(!n?.enabled||e(r))return t;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),a={version:n.version??p,aliases:i};return J(r,a,t.logger),{...t,inputs:r}},J=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))tt(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)J(e,t,n);else typeof i==`object`&&i&&J(i,t,n)}},Xe=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=v(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Ze=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Qe=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},$e=(e,t,n,r,i)=>{n.every(Qe)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},et=(e,t,n)=>{e instanceof m&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},tt=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=Xe(o,t,r,i);Ze(n,t,s,a),$e(n,t,s,c,a)}catch(e){et(e,t,i)}},Y=`remote_`,nt=t=>{let n=t.operation?.compositeIdentifiers;if(!n?.enabled)return t;let r=`data`,i=t.outputs?.[r];if(e(i))return t;let a=Array.isArray(i)?i.map(e=>X(e,n)):X(i,n);return{...t,outputs:{...t.outputs??{},[r]:a}}},X=(e,t)=>{let r=rt(e,t),i=Z(r);return{...e,...n(i)?i:{}}},rt=(e,t)=>{let n=t.version??p,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=y(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${Y}${t.remote}`]=e[t.remote])}),{...e,...r}},it=e=>e===`id`||/.+_id(s)?$/.test(e),at=e=>Array.isArray(e)&&e.every(e=>r(e)&&e.length>0),ot=(e,t)=>x(e)||t.startsWith(Y),st=(e,t)=>{try{return y({key:e,value:t},{version:p})}catch{return t}},ct=(e,t,n)=>{let i=t.map(t=>r(t)&&t.length>0&&!x(t)?st(e,t):t);n[e]=i,n[`${Y}${e}`]=t},lt=(e,t,n)=>{if(ot(t,e))return;let r=y({key:e,value:t},{version:p});n[e]=r,n[`remote_${e}`]=t},ut=(e,t,n)=>{at(t)?ct(e,t,n):r(t)&&t.length>0&&lt(e,t,n)},Z=e=>{if(Array.isArray(e))return e.map(e=>Z(e));if(!n(e))return e;let t={...e};for(let[r,i]of Object.entries(e))(n(i)||Array.isArray(i)&&i.length>0&&n(i[0]))&&(t[r]=Z(i)),it(r)&&ut(r,i,t);return t},dt=(e,n)=>{let r=Number(e.inputs?.page_size),a=i(e.inputs?.page_size)&&t(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??n;return a},ft=(t,r,a,o)=>{let s=e(t)?void 0:t.data,c=Object.keys(a).length+1,l=S({cursor:o,ignoreStepIndex:c});if(!n(t)||e(s)||(s?.length??0)<=r)return{result:t,next:i(o)&&!l?C(o):null};let u=o?.remote?.[c]?.pageNumber??1,d=(u-1)*r,f=d+r,p=s.slice(d,f),m=s.length>f||!l,h=w({cursor:o,stepIndex:c,pageNumber:u+1});return{result:{...t,data:p},next:m?C(h):null}},Q=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=ft,encodeResultCompositeIds:r=nt,decodeInputCompositeIds:i=Ye})=>{let a=i(e),o=await vt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},pt=(e,t)=>e.condition?!O(e.condition,t):!1,mt=(e,t,n)=>{let r=e.stepFunction,a=_[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],o=i(a?.inputSchema?.shape)?`cursor`in a?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&o?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},ht=(e,t,n,r,i)=>{let a=$({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},gt=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(pt(o,r))return $({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return $({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=mt(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return ht(r,e,u,o,i);let d=r.operation?.cursor.enabled?w({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return $({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},_t=(e,t,r,a,o)=>{let s=!r.hasFatalError,c=s?e.operation?.responses.success.statusCode??200:r.errorStatusCode??500,l=i(o)&&n(o.result)?{next:o.next,...o.result}:a;return{...t,outputs:l,response:{successful:s,statusCode:c,message:s?void 0:e.operation?.responses?.errors?.[c]?.description??T?.[c]??`Error while processing the request`}}},vt=async({block:e,buildStepFunction:t=g.build,virtualPaginateResultFn:n=ft})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=dt(e,F),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await gt(t,e,r,i,s,c);let l=e.operation?.result?yt(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return _t(e,i,s,l,u)},yt=(e,t)=>n(e)?te(e,t):O(e,t),$=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),bt=async({operationId:t,account:n,connector:i,pathParams:a={},queryParams:o={},body:s={},headers:c={},logger:l,getHttpClient:u,parseConnector:d=L,parseOperationInputsFn:f=z,createBlockContextFn:p=q,createBlockFn:m=k,runStepOperationFn:h=Q})=>{let g=n.authConfigKey,_=n.environment??`production`,v=n.secureId,y=n.projectSecureId,b=n.credentials,x=p({category:`action`,connectorKey:n.providerKey,connectorVersion:n.providerVersion,authConfigKey:g,environment:_,accountSecureId:v,projectSecureId:y}),S;try{S=r(i)?d(i):i}catch{throw new W(x,`Error while parsing connector`)}let C=ce(i,t);if(e(C))throw new G(x,`No matching operation found`);x.operationType=C.operationType,x.schema=C.schema?.key;let w=xt(o,x),T;try{T=f(C,{path:a,query:o,body:s,headers:c})}catch{throw new K(x,`Error while parsing operation inputs`)}let E=await m({connector:S,inputs:T,context:x,operation:C,credentials:b,nextCursor:w,logger:l,getHttpClient:u});return await h({block:E})},xt=(e,t)=>{let n=e?.next,r=i(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Ue(t,`Invalid cursor.`);return r},St=async({account:t,connector:n,category:i,path:a,method:o=`get`,queryParams:s={},body:c,headers:l,logger:u,getHttpClient:d,parseConnector:f=L,getOperationFromUrlFn:p=oe,getOperationForRefreshAuthenticationFn:m=V,parseOperationInputsFn:h=z,createBlockContextFn:g=q,createBlockFn:_=k,runStepOperationFn:v=Q})=>{let y=t.authConfigKey,b=t.environment??`production`,x=t.secureId,S=t.projectSecureId,C=t.credentials,w=g({category:i,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:y,environment:b,accountSecureId:x,projectSecureId:S}),T;try{T=r(n)?f(n):n}catch{throw new W(w,`Error while parsing connector`)}let E=wt(a)?m(T,y,b):p(T,a,o);if(e(E))throw new G(w,`No matching operation found`);w.operationType=E.operation.operationType,w.schema=E.operation.schema?.key;let ee=Ct(s,w),D;try{D=h(E.operation,{query:s,body:c,headers:l,path:E.params})}catch{throw new K(w,`Error while parsing operation inputs`)}let O=await _({connector:T,inputs:D,context:w,operation:E.operation,credentials:C,nextCursor:ee,logger:u,getHttpClient:d});return await v({block:O})},Ct=(e,t)=>{let n=e?.next,r=i(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Ue(t,`Invalid cursor.`);return r},wt=e=>e===qe,Tt=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Et=async({account:t,connector:n,logger:a,getHttpClient:o,parseConnector:s=L,getTestOperationsFn:c=Tt,createBlockContextFn:l=q,createBlockFn:u=k,runStepOperationFn:d=Q})=>{let f=t.authConfigKey,p=t.environment??`production`,m=t.secureId,h=t.projectSecureId,g=t.credentials,_=l({category:`internal`,connectorKey:t.providerKey,connectorVersion:t.providerVersion,authConfigKey:f,environment:p,accountSecureId:m,projectSecureId:h}),v;try{v=r(n)?s(n):n}catch{throw new W(_,`Error while parsing connector`)}let y=c(v,f,p);if(e(y)||y.length===0)return!0;_.operationType=`test`;for(let t of y){let n=await u({connector:v,inputs:void 0,context:_,operation:t.operation,credentials:g,nextCursor:void 0,logger:a,getHttpClient:o}),r=i(t.condition)?D(t.condition,n):!0;if(!r)continue;let s=await d({block:n});if((e(s?.response?.successful)||!s.response.successful)&&t.required)return a?.error({code:`TestOperationFailed`,message:`Test operation "${t.operation.id}" failed with error: ${s?.response?.message}`}),!1}return!0};export{U as ConnectSDKError,qe as REFRESH_TOKEN_OPERATION_PATH,We as buildActionsMetaFromConfig,k as createBlock,Je as executeStepFunction,Ge as getActionsMetaFromConfigs,oe as getOperationFromUrl,Be as getRefreshTokenExpiresIn,ze as getTokenExpiresIn,ne as loadConnector,z as parseOperationInputs,L as parseYamlConnector,bt as runConnectorAction,St as runConnectorOperation,Q as runStepOperation,Et as runTestOperations,Re as supportsRefreshAuthentication,Ve as validateYamlConnector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/connect-sdk",
3
- "version": "1.56.0",
3
+ "version": "1.56.2",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",