@stackone/core 3.33.0 → 4.1.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.cjs CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("@stackone/expressions"),c=require("@stackone/transport"),l=require("@aws-sdk/client-lambda"),u=require("node:stream"),d=require("mime-types");d=__toESM(d);let f=require("saml"),p=require("uuid"),m=require("@stackone/redaction"),h=require("node:crypto"),g=require("jose"),_=require("form-data");_=__toESM(_);const v=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=v.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},y={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>y[e.toLowerCase()]??null,isValidCategory=e=>!!y[e.toLowerCase()],b=(0,o.encodeToBase64)(`so1!`),x=RegExp(`(?<!\\\\):`,`g`),S=RegExp(`(?<!\\\\),`,`g`);var C=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends C{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!(0,o.isMissing)(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!(0,o.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(S).forEach(e=>{let[n,i]=e.split(x),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${b}${(0,o.encodeToBase64)(e)}`,decodeIdV1=e=>{if(!e.startsWith(b))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let t=e.split(b)[1];if(!t)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return(0,o.decodeFromBase64)(t)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>(0,o.isMissing)(e)?!1:e.startsWith(b),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return(0,o.getContentHash)({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if((0,o.isMissing)(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=(0,s.safeEvaluate)(`{{${n.result.trim()}}}`,t);if(!(0,o.isMissing)(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if(!(0,o.isMissing)(n))for(let e of n.rules){let n=(0,s.safeEvaluate)(`{{${e.when.trim()}}}`,t);if(n!==null&&n!==!1&&n!==void 0){let n=e.then.input?Object.fromEntries(Object.entries(e.then.input).map(([e,n])=>[e,(0,s.safeEvaluate)(`{{${String(n).trim()}}}`,t)])):void 0;return{action:e.then.action,input:n}}}},w={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},T={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>T[e],isValidEnumRef=e=>e in T,E=[`preview`,`beta`,`ga`,`deprecated`,`internal`],D=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],O=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],k=[`read`,`write`,`delete`,`search`,`execute`],A=[`native`,`unified`],j=[`body`,`query`,`path`,`headers`],M=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],N=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],P=[`sync`,`async`],F=(0,o.zStrictObject)({r:o.z.record(o.z.string(),(0,o.zStrictObject)({n:o.z.number().optional().nullable(),c:o.z.string().optional().nullable(),p:o.z.number().optional().nullable()})),v:o.z.number(),t:o.z.number()}),I=(0,o.zStrictObject)({remote:o.z.record(o.z.string(),(0,o.zStrictObject)({pageNumber:o.z.number().optional(),providerPageCursor:o.z.string().optional(),position:o.z.number().optional()})),version:o.z.number(),timestamp:o.z.number()}),minifyCursor=e=>(0,o.encodeToBase64)(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if((0,o.isString)(e)){let t=(0,o.decodeFromBase64)(e),n=JSON.parse(t);return expandCursorObject(F.parse(n))}else return I.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,r=typeof t==`string`?expandCursor(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:s,...c}=r;return(0,o.getContentHash)(a)===(0,o.getContentHash)(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>(0,o.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,o.isMissing)(t)||r!==t.toString())&&(n=n&&(0,o.isMissing)(i.pageNumber)&&(0,o.isMissing)(i.position)&&(0,o.isMissing)(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},s=(0,o.isMissing)(n)&&(0,o.isMissing)(r)&&(0,o.isMissing)(i);return(0,o.isMissing)(e)?{remote:s?{}:{[t]:a},version:2,timestamp:Date.now()}:s?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof C;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const L={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},R={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},z={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},B={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},V=o.z.object({startUrl:o.z.string().url(),systemPrompt:o.z.string().optional(),viewport:(0,o.zStrictObject)({width:o.z.number().int().positive(),height:o.z.number().int().positive()}).optional(),locale:o.z.string().optional(),budgets:(0,o.zStrictObject)({maxDurationMs:o.z.number().int().positive(),maxSteps:o.z.number().int().positive()}),auth:(0,o.zStrictObject)({sensitiveKeys:o.z.array(o.z.string().min(1)).optional(),requiresSession:o.z.boolean().optional(),allowedDomains:o.z.array(o.z.string().min(1)).optional()}).optional()}),H=o.z.unknown(),U=(0,o.zStrictObject)({lambdaName:o.z.string(),region:o.z.string().optional(),endpoint:o.z.string().optional(),invocationType:o.z.enum([`RequestResponse`,`Event`,`DryRun`]).optional(),qualifier:o.z.string().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional()}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:o.z.string().optional()}),ee=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),executedVersion:o.z.string().optional()}).optional(),W=(0,o.zStrictObject)({strategy:o.z.literal(`aws4`),service:o.z.string(),region:o.z.string().optional()}),G=(0,o.zStrictObject)({strategy:o.z.literal(`hmac`),algorithm:o.z.enum([`sha1`,`sha256`,`sha512`]).optional(),headerName:o.z.string().optional(),prefix:o.z.string().optional(),dateFormat:o.z.enum([`iso8601`,`rfc2822`]).optional(),includeHost:o.z.boolean().optional(),includeBodyHash:o.z.boolean().optional(),outputFormat:o.z.enum([`header`,`basic`]).optional(),username:o.z.string().optional()}),te=o.z.discriminatedUnion(`strategy`,[W,G]),K=(0,o.zStrictObject)({type:o.z.literal(`none`),signing:te.optional(),redirectUri:o.z.string().optional()}),q=(0,o.zStrictObject)({type:o.z.literal(`basic`),username:o.z.string().optional(),password:o.z.string().optional(),encoding:o.z.string().optional(),redirectUri:o.z.string().optional()}),ne=(0,o.zStrictObject)({type:o.z.literal(`bearer`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),redirectUri:o.z.string().optional()}),J=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),Y=(0,o.zStrictObject)({type:o.z.literal(`oauth2`),authorizationUrl:o.z.string().optional(),redirectUri:o.z.string().optional(),authorizationParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenUrl:o.z.string().optional(),tokenParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenExpiresIn:o.z.number().optional(),tokenRefreshExpiresIn:o.z.number().optional(),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),scopes:o.z.string().optional(),scopeDelimiter:o.z.string().optional(),customHeaders:o.z.record(o.z.string(),o.z.string()).optional(),pkce:o.z.boolean().optional(),additionalTokenFields:o.z.record(o.z.string(),o.z.string().optional()).optional(),callbackParams:o.z.record(o.z.string(),o.z.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))J.has(r)&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional(),issuer:o.z.string().optional(),tokenResponse:(0,o.zStrictObject)({acceptTokenTypes:o.z.array(o.z.string()).optional(),accessToken:o.z.string().min(1).optional(),refreshToken:o.z.string().min(1).optional()}).optional()}),X=o.z.discriminatedUnion(`type`,[K,q,ne,Y]),re=(0,o.zStrictObject)({certs:o.z.string().array().optional(),keys:o.z.string().array().optional()}).optional(),ie=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).optional().default(`get`),authorization:X.optional(),responseMode:o.z.enum([`buffer`,`stream`]).optional().default(`buffer`),responseType:o.z.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`),encoding:o.z.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`),response:(0,o.zStrictObject)({dataKey:o.z.string().optional(),fileNameKey:o.z.string().optional(),contentTypeKey:o.z.string().optional(),contentType:o.z.string().optional(),contentIsBase64:o.z.boolean().optional().default(!1),urlKey:o.z.string().optional(),forwardAuth:o.z.boolean().optional().default(!1)}).optional(),maxRedirects:o.z.number().optional().default(5),followRedirects:o.z.boolean().optional().default(!0),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Z=(0,o.zStrictObject)({data:o.z.union([o.z.string(),o.z.instanceof(Buffer)]).optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),headers:o.z.record(o.z.string(),o.z.union([o.z.string(),o.z.array(o.z.string())])).optional(),contentDisposition:o.z.string().optional(),fileMetadata:(0,o.zStrictObject)({contentType:o.z.string().optional(),contentLength:o.z.number().optional(),fileName:o.z.string().optional(),lastModified:o.z.string().optional(),etag:o.z.string().optional()}).optional(),finalUrl:o.z.string().optional()}).optional(),ae=o.z.object({event:o.z.object({eventType:o.z.string(),eventId:o.z.coerce.string().optional(),eventDate:o.z.coerce.string().optional(),data:o.z.unknown().optional()}).optional()}),oe=o.z.record(o.z.string(),o.z.unknown()),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof c.HttpResponseError){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new l.LambdaClient(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),u=new l.InvokeCommand({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),d=await c.send(u),f=d.Payload?Buffer.from(d.Payload).toString(`utf-8`):``,p;if(f.length===0)p=void 0;else try{p=JSON.parse(f)}catch{p=f}return{statusCode:d.StatusCode??200,payload:p,functionError:d.FunctionError,executedVersion:d.ExecutedVersion}},se=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>(0,s.isExpression)(e)||se.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>(0,s.isExpression)(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,ce=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;try{let n=(0,s.evaluate)(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||(0,s.safeEvaluate)(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,c=typeof o==`string`&&!se.test(o),l=t?.qualifier,u=typeof l==`string`&&!hasExpressionMarker(l),d={...t?(0,s.safeEvaluateRecord)(i===void 0?t:{...t,args:a},e):{},...c?{dataKey:o}:{},...u?{qualifier:l}:{}},f;try{f=U.parse(d)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:p,region:m,endpoint:h,invocationType:g,qualifier:_,args:v,dataKey:y}=f,b;try{b=await n({lambdaName:p,payload:buildPayloadFromArgs(v),region:m,endpoint:h,invocationType:g,qualifier:_,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(b.functionError){let t=typeof b.payload==`object`&&b.payload!==null&&`errorMessage`in b.payload&&typeof b.payload.errorMessage==`string`?b.payload.errorMessage:`Lambda function error: ${b.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:b.functionError}],output:{statusCode:b.statusCode,message:t,data:b.payload,raw:b}}}return{block:e,successful:!0,output:{data:y?ce(b.payload,y):b.payload,raw:b,statusCode:b.statusCode,executedVersion:b.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,authorization:f,args:p,responseMode:m,responseType:h,encoding:g,response:_,maxRedirects:v,followRedirects:y}=ie.parse(a),b=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=p?(0,c.parseRequestParameters)(p):{query:{},body:{},headers:{}},S=typeof x?.body==`string`?void 0:x?.body,C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(f)?f:X.parse(b)),w={...x?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimits:T,concurrency:E}:void 0,O=buildRequestContext(e);if(m===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,maxRedirects:y?v:0,requestConfig:D,context:O,response:_,responseType:h,authHeaders:C});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,responseType:h,encoding:g,response:_,maxRedirects:y?v:0,requestConfig:D,context:O,authHeaders:C})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,maxRedirects:d,requestConfig:f,context:p,response:m,responseType:h,authHeaders:g}=e,_=`${r}${i}`;if(!_.startsWith(`http://`)&&!_.startsWith(`https://`))throw Error(`Invalid URL: "${_}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if((0,o.notMissing)(m?.dataKey)||(0,o.notMissing)(m?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,responseType:h??`arraybuffer`,encoding:`none`,response:m,maxRedirects:d,requestConfig:f,context:p,authHeaders:g??{}}),_=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),v={...e.fileMetadata,contentLength:_.length};return{block:t,successful:!0,streamOutput:{stream:u.Readable.from(_),headers:(0,o.notMissing)(v.contentType)?{"content-type":v.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:v}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:_,method:a,headers:s,queryParams:c,payload:l,maxRedirects:d,requestConfig:f,context:p}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:s,context:c,authHeaders:l}=e,u=n.data;if(r.urlKey){let e=extractValueByPath(u,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?l:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:s,context:c}),d=encodeFileData(n.data,i),f=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(f.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(f.contentType=e)}(0,o.isMissing)(f.contentType)&&(0,o.notMissing)(r.contentType)&&(f.contentType=r.contentType);let p=buildContentDisposition(f);return{data:d,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:p,fileMetadata:f,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(u,r.dataKey);if((0,o.isMissing)(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}(0,o.isMissing)(a.contentType)&&(0,o.notMissing)(r.contentType)&&(a.contentType=r.contentType);let s=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:s,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if((0,o.isMissing)(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=(0,o.isString)(e[`content-type`])?e[`content-type`]:void 0,n=(0,o.isString)(e[`content-length`])?e[`content-length`]:void 0,r=(0,o.isString)(e[`content-disposition`])?e[`content-disposition`]:void 0,i=(0,o.isString)(e[`last-modified`])?e[`last-modified`]:void 0,a=(0,o.isString)(e.etag)?e.etag:void 0,s=n?parseInt(n,10):void 0,c=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(s)?void 0:s,fileName:c,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return d.default.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?(0,s.safeEvaluateRecord)(t,e):{},{event:r}=ae.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},le=o.z.object({stepsDataToGroup:o.z.array(o.z.string()),isSingleRecord:o.z.boolean().optional()}),ue=o.z.object({data:o.z.unknown()}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=le.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...(0,o.notMissing)(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},de=__name(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=fe(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=fe(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),fe=__name((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=pe(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),pe=__name((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=(0,s.evaluate)(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return o.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return o.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return o.getCountryCodeByCountryCode;case`country_name_by_country_name`:return o.getCountryNameByCountryName;case`country_name_by_alpha3code`:return o.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return o.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return o.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return o.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return o.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return o.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return o.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return o.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return o.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return o.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return o.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return o.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return o.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return o.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return o.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return o.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return o.getDocumentFileFormatFromExtension;default:return}},me=(0,o.zStrictObject)({targetFieldKey:o.z.string(),alias:o.z.string().optional(),expression:o.z.string().optional(),values:o.z.unknown().optional(),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.z.boolean().default(!1),custom:o.z.boolean().default(!1),hidden:o.z.boolean().default(!1),enumMapper:(0,o.zStrictObject)({matcher:o.z.string().or((0,o.zStrictObject)({matchExpression:o.z.string(),value:o.z.string()}).array())}).optional(),properties:o.z.lazy(()=>me).array().optional(),requiredScopes:o.z.string().array().optional()}),he=o.z.object({fields:me.array(),dataSource:o.z.string(),externalSources:o.z.record(o.z.string(),o.z.string()).optional()}),ge=o.z.object({data:o.z.unknown()}),mergeSourceWithState=(e,t)=>(0,o.isObject)(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=he.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),c=(0,s.evaluate)(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!c)return{block:e,successful:!0};let l=Object.keys(a??{})?.reduce((e,t)=>(e[t]=(0,s.evaluate)(a?.[t],o),e),{}),u;if(Array.isArray(c))u=c.map(e=>{let t=Q(r,{...e,external:l},o);return n.push(...t?.errors||[]),t?.record});else{let e=Q(r,{...c,external:l},o);u=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:u},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),s=Q(e.properties,a,r);return(0,o.notMissing)(s?.errors)&&n.push(...s.errors),s?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=(0,s.evaluate)(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=(0,o.notMissing)(e.values)?e.values:t,a=Q(e.properties,i,r);return(0,o.notMissing)(a?.errors)&&n.push(...a.errors),a?.record},_e=__name((e,t,n,r,i)=>{if(!(0,o.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),Q=__name((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=_e(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,s.isValidExpression)(e))try{return(0,s.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return ve(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},ve=__name((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,s.evaluate)(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=ve(e,t,n),i=(0,o.notMissing)(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if((0,o.isString)(a)){let n=getEnumMatcher(a);return(0,o.notMissing)(n)?{value:{value:((0,o.notMissing)(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if((0,s.evaluate)(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},ye=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string().optional(),method:o.z.enum([`tools/call`,`tools/list`]).default(`tools/call`),toolName:o.z.string().optional(),timeout:o.z.number().int().positive().optional(),authorization:X.optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional()}).array().optional()}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),be=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),buildMcpClient=e=>new c.McpClient(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if((0,o.notMissing)(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l;try{l=ye.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:u,url:d,method:f,toolName:p,timeout:m,authorization:h,args:g}=l,_=`${u??``}${d??``}`;if(!_)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let v=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,y;try{y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:X.parse(v??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let b=e.connector?.rateLimit,x=e.connector?.concurrency,S=n({serverUrl:_,headers:y,timeout:m,requestConfig:b!==void 0||x!==void 0?{rateLimits:b,concurrency:x}:void 0,context:buildRequestContext(e)});try{if(f===`tools/list`){let t=await S.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!p)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await S.callTool({name:p,arguments:buildToolArguments(g)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${p}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:p}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await S.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>f.Saml20.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},m={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+(0,p.v4)()},h=Buffer.from(l(m)).toString(`base64`);return await u(1e3),h},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("@stackone/expressions"),c=require("@stackone/transport"),l=require("@aws-sdk/client-lambda"),u=require("node:stream"),d=require("mime-types");d=__toESM(d);let f=require("saml"),p=require("uuid"),m=require("@stackone/redaction"),h=require("node:crypto"),g=require("jose"),_=require("form-data");_=__toESM(_);const v=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=v.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},y={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>y[e.toLowerCase()]??null,isValidCategory=e=>!!y[e.toLowerCase()],b=(0,o.encodeToBase64)(`so1!`),x=RegExp(`(?<!\\\\):`,`g`),S=RegExp(`(?<!\\\\),`,`g`);var C=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends C{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!(0,o.isMissing)(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!(0,o.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(S).forEach(e=>{let[n,i]=e.split(x),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${b}${(0,o.encodeToBase64)(e)}`,decodeIdV1=e=>{if(!e.startsWith(b))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let t=e.split(b)[1];if(!t)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return(0,o.decodeFromBase64)(t)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>(0,o.isMissing)(e)?!1:e.startsWith(b),w=/\$\{([^}]+)\}/,T=`must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation`,isBareJexl=e=>!e.includes(`{{`)&&!e.includes(`}}`)&&!w.test(e),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return(0,o.getContentHash)({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if((0,o.isMissing)(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=(0,s.safeEvaluate)(`{{${n.result.trim()}}}`,t);if(!(0,o.isMissing)(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},resolveEvents=(e,t)=>{if(e===void 0)return[t.body];if((0,o.notMissing)(e)&&typeof e!=`string`)throw Error(`events.router.itemsPath must be a string, received ${typeof e}`);let n=(0,o.notMissing)(e)?e.trim():``;if(n.length===0)throw Error(`events.router.itemsPath is declared but must not be blank`);if(!isBareJexl(n))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It ${T}`);let r;try{r=(0,s.evaluate)(`{{${n}}}`,t,{throwOnEvalError:!0})}catch(e){throw Error(`Failed to evaluate events.router.itemsPath: ${n}. ${e.message}`)}if((0,o.isMissing)(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. The path resolved to nothing. Check it against the delivery payload, and put rules that match the whole delivery under events.router.delivery`);if(!Array.isArray(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It did not resolve to a list of events`);return r},firstMatch=(e,t)=>{for(let n of e){if(typeof n.when!=`string`)throw Error(`events.router rule when must be a string, received ${typeof n.when}`);let e=n.when.trim();if(e.length===0)continue;let r=(0,s.safeEvaluate)(`{{${e}}}`,t);if(r===null||r===!1||r===void 0)continue;let i=(0,o.isMissing)(n.then.input)?void 0:Object.fromEntries(Object.entries(n.then.input).map(([e,n])=>{if(typeof n!=`string`)throw Error(`events.router rule input ${e} must be a string, received ${typeof n}`);let r=n.trim();if(r.length===0)return[e,void 0];try{return[e,(0,s.evaluate)(`{{${r}}}`,t)]}catch(t){throw Error(`Failed to evaluate events.router rule input ${e}: ${r}. ${t.message}`)}}));return{action:n.then.action,input:i,event:t.event,eventIndex:t.eventIndex}}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if((0,o.isMissing)(n))return{matches:[],totalEvents:0};if((0,o.notMissing)(n.delivery)){let e=firstMatch(n.delivery,{...t,event:t.body,eventIndex:0});if((0,o.notMissing)(e))return{matches:[e],totalEvents:1}}let r=resolveEvents(n.itemsPath,t),i=[];return r.forEach((e,r)=>{let a=firstMatch(n.rules,{...t,event:e,eventIndex:r});(0,o.notMissing)(a)&&i.push(a)}),{matches:i,totalEvents:r.length}},E={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},D={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>D[e],isValidEnumRef=e=>e in D,O=[`preview`,`beta`,`ga`,`deprecated`,`internal`],k=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],A=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],j=[`read`,`write`,`delete`,`search`,`execute`],M=[`native`,`unified`],N=[`body`,`query`,`path`,`headers`],P=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],F=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],I=[`sync`,`async`],L=(0,o.zStrictObject)({r:o.z.record(o.z.string(),(0,o.zStrictObject)({n:o.z.number().optional().nullable(),c:o.z.string().optional().nullable(),p:o.z.number().optional().nullable()})),v:o.z.number(),t:o.z.number()}),R=(0,o.zStrictObject)({remote:o.z.record(o.z.string(),(0,o.zStrictObject)({pageNumber:o.z.number().optional(),providerPageCursor:o.z.string().optional(),position:o.z.number().optional()})),version:o.z.number(),timestamp:o.z.number()}),minifyCursor=e=>(0,o.encodeToBase64)(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if((0,o.isString)(e)){let t=(0,o.decodeFromBase64)(e),n=JSON.parse(t);return expandCursorObject(L.parse(n))}else return R.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,r=typeof t==`string`?expandCursor(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:s,...c}=r;return(0,o.getContentHash)(a)===(0,o.getContentHash)(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>(0,o.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,o.isMissing)(t)||r!==t.toString())&&(n=n&&(0,o.isMissing)(i.pageNumber)&&(0,o.isMissing)(i.position)&&(0,o.isMissing)(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},s=(0,o.isMissing)(n)&&(0,o.isMissing)(r)&&(0,o.isMissing)(i);return(0,o.isMissing)(e)?{remote:s?{}:{[t]:a},version:2,timestamp:Date.now()}:s?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof C;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const z={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},B={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},V={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},H={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},U=o.z.object({startUrl:o.z.string().url(),systemPrompt:o.z.string().optional(),viewport:(0,o.zStrictObject)({width:o.z.number().int().positive(),height:o.z.number().int().positive()}).optional(),locale:o.z.string().optional(),budgets:(0,o.zStrictObject)({maxDurationMs:o.z.number().int().positive(),maxSteps:o.z.number().int().positive()}),auth:(0,o.zStrictObject)({sensitiveKeys:o.z.array(o.z.string().min(1)).optional(),requiresSession:o.z.boolean().optional(),allowedDomains:o.z.array(o.z.string().min(1)).optional()}).optional()}),W=o.z.unknown(),G=(0,o.zStrictObject)({lambdaName:o.z.string(),region:o.z.string().optional(),endpoint:o.z.string().optional(),invocationType:o.z.enum([`RequestResponse`,`Event`,`DryRun`]).optional(),qualifier:o.z.string().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional()}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:o.z.string().optional()}),K=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),executedVersion:o.z.string().optional()}).optional(),ee=(0,o.zStrictObject)({strategy:o.z.literal(`aws4`),service:o.z.string(),region:o.z.string().optional()}),q=(0,o.zStrictObject)({strategy:o.z.literal(`hmac`),algorithm:o.z.enum([`sha1`,`sha256`,`sha512`]).optional(),headerName:o.z.string().optional(),prefix:o.z.string().optional(),dateFormat:o.z.enum([`iso8601`,`rfc2822`]).optional(),includeHost:o.z.boolean().optional(),includeBodyHash:o.z.boolean().optional(),outputFormat:o.z.enum([`header`,`basic`]).optional(),username:o.z.string().optional()}),J=o.z.discriminatedUnion(`strategy`,[ee,q]),te=(0,o.zStrictObject)({type:o.z.literal(`none`),signing:J.optional(),redirectUri:o.z.string().optional()}),Y=(0,o.zStrictObject)({type:o.z.literal(`basic`),username:o.z.string().optional(),password:o.z.string().optional(),encoding:o.z.string().optional(),redirectUri:o.z.string().optional()}),X=(0,o.zStrictObject)({type:o.z.literal(`bearer`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),redirectUri:o.z.string().optional()}),ne=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),re=(0,o.zStrictObject)({type:o.z.literal(`oauth2`),authorizationUrl:o.z.string().optional(),redirectUri:o.z.string().optional(),authorizationParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenUrl:o.z.string().optional(),tokenParams:o.z.record(o.z.string(),o.z.string()).optional(),tokenExpiresIn:o.z.number().optional(),tokenRefreshExpiresIn:o.z.number().optional(),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0),scopes:o.z.string().optional(),scopeDelimiter:o.z.string().optional(),customHeaders:o.z.record(o.z.string(),o.z.string()).optional(),pkce:o.z.boolean().optional(),additionalTokenFields:o.z.record(o.z.string(),o.z.string().optional()).optional(),callbackParams:o.z.record(o.z.string(),o.z.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))ne.has(r)&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional(),issuer:o.z.string().optional(),tokenResponse:(0,o.zStrictObject)({acceptTokenTypes:o.z.array(o.z.string()).optional(),accessToken:o.z.string().min(1).optional(),refreshToken:o.z.string().min(1).optional()}).optional()}),Z=o.z.discriminatedUnion(`type`,[te,Y,X,re]),ie=(0,o.zStrictObject)({certs:o.z.string().array().optional(),keys:o.z.string().array().optional()}).optional(),ae=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).optional().default(`get`),authorization:Z.optional(),responseMode:o.z.enum([`buffer`,`stream`]).optional().default(`buffer`),responseType:o.z.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`),encoding:o.z.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`),response:(0,o.zStrictObject)({dataKey:o.z.string().optional(),fileNameKey:o.z.string().optional(),contentTypeKey:o.z.string().optional(),contentType:o.z.string().optional(),contentIsBase64:o.z.boolean().optional().default(!1),urlKey:o.z.string().optional(),forwardAuth:o.z.boolean().optional().default(!1)}).optional(),maxRedirects:o.z.number().optional().default(5),followRedirects:o.z.boolean().optional().default(!0),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),oe=(0,o.zStrictObject)({data:o.z.union([o.z.string(),o.z.instanceof(Buffer)]).optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),headers:o.z.record(o.z.string(),o.z.union([o.z.string(),o.z.array(o.z.string())])).optional(),contentDisposition:o.z.string().optional(),fileMetadata:(0,o.zStrictObject)({contentType:o.z.string().optional(),contentLength:o.z.number().optional(),fileName:o.z.string().optional(),lastModified:o.z.string().optional(),etag:o.z.string().optional()}).optional(),finalUrl:o.z.string().optional()}).optional(),se=o.z.object({event:o.z.object({eventType:o.z.string(),eventId:o.z.coerce.string().optional(),eventDate:o.z.coerce.string().optional(),data:o.z.unknown().optional()}).optional()}),ce=o.z.record(o.z.string(),o.z.unknown()),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof c.HttpResponseError){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[(0,c.serializeHttpResponseError)(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new l.LambdaClient(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),u=new l.InvokeCommand({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),d=await c.send(u),f=d.Payload?Buffer.from(d.Payload).toString(`utf-8`):``,p;if(f.length===0)p=void 0;else try{p=JSON.parse(f)}catch{p=f}return{statusCode:d.StatusCode??200,payload:p,functionError:d.FunctionError,executedVersion:d.ExecutedVersion}},le=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>(0,s.isExpression)(e)||le.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>(0,s.isExpression)(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,ue=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;try{let n=(0,s.evaluate)(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||(0,s.safeEvaluate)(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,c=typeof o==`string`&&!le.test(o),l=t?.qualifier,u=typeof l==`string`&&!hasExpressionMarker(l),d={...t?(0,s.safeEvaluateRecord)(i===void 0?t:{...t,args:a},e):{},...c?{dataKey:o}:{},...u?{qualifier:l}:{}},f;try{f=G.parse(d)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:p,region:m,endpoint:h,invocationType:g,qualifier:_,args:v,dataKey:y}=f,b;try{b=await n({lambdaName:p,payload:buildPayloadFromArgs(v),region:m,endpoint:h,invocationType:g,qualifier:_,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(b.functionError){let t=typeof b.payload==`object`&&b.payload!==null&&`errorMessage`in b.payload&&typeof b.payload.errorMessage==`string`?b.payload.errorMessage:`Lambda function error: ${b.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:b.functionError}],output:{statusCode:b.statusCode,message:t,data:b.payload,raw:b}}}return{block:e,successful:!0,output:{data:y?ue(b.payload,y):b.payload,raw:b,statusCode:b.statusCode,executedVersion:b.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,authorization:f,args:p,responseMode:m,responseType:h,encoding:g,response:_,maxRedirects:v,followRedirects:y}=ae.parse(a),b=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=p?(0,c.parseRequestParameters)(p):{query:{},body:{},headers:{}},S=typeof x?.body==`string`?void 0:x?.body,C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(f)?f:Z.parse(b)),w={...x?.headers??{},...C},T=e.connector?.rateLimit,E=e.connector?.concurrency,D=T!==void 0||E!==void 0?{rateLimits:T,concurrency:E}:void 0,O=buildRequestContext(e);if(m===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,maxRedirects:y?v:0,requestConfig:D,context:O,response:_,responseType:h,authHeaders:C});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:l??``,url:u,method:d,headers:w,queryParams:x?.query,body:S,responseType:h,encoding:g,response:_,maxRedirects:y?v:0,requestConfig:D,context:O,authHeaders:C})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,maxRedirects:d,requestConfig:f,context:p,response:m,responseType:h,authHeaders:g}=e,_=`${r}${i}`;if(!_.startsWith(`http://`)&&!_.startsWith(`https://`))throw Error(`Invalid URL: "${_}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if((0,o.notMissing)(m?.dataKey)||(0,o.notMissing)(m?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:s,queryParams:c,body:l,responseType:h??`arraybuffer`,encoding:`none`,response:m,maxRedirects:d,requestConfig:f,context:p,authHeaders:g??{}}),_=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),v={...e.fileMetadata,contentLength:_.length};return{block:t,successful:!0,streamOutput:{stream:u.Readable.from(_),headers:(0,o.notMissing)(v.contentType)?{"content-type":v.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:v}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:_,method:a,headers:s,queryParams:c,payload:l,maxRedirects:d,requestConfig:f,context:p}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:s,context:c,authHeaders:l}=e,u=n.data;if(r.urlKey){let e=extractValueByPath(u,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?l:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:s,context:c}),d=encodeFileData(n.data,i),f=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(f.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(f.contentType=e)}(0,o.isMissing)(f.contentType)&&(0,o.notMissing)(r.contentType)&&(f.contentType=r.contentType);let p=buildContentDisposition(f);return{data:d,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:p,fileMetadata:f,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(u,r.dataKey);if((0,o.isMissing)(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(u,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(u,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}(0,o.isMissing)(a.contentType)&&(0,o.notMissing)(r.contentType)&&(a.contentType=r.contentType);let s=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:s,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if((0,o.isMissing)(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=(0,o.isString)(e[`content-type`])?e[`content-type`]:void 0,n=(0,o.isString)(e[`content-length`])?e[`content-length`]:void 0,r=(0,o.isString)(e[`content-disposition`])?e[`content-disposition`]:void 0,i=(0,o.isString)(e[`last-modified`])?e[`last-modified`]:void 0,a=(0,o.isString)(e.etag)?e.etag:void 0,s=n?parseInt(n,10):void 0,c=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(s)?void 0:s,fileName:c,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return d.default.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?(0,s.safeEvaluateRecord)(t,e):{},{event:r}=se.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},de=o.z.object({stepsDataToGroup:o.z.array(o.z.string()),isSingleRecord:o.z.boolean().optional()}),fe=o.z.object({data:o.z.unknown()}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=de.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...(0,o.notMissing)(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},pe=__name(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=me(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=me(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),me=__name((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=he(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),he=__name((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=(0,s.evaluate)(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return o.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return o.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return o.getCountryCodeByCountryCode;case`country_name_by_country_name`:return o.getCountryNameByCountryName;case`country_name_by_alpha3code`:return o.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return o.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return o.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return o.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return o.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return o.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return o.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return o.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return o.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return o.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return o.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return o.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return o.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return o.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return o.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return o.getCountrySubDivisionNameBySubDivisionCode;case`document_file_format_from_extension`:return o.getDocumentFileFormatFromExtension;default:return}},ge=(0,o.zStrictObject)({targetFieldKey:o.z.string(),alias:o.z.string().optional(),expression:o.z.string().optional(),values:o.z.unknown().optional(),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.z.boolean().default(!1),custom:o.z.boolean().default(!1),hidden:o.z.boolean().default(!1),enumMapper:(0,o.zStrictObject)({matcher:o.z.string().or((0,o.zStrictObject)({matchExpression:o.z.string(),value:o.z.string()}).array())}).optional(),properties:o.z.lazy(()=>ge).array().optional(),requiredScopes:o.z.string().array().optional()}),_e=o.z.object({fields:ge.array(),dataSource:o.z.string(),externalSources:o.z.record(o.z.string(),o.z.string()).optional()}),ve=o.z.object({data:o.z.unknown()}),mergeSourceWithState=(e,t)=>(0,o.isObject)(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=_e.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),c=(0,s.evaluate)(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!c)return{block:e,successful:!0};let l=Object.keys(a??{})?.reduce((e,t)=>(e[t]=(0,s.evaluate)(a?.[t],o),e),{}),u;if(Array.isArray(c))u=c.map(e=>{let t=Q(r,{...e,external:l},o);return n.push(...t?.errors||[]),t?.record});else{let e=Q(r,{...c,external:l},o);u=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:u},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),s=Q(e.properties,a,r);return(0,o.notMissing)(s?.errors)&&n.push(...s.errors),s?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=(0,s.evaluate)(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=Q(e.properties,t,i);return(0,o.notMissing)(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=(0,o.notMissing)(e.values)?e.values:t,a=Q(e.properties,i,r);return(0,o.notMissing)(a?.errors)&&n.push(...a.errors),a?.record},ye=__name((e,t,n,r,i)=>{if(!(0,o.isMissing)(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),Q=__name((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=ye(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if((0,s.isValidExpression)(e))try{return(0,s.evaluate)(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return be(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},be=__name((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,s.evaluate)(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=be(e,t,n),i=(0,o.notMissing)(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if((0,o.isString)(a)){let n=getEnumMatcher(a);return(0,o.notMissing)(n)?{value:{value:((0,o.notMissing)(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if((0,s.evaluate)(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},xe=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string().optional(),method:o.z.enum([`tools/call`,`tools/list`]).default(`tools/call`),toolName:o.z.string().optional(),timeout:o.z.number().int().positive().optional(),authorization:Z.optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional()}).array().optional()}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),Se=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),buildMcpClient=e=>new c.McpClient(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if((0,o.notMissing)(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l;try{l=xe.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:u,url:d,method:f,toolName:p,timeout:m,authorization:h,args:g}=l,_=`${u??``}${d??``}`;if(!_)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let v=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,y;try{y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(v??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let b=e.connector?.rateLimit,x=e.connector?.concurrency,S=n({serverUrl:_,headers:y,timeout:m,requestConfig:b!==void 0||x!==void 0?{rateLimits:b,concurrency:x}:void 0,context:buildRequestContext(e)});try{if(f===`tools/list`){let t=await S.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!p)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await S.callTool({name:p,arguments:buildToolArguments(g)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${p}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:p}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await S.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>f.Saml20.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},m={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+(0,p.v4)()},h=Buffer.from(l(m)).toString(`base64`);return await u(1e3),h},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
2
2
  ${n}
3
- -----END PRIVATE KEY-----`)},$=__name(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),xe=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`)return null;if($(t)){let n=(0,s.safeEvaluate)(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return null;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return(0,o.isMissing)(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&$(n),a=r&&$(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},Se=o.z.object({baseUrl:o.z.string(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:X.optional(),saml:(0,o.zStrictObject)({objectKey:o.z.string(),key:o.z.string(),clientId:o.z.string(),cert:o.z.unknown().optional(),issuer:o.z.string().optional(),lifetime:o.z.number().optional(),nameId:o.z.string().optional(),audience:o.z.string().optional(),nameIdentifierFormat:o.z.string().optional(),tokenEndpoint:o.z.string().optional()}).optional(),response:(0,o.zStrictObject)({indexField:o.z.string().optional(),dataKey:o.z.string().optional(),nextKey:o.z.string().optional(),nextKeyIn:o.z.enum([`data`,`headers`]).optional()}).optional(),iterator:(0,o.zStrictObject)({key:o.z.string(),in:o.z.enum([`query`,`body`]),condition:o.z.string().optional(),mode:o.z.enum([`cursor`,`offset`,`page`]).optional(),startPage:o.z.number().int().min(0).max(2**53-1).optional(),maxPage:o.z.number().int().positive().max(1e4).optional()}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable(),position:o.z.number().optional().nullable()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),cacheTTL:o.z.number().int().nonnegative().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Ce=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),next:o.z.string().optional().nullable(),position:o.z.number().optional()}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,iterator:{...u?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,u?.response)},f=d.authorization;if((0,o.notMissing)(f)){let t=X.safeParse(f);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:p,url:m,method:h,response:g,authorization:_,iterator:v,cursor:y,customErrors:b,encodeQueryParams:x,args:S,saml:C,cacheTTL:w}=Se.parse(d),T=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],E=T?.authorization,D=T?.certificates,O=D?(0,c.buildHttpsAgent)(D):void 0,k=(0,o.notMissing)(_)?_:X.parse(E);if(k.type===`none`&&(0,o.notMissing)(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},j=(0,c.createAuthorizationHeaders)(k),M={...A?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=buildRequestContext(e),L=(0,o.notMissing)(C)?{[C.objectKey]:await generateSamlAssertion({key:C.key,clientId:C.clientId,cert:C.cert,issuer:C.issuer,lifetime:C.lifetime,audience:C.audience,nameId:C.nameId,nameIdentifierFormat:C.nameIdentifierFormat,tokenEndpoint:C.tokenEndpoint})}:{},R=v.mode===`offset`,z=v.mode===`page`,B=v.maxPage??1e3,V=B+1,H=z?resolveInitialPage(y?.token,v.startPage??1):y?.token??null,U=null,ee=null,W=[],G=[],te=[],K=a,q=y?.position??0,ne=!0,J=!0,Y=!0,re=null;do{if(z&&Number(H)>V)return buildStepErrorOutput(maxPageExceededError(B,H),e);ne?ne=!1:R||(q=0),H===null?R&&(v.in===`query`?A.query[v.key]=q.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=q))):v.in===`query`?(0,o.isObject)(H)?Object.entries(H).forEach(([e,t])=>{A.query[`${v.key}[${e}]`]=t?.toString()??``}):A.query[v.key]=H.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=H));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...A?.query},encodeQueryParams:x,method:h,headers:{...M},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...L},customErrorConfigs:b,requestConfig:F,httpsAgent:O,credentials:e.credentials,context:I,cacheTTL:w})}catch(t){return buildStepErrorOutput(t,e)}if(U=H,G=g?.dataKey?xe(t.data,g.dataKey):t.data,!Array.isArray(G)){let n=z?` at page ${U}`:``,r=g?.dataKey?` at "${g.dataKey}"`:``,i=G===null?`null`:typeof G;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),te.push(t),ee=t?.status,J=!0;break}if(z){let t=(0,o.getContentHash)(G);if(t===re){e.logger?.warning({message:`Pagination stopped at page ${U}: the provider returned the previous page again, so the page number is not advancing`}),J=!0;break}re=t}if(z&&Number(U)>B&&G.length>0)return buildStepErrorOutput(maxPageExceededError(B,U),e);let r=R?G?.slice(0,K):G?.slice(q,q+K);K-=r.length,q+=r.length,te.push(t),W=W.concat(r),ee=t?.status,H=z?incrementPage(Number(U)):we({result:t,response:g}),Y=(0,o.notMissing)(v.condition)?(0,s.safeEvaluate)(v.condition,t.data)===!0:!0;let i=q>=(G?.length??0),c=(0,o.notMissing)(g?.nextKey),l=r.length===G.length&&K===0;!R&&(c||z)&&i&&(q=0,U=H),J=R?!Y||(0,o.isMissing)(H)&&W.length<a:z?i&&(!Y||W.length<a):c?i&&((0,o.isMissing)(H)||!Y):!Y||(0,o.isMissing)(H)&&W.length<a||l}while((R||(0,o.notMissing)(H))&&Y&&W.length<a&&G?.length>0);let ie=Te(W,g),Z=J?void 0:U;return{block:e,successful:!0,output:{data:ie,raw:te,statusCode:ee,next:z&&typeof Z==`number`?Z.toString():Z,position:J?void 0:q}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,we=__name(({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),Te=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ee=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:X.optional(),certificates:re,saml:(0,o.zStrictObject)({objectKey:o.z.string(),key:o.z.string(),clientId:o.z.string(),cert:o.z.unknown().optional(),issuer:o.z.string().optional(),lifetime:o.z.number().optional(),nameId:o.z.string().optional(),audience:o.z.string().optional(),nameIdentifierFormat:o.z.string().optional(),tokenEndpoint:o.z.string().optional()}).optional(),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),cacheTTL:o.z.number().int().nonnegative().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),inline:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),De=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,l=a&&isJexlExpression(a),u=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},d={...u,customErrors:t?.customErrors,response:l?{...u?.response??{},dataKey:a}:u?.response},{baseUrl:f,url:p,method:h,response:g,authorization:_,certificates:v,customErrors:y,encodeQueryParams:b,args:x,saml:S,cacheTTL:C}=Ee.parse(d),w=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],T=w?.authorization,E=v??w?.certificates,D=E?(0,c.buildHttpsAgent)(E):void 0,O=x?(0,c.parseRequestParameters)(x):{query:{},body:{},headers:{}},k=x?.some(e=>e.in===`body`&&e.inline===!0)??!1,A=(0,o.notMissing)(_)?_:X.parse(T),j=(0,c.createAuthorizationHeaders)(A),M={...O?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=(0,o.notMissing)(S)?{[S.objectKey]:await generateSamlAssertion({key:S.key,clientId:S.clientId,cert:S.cert,issuer:S.issuer,lifetime:S.lifetime,audience:S.audience,nameId:S.nameId,nameIdentifierFormat:S.nameIdentifierFormat,tokenEndpoint:S.tokenEndpoint})}:{},L=typeof O?.body==`string`||Array.isArray(O?.body)?O?.body:{...O?.body,...I};if(A.type===`none`&&A.signing?.strategy){if(b===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=A.signing,n=e.credentials??{};try{let e=(0,c.getSigningStrategy)(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:h,url:`${f}${p}`,headers:M,query:O?.query??{},body:L},n,t);Object.assign(M,r)}catch(t){return buildStepErrorOutput(t,e)}}let R;try{R=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:O?.query,encodeQueryParams:b,method:h,headers:M,body:L,customErrorConfigs:y,requestConfig:F,httpsAgent:D,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:C})}catch(t){return k&&(isErrorWithResponseBody(t)&&(t.response.body=m.REDACT_CENSOR),isErrorWithResponseConfigData(t)&&(t.response.config.data=m.REDACT_CENSOR)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Oe(g?.dataKey?resolveDataKey(R.data,g.dataKey):R.data,g),raw:k&&R&&`body`in R?{...R,body:m.REDACT_CENSOR}:R,statusCode:R?.status,message:R?.message}}},resolveDataKey=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Oe=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),ke=o.z.union([o.z.string(),o.z.number()]),Ae=(0,o.zStrictObject)({algorithm:o.z.literal(`RS256`),privateKey:o.z.string(),claims:o.z.record(o.z.string(),ke)}),je=(0,o.zStrictObject)({token:o.z.string(),expiresIn:o.z.number(),publicKeyFingerprint:o.z.string()}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${(0,h.createHash)(`sha256`).update(t).digest(`base64`)}`},Me=/^now$/,Ne=/^now\+(?<amount>\d+)(?<unit>[smh])$/,Pe=`{publicKeyFingerprint}`,Fe={s:1,m:60,h:3600},Ie=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(Pe)?t.split(Pe).join(r):t;if(!Ie.has(e))return i;if(Me.test(i))return n;let a=i.match(Ne);return a?.groups?n+Number(a.groups.amount)*Fe[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?(0,s.safeEvaluateRecord)(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Ae.parse(n),o=(0,h.createPrivateKey)(i),c=computePublicKeyFingerprint((0,h.createPublicKey)(o)),l=Math.floor(Date.now()/1e3),u={};for(let[e,t]of Object.entries(a))u[e]=resolveClaimValue(e,t,{now:l,publicKeyFingerprint:c});let{iat:d,exp:f}=u;if(typeof d!=`number`||typeof f!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(f<=d)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let p=await new g.SignJWT(u).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:p,expiresIn:f-d,publicKeyFingerprint:c}}}catch(t){return buildStepErrorOutput(t,e)}},Le=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:o.z.discriminatedUnion(`type`,[(0,o.zStrictObject)({type:o.z.literal(`none`)}),(0,o.zStrictObject)({type:o.z.literal(`basic`),username:o.z.string().optional(),password:o.z.string().optional(),encoding:o.z.string().optional()}),(0,o.zStrictObject)({type:o.z.literal(`bearer`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0)}),(0,o.zStrictObject)({type:o.z.literal(`oauth2`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0)})]).optional(),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional(),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string(),namespace:o.z.string()}).array().optional(),soapOperation:o.z.string().optional(),soapAction:o.z.string().optional(),useSoapContext:o.z.boolean().optional().default(!0),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional(),nextKey:o.z.string().optional(),nextKeyIn:o.z.enum([`data`,`headers`]).optional()}).optional(),iterator:(0,o.zStrictObject)({key:o.z.string(),in:o.z.enum([`query`,`body`])}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable(),position:o.z.number().optional().nullable()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Re=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),next:o.z.string().optional().nullable(),position:o.z.number().optional()}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,u?.response)},f=t?.envelope,{baseUrl:p,url:m,method:h,response:g,iterator:_,cursor:v,authorization:y,customErrors:b,encodeQueryParams:x,args:S,soapOperation:C,namespaces:w,soapAction:T,useSoapContext:E}=Le.parse(d),D=u?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,O=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},k=(0,c.createAuthorizationHeaders)((0,o.notMissing)(y)?y:X.parse(D)),A={...O?.headers??{},...k},j=e.connector?.rateLimit,M=e.connector?.concurrency,N={...j!==void 0||M!==void 0?{rateLimits:j,concurrency:M}:void 0,soapOperation:C,namespaces:w,soapAction:T,soapContext:E?{username:e.credentials?.username,password:e.credentials?.password}:void 0},P=v?.token??null,F=null,I=null,L=[],R=[],z=[],B=a,V=v?.position??0,H=!0,U;do{H?H=!1:V=0,P!==null&&(_.in===`query`?O.query[_.key]=P.toString():_.in===`body`&&(O.body[_.key]=P));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...O?.query},encodeQueryParams:x,method:h,headers:A,body:O?.body,customErrorConfigs:b,requestConfig:{...N,...(0,o.notMissing)(f)&&{envelope:evaluateEnvelope(f,e,P)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}F=P,R=g?.dataKey?xe(t.data,g.dataKey):t.data,Array.isArray(R)||(R=R?[R]:[]);let r=R?.slice(V,V+B);B-=r.length,V+=r.length,z.push(t),L=L.concat(r),I=t?.status,P=resolveNextIterator({result:t,response:g});let i=V>=(R?.length??0),s=(0,o.notMissing)(g?.nextKey),c=r.length===R.length&&B===0;s&&i&&(V=0,F=P),U=s?i&&(0,o.isMissing)(P):(0,o.isMissing)(P)&&L.length<a||c}while((0,o.notMissing)(P)&&L.length<a&&R?.length>0);return{block:e,successful:!0,output:{data:ze(L,g),raw:z,statusCode:I,next:U?void 0:stringifyCursorToken(F),position:U?void 0:V}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?(0,s.safeEvaluate)(e,r):(0,s.safeEvaluateRecord)(e,r)},resolveNextIterator=({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},ze=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Be=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:X.optional(),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional(),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string(),namespace:o.z.string()}).array().optional(),soapOperation:o.z.string().optional(),soapAction:o.z.string().optional(),useSoapContext:o.z.boolean().optional().default(!0),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Ve=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l={...a,customErrors:t?.customErrors},{baseUrl:u,url:d,method:f,response:p,authorization:m,customErrors:h,encodeQueryParams:g,args:_,soapOperation:v,namespaces:y,envelope:b,soapAction:x,useSoapContext:S}=Be.parse(l),C=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,w=_?(0,c.parseRequestParameters)(_):{query:{},body:{},headers:{}},T=(0,c.createAuthorizationHeaders)((0,o.notMissing)(m)?m:X.parse(C)),E={...w?.headers??{},...T},D=e.connector?.rateLimit,O=e.connector?.concurrency,k={...D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,soapOperation:v,namespaces:y,envelope:b,soapAction:x,soapContext:S?{username:e.credentials?.username,password:e.credentials?.password}:void 0},A;try{A=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:w?.query,encodeQueryParams:g,method:f,headers:E,body:w?.body,customErrorConfigs:h,requestConfig:k,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:He(p?.dataKey?A.data[p?.dataKey]:A.data,p),raw:A,statusCode:A?.status,message:A?.message}}},He=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ue=o.z.object({values:o.z.string().or(o.z.record(o.z.string(),o.z.unknown())).or(o.z.array(o.z.unknown()))}),We=o.z.object({data:o.z.unknown()}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Ue.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>(0,o.isString)(e)?(0,s.safeEvaluate)(e,t):(0,o.isObject)(e)?(0,s.safeEvaluateRecord)(e,t):e,Ge=o.z.object({targetFieldKey:o.z.string(),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.z.boolean().default(!1),custom:o.z.boolean().default(!1),hidden:o.z.boolean().default(!1),properties:o.z.lazy(()=>Ge).array().optional(),requiredScopes:o.z.string().array().optional()}),Ke=o.z.object({fields:Ge.array().optional(),dataSource:o.z.string()}),qe=o.z.object({data:o.z.unknown()});let Je=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if((0,o.isMissing)(e))return null;switch(t){case`string`:return(0,o.safeParseToString)({value:e});case`number`:return(0,o.safeParseToNumber)({value:e});case`boolean`:return(0,o.safeParseToBoolean)({value:e});case`datetime_string`:return(0,o.safeParseToDateTimeString)({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values(Je).includes(e),Ye=__name(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>Xe(e,t)):Xe(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),Xe=__name((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Ke.parse(t),i=(0,s.evaluate)(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,o.notMissing)(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Ze=(0,o.zStrictObject)({content:o.z.string().meta({description:`The file content as base64 encoded string`}),contentType:o.z.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),Qe=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).default(`post`),authorization:X.optional(),binaryContent:Ze.meta({description:`Raw binary content for octet-stream uploads`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),$e=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,authorization:p,binaryContent:m,args:h,customErrors:g}=Qe.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?(0,c.parseRequestParameters)(h):{query:{},body:{},headers:{}},y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(p)?p:X.parse(_)),b=Buffer.from(m.content,`base64`),x={"content-type":m.contentType??`application/octet-stream`,...v?.headers??{},...y},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T;try{T=await e.httpClient.request({url:`${l??``}${u}`,method:d,headers:x,queryParams:v?.query,payload:b,requestConfig:w,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=(0,c.translateCustomError)(T,g,e.credentials);return(0,c.isFailedStatusCode)(E?.status)?{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(new c.HttpResponseError(E,E.message))],output:{statusCode:E.status,message:E.message}}:{block:e,successful:!0,output:{data:et(f?.dataKey?E.data[f?.dataKey]:E.data,f),raw:E,statusCode:E?.status,message:E?.message}}},et=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),tt=(0,o.zStrictObject)({fieldName:o.z.string().meta({description:`The form field name for the file`}),content:o.z.string().meta({description:`The file content as base64 encoded string`}),filename:o.z.string().meta({description:`The filename to use in the upload`}),contentType:o.z.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),nt=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).default(`post`),authorization:X.optional(),file:tt.meta({description:`The file to upload`}),additionalFields:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional(),contentType:o.z.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),rt=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,l=t?(0,s.safeEvaluateRecord)({...t,args:i,additionalFields:a},e):{},u={...l,customErrors:t?.customErrors},{baseUrl:d,url:f,method:p,response:m,authorization:h,file:g,additionalFields:v,args:y,customErrors:b}=nt.parse(u),x=l?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,S=y?(0,c.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:X.parse(x)),w=new _.default;if(v)for(let e of v){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);w.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let T=Buffer.from(g.content,`base64`);w.append(g.fieldName,T,{filename:g.filename,contentType:g.contentType});let E={...w.getHeaders(),...S?.headers??{},...C},D=e.connector?.rateLimit,O=e.connector?.concurrency,k=D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,A;try{A=await e.httpClient.request({url:`${d??``}${f}`,method:p,headers:E,queryParams:S?.query,payload:w,requestConfig:k,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let j=(0,c.translateCustomError)(A,b,e.credentials);return(0,c.isFailedStatusCode)(j?.status)?buildStepErrorOutput(new c.HttpResponseError(j,j.message),e):{block:e,successful:!0,output:{data:indexResponseData(m?.dataKey?j.data[m?.dataKey]:j.data,m),raw:j,statusCode:j?.status,message:j?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let it=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const at={typecast:{v1:{fn:Ye},v2:{fn:typecastStepFunction,inputSchema:Ke,outputSchema:qe}},map_fields:{v1:{fn:de},v2:{fn:mapFieldsStepFunction,inputSchema:he,outputSchema:ge}},request:{v1:{fn:requestStepFunction,inputSchema:Ee,outputSchema:De}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:le,outputSchema:ue}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:Se,outputSchema:Ce}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:Be,outputSchema:Ve}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:Le,outputSchema:Re}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Ue,outputSchema:We}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:nt,outputSchema:rt}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:Qe,outputSchema:$e}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:ie,outputSchema:Z}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:ae,outputSchema:oe}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:V,outputSchema:H}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:U,outputSchema:ee}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Ae,outputSchema:je}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:ye,outputSchema:be}}},formatZodIssues=(e,t,n)=>e instanceof o.z.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},ot={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=at}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;exports.AUTHORIZATION_SCHEMA=X,exports.ActionTypes=O,exports.AuthType=B,exports.BROWSER_USE_INPUT_PARAMS=V,exports.BROWSER_USE_OUTPUT=H,exports.CODE_EXECUTION_LAMBDA_INPUT_PARAMS=U,exports.CODE_EXECUTION_LAMBDA_OUTPUT=ee,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.ChangelogLabels=D,exports.CoreError=C,exports.DOWNLOAD_FILE_INPUT_PARAMS=ie,exports.DOWNLOAD_FILE_OUTPUT=Z,exports.EMIT_EVENT_INPUT_PARAMS=ae,exports.EMIT_EVENT_OUTPUT=oe,exports.Effects=k,exports.ExecutionModes=P,exports.FORMAT_PATTERNS=w,exports.GROUP_DATA_INPUT_PARAMS=le,exports.GROUP_DATA_OUTPUT=ue,exports.INPUT_ENUM_REGISTRY=T,exports.InputFormats=M,exports.InputLocations=j,exports.InputTypes=N,exports.MAP_FIELDS_INPUT_PARAMS=he,exports.MAP_FIELDS_OUTPUT=ge,exports.MCP_REQUEST_INPUT_PARAMS=ye,exports.MCP_REQUEST_OUTPUT=be,exports.PAGINATED_REQUEST_INPUT_PARAMS=Se,exports.PAGINATED_REQUEST_OUTPUT=Ce,exports.REQUEST_INPUT_PARAMS=Ee,exports.REQUEST_OUTPUT=De,exports.ReleaseStages=E,exports.SIGN_JWT_INPUT_PARAMS=Ae,exports.SIGN_JWT_OUTPUT=je,exports.SOAP_PAGINATED_REQUEST_INPUT_PARAMS=Le,exports.SOAP_PAGINATED_REQUEST_OUTPUT=Re,exports.SOAP_REQUEST_INPUT_PARAMS=Be,exports.SOAP_REQUEST_OUTPUT=Ve,exports.STATIC_VALUES_INPUT_PARAMS=Ue,exports.STATIC_VALUES_OUTPUT=We,exports.SchemaTypes=A,exports.SourceType=L,exports.StepFunctionName=it,exports.StepFunctionsFactory=ot,exports.StepFunctionsRegistry=at,exports.StreamType=z,exports.TYPECAST_INPUT_PARAMS=Ke,exports.TYPECAST_OUTPUT=qe,exports.TransportType=R,exports.UPLOAD_BINARY_INPUT_PARAMS=Qe,exports.UPLOAD_BINARY_OUTPUT=$e,exports.UPLOAD_FILE_INPUT_PARAMS=nt,exports.UPLOAD_FILE_OUTPUT=rt,exports.areCursorsEqual=areCursorsEqual,exports.buildExpressionContext=buildExpressionContext,exports.computeDataSyncFingerprint=computeDataSyncFingerprint,exports.decodeCompositeId=decodeCompositeId,exports.encodeCompositeId=encodeCompositeId,exports.evaluateEventRouter=evaluateEventRouter,exports.evaluateExternalAccountIdExtractor=evaluateExternalAccountIdExtractor,exports.expandCursor=expandCursor,exports.getCategoryDetails=getCategoryDetails,exports.getInputEnumValues=getInputEnumValues,exports.getIteratorLocation=getIteratorLocation,exports.getPaginationKeys=getPaginationKeys,exports.isCompositeId=isCompositeId,exports.isCoreError=isCoreError,exports.isCursorEmpty=isCursorEmpty,exports.isForeachStep=isForeachStep,exports.isValidCategory=isValidCategory,exports.isValidEnumRef=isValidEnumRef,exports.minifyCursor=minifyCursor,exports.stripIncrementalParams=stripIncrementalParams,exports.stripPaginationParams=stripPaginationParams,exports.updateCursor=updateCursor;
3
+ -----END PRIVATE KEY-----`)},$=__name(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),Ce=__name((e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`)return null;if($(t)){let n=(0,s.safeEvaluate)(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return null;let n=(0,s.safeEvaluate)($(t)?t:`$.${t}`,e);return(0,o.isMissing)(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&$(n),a=r&&$(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},we=o.z.object({baseUrl:o.z.string(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:Z.optional(),saml:(0,o.zStrictObject)({objectKey:o.z.string(),key:o.z.string(),clientId:o.z.string(),cert:o.z.unknown().optional(),issuer:o.z.string().optional(),lifetime:o.z.number().optional(),nameId:o.z.string().optional(),audience:o.z.string().optional(),nameIdentifierFormat:o.z.string().optional(),tokenEndpoint:o.z.string().optional()}).optional(),response:(0,o.zStrictObject)({indexField:o.z.string().optional(),dataKey:o.z.string().optional(),nextKey:o.z.string().optional(),nextKeyIn:o.z.enum([`data`,`headers`]).optional()}).optional(),iterator:(0,o.zStrictObject)({key:o.z.string(),in:o.z.enum([`query`,`body`]),condition:o.z.string().optional(),mode:o.z.enum([`cursor`,`offset`,`page`]).optional(),startPage:o.z.number().int().min(0).max(2**53-1).optional(),maxPage:o.z.number().int().positive().max(1e4).optional()}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable(),position:o.z.number().optional().nullable()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),cacheTTL:o.z.number().int().nonnegative().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Te=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),next:o.z.string().optional().nullable(),position:o.z.number().optional()}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,iterator:{...u?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,u?.response)},f=d.authorization;if((0,o.notMissing)(f)){let t=Z.safeParse(f);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:p,url:m,method:h,response:g,authorization:_,iterator:v,cursor:y,customErrors:b,encodeQueryParams:x,args:S,saml:C,cacheTTL:w}=we.parse(d),T=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],E=T?.authorization,D=T?.certificates,O=D?(0,c.buildHttpsAgent)(D):void 0,k=(0,o.notMissing)(_)?_:Z.parse(E);if(k.type===`none`&&(0,o.notMissing)(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},j=(0,c.createAuthorizationHeaders)(k),M={...A?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=buildRequestContext(e),L=(0,o.notMissing)(C)?{[C.objectKey]:await generateSamlAssertion({key:C.key,clientId:C.clientId,cert:C.cert,issuer:C.issuer,lifetime:C.lifetime,audience:C.audience,nameId:C.nameId,nameIdentifierFormat:C.nameIdentifierFormat,tokenEndpoint:C.tokenEndpoint})}:{},R=v.mode===`offset`,z=v.mode===`page`,B=v.maxPage??1e3,V=B+1,H=z?resolveInitialPage(y?.token,v.startPage??1):y?.token??null,U=null,W=null,G=[],K=[],ee=[],q=a,J=y?.position??0,te=!0,Y=!0,X=!0,ne=null;do{if(z&&Number(H)>V)return buildStepErrorOutput(maxPageExceededError(B,H),e);te?te=!1:R||(J=0),H===null?R&&(v.in===`query`?A.query[v.key]=J.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=J))):v.in===`query`?(0,o.isObject)(H)?Object.entries(H).forEach(([e,t])=>{A.query[`${v.key}[${e}]`]=t?.toString()??``}):A.query[v.key]=H.toString():v.in===`body`&&(Array.isArray(A.body)||(A.body[v.key]=H));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...A?.query},encodeQueryParams:x,method:h,headers:{...M},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...L},customErrorConfigs:b,requestConfig:F,httpsAgent:O,credentials:e.credentials,context:I,cacheTTL:w})}catch(t){return buildStepErrorOutput(t,e)}if(U=H,K=g?.dataKey?Ce(t.data,g.dataKey):t.data,!Array.isArray(K)){let n=z?` at page ${U}`:``,r=g?.dataKey?` at "${g.dataKey}"`:``,i=K===null?`null`:typeof K;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),ee.push(t),W=t?.status,Y=!0;break}if(z){let t=(0,o.getContentHash)(K);if(t===ne){e.logger?.warning({message:`Pagination stopped at page ${U}: the provider returned the previous page again, so the page number is not advancing`}),Y=!0;break}ne=t}if(z&&Number(U)>B&&K.length>0)return buildStepErrorOutput(maxPageExceededError(B,U),e);let r=R?K?.slice(0,q):K?.slice(J,J+q);q-=r.length,J+=r.length,ee.push(t),G=G.concat(r),W=t?.status,H=z?incrementPage(Number(U)):Ee({result:t,response:g}),X=(0,o.notMissing)(v.condition)?(0,s.safeEvaluate)(v.condition,t.data)===!0:!0;let i=J>=(K?.length??0),c=(0,o.notMissing)(g?.nextKey),l=r.length===K.length&&q===0;!R&&(c||z)&&i&&(J=0,U=H),Y=R?!X||(0,o.isMissing)(H)&&G.length<a:z?i&&(!X||G.length<a):c?i&&((0,o.isMissing)(H)||!X):!X||(0,o.isMissing)(H)&&G.length<a||l}while((R||(0,o.notMissing)(H))&&X&&G.length<a&&K?.length>0);let re=De(G,g),ie=Y?void 0:U;return{block:e,successful:!0,output:{data:re,raw:ee,statusCode:W,next:z&&typeof ie==`number`?ie.toString():ie,position:Y?void 0:J}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,Ee=__name(({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),De=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Oe=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:Z.optional(),certificates:ie,saml:(0,o.zStrictObject)({objectKey:o.z.string(),key:o.z.string(),clientId:o.z.string(),cert:o.z.unknown().optional(),issuer:o.z.string().optional(),lifetime:o.z.number().optional(),nameId:o.z.string().optional(),audience:o.z.string().optional(),nameIdentifierFormat:o.z.string().optional(),tokenEndpoint:o.z.string().optional()}).optional(),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),cacheTTL:o.z.number().int().nonnegative().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),inline:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:o.z.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),ke=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,l=a&&isJexlExpression(a),u=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},d={...u,customErrors:t?.customErrors,response:l?{...u?.response??{},dataKey:a}:u?.response},{baseUrl:f,url:p,method:h,response:g,authorization:_,certificates:v,customErrors:y,encodeQueryParams:b,args:x,saml:S,cacheTTL:C}=Oe.parse(d),w=u?.authentication?.[e.context.authenticationType]?.[e.context.environment],T=w?.authorization,E=v??w?.certificates,D=E?(0,c.buildHttpsAgent)(E):void 0,O=x?(0,c.parseRequestParameters)(x):{query:{},body:{},headers:{}},k=x?.some(e=>e.in===`body`&&e.inline===!0)??!1,A=(0,o.notMissing)(_)?_:Z.parse(T),j=(0,c.createAuthorizationHeaders)(A),M={...O?.headers??{},...j},N=e.connector?.rateLimit,P=e.connector?.concurrency,F=N!==void 0||P!==void 0?{rateLimits:N,concurrency:P}:void 0,I=(0,o.notMissing)(S)?{[S.objectKey]:await generateSamlAssertion({key:S.key,clientId:S.clientId,cert:S.cert,issuer:S.issuer,lifetime:S.lifetime,audience:S.audience,nameId:S.nameId,nameIdentifierFormat:S.nameIdentifierFormat,tokenEndpoint:S.tokenEndpoint})}:{},L=typeof O?.body==`string`||Array.isArray(O?.body)?O?.body:{...O?.body,...I};if(A.type===`none`&&A.signing?.strategy){if(b===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=A.signing,n=e.credentials??{};try{let e=(0,c.getSigningStrategy)(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:h,url:`${f}${p}`,headers:M,query:O?.query??{},body:L},n,t);Object.assign(M,r)}catch(t){return buildStepErrorOutput(t,e)}}let R;try{R=await n.performRequest({httpClient:e.httpClient,url:`${f}${p}`,queryParams:O?.query,encodeQueryParams:b,method:h,headers:M,body:L,customErrorConfigs:y,requestConfig:F,httpsAgent:D,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:C})}catch(t){return k&&(isErrorWithResponseBody(t)&&(t.response.body=m.REDACT_CENSOR),isErrorWithResponseConfigData(t)&&(t.response.config.data=m.REDACT_CENSOR)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Ae(g?.dataKey?resolveDataKey(R.data,g.dataKey):R.data,g),raw:k&&R&&`body`in R?{...R,body:m.REDACT_CENSOR}:R,statusCode:R?.status,message:R?.message}}},resolveDataKey=(e,t)=>{if((0,o.isMissing)(e)||typeof e!=`object`||!e)return e;let n=(0,s.safeEvaluate)(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Ae=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),je=o.z.union([o.z.string(),o.z.number()]),Me=(0,o.zStrictObject)({algorithm:o.z.literal(`RS256`),privateKey:o.z.string(),claims:o.z.record(o.z.string(),je)}),Ne=(0,o.zStrictObject)({token:o.z.string(),expiresIn:o.z.number(),publicKeyFingerprint:o.z.string()}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${(0,h.createHash)(`sha256`).update(t).digest(`base64`)}`},Pe=/^now$/,Fe=/^now\+(?<amount>\d+)(?<unit>[smh])$/,Ie=`{publicKeyFingerprint}`,Le={s:1,m:60,h:3600},Re=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(Ie)?t.split(Ie).join(r):t;if(!Re.has(e))return i;if(Pe.test(i))return n;let a=i.match(Fe);return a?.groups?n+Number(a.groups.amount)*Le[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?(0,s.safeEvaluateRecord)(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Me.parse(n),o=(0,h.createPrivateKey)(i),c=computePublicKeyFingerprint((0,h.createPublicKey)(o)),l=Math.floor(Date.now()/1e3),u={};for(let[e,t]of Object.entries(a))u[e]=resolveClaimValue(e,t,{now:l,publicKeyFingerprint:c});let{iat:d,exp:f}=u;if(typeof d!=`number`||typeof f!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(f<=d)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let p=await new g.SignJWT(u).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:p,expiresIn:f-d,publicKeyFingerprint:c}}}catch(t){return buildStepErrorOutput(t,e)}},ze=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:o.z.discriminatedUnion(`type`,[(0,o.zStrictObject)({type:o.z.literal(`none`)}),(0,o.zStrictObject)({type:o.z.literal(`basic`),username:o.z.string().optional(),password:o.z.string().optional(),encoding:o.z.string().optional()}),(0,o.zStrictObject)({type:o.z.literal(`bearer`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0)}),(0,o.zStrictObject)({type:o.z.literal(`oauth2`),token:o.z.string(),includeBearer:o.z.boolean().optional().default(!0)})]).optional(),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional(),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string(),namespace:o.z.string()}).array().optional(),soapOperation:o.z.string().optional(),soapAction:o.z.string().optional(),useSoapContext:o.z.boolean().optional().default(!0),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional(),nextKey:o.z.string().optional(),nextKeyIn:o.z.enum([`data`,`headers`]).optional()}).optional(),iterator:(0,o.zStrictObject)({key:o.z.string(),in:o.z.enum([`query`,`body`])}),cursor:(0,o.zStrictObject)({token:o.z.string().optional().nullable(),position:o.z.number().optional().nullable()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Be=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional(),next:o.z.string().optional().nullable(),position:o.z.number().optional()}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,l=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,u=t?(0,s.safeEvaluateRecord)({...t,args:l},e):{},d={...u,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,u?.response)},f=t?.envelope,{baseUrl:p,url:m,method:h,response:g,iterator:_,cursor:v,authorization:y,customErrors:b,encodeQueryParams:x,args:S,soapOperation:C,namespaces:w,soapAction:T,useSoapContext:E}=ze.parse(d),D=u?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,O=S?(0,c.parseRequestParameters)(S):{query:{},body:{},headers:{}},k=(0,c.createAuthorizationHeaders)((0,o.notMissing)(y)?y:Z.parse(D)),A={...O?.headers??{},...k},j=e.connector?.rateLimit,M=e.connector?.concurrency,N={...j!==void 0||M!==void 0?{rateLimits:j,concurrency:M}:void 0,soapOperation:C,namespaces:w,soapAction:T,soapContext:E?{username:e.credentials?.username,password:e.credentials?.password}:void 0},P=v?.token??null,F=null,I=null,L=[],R=[],z=[],B=a,V=v?.position??0,H=!0,U;do{H?H=!1:V=0,P!==null&&(_.in===`query`?O.query[_.key]=P.toString():_.in===`body`&&(O.body[_.key]=P));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${p}${m}`,queryParams:{...O?.query},encodeQueryParams:x,method:h,headers:A,body:O?.body,customErrorConfigs:b,requestConfig:{...N,...(0,o.notMissing)(f)&&{envelope:evaluateEnvelope(f,e,P)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}F=P,R=g?.dataKey?Ce(t.data,g.dataKey):t.data,Array.isArray(R)||(R=R?[R]:[]);let r=R?.slice(V,V+B);B-=r.length,V+=r.length,z.push(t),L=L.concat(r),I=t?.status,P=resolveNextIterator({result:t,response:g});let i=V>=(R?.length??0),s=(0,o.notMissing)(g?.nextKey),c=r.length===R.length&&B===0;s&&i&&(V=0,F=P),U=s?i&&(0,o.isMissing)(P):(0,o.isMissing)(P)&&L.length<a||c}while((0,o.notMissing)(P)&&L.length<a&&R?.length>0);return{block:e,successful:!0,output:{data:Ve(L,g),raw:z,statusCode:I,next:U?void 0:stringifyCursorToken(F),position:U?void 0:V}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?(0,s.safeEvaluate)(e,r):(0,s.safeEvaluateRecord)(e,r)},resolveNextIterator=({result:e,response:t})=>{if((0,o.isMissing)(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},Ve=__name((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),He=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods),authorization:Z.optional(),envelope:o.z.union([o.z.string(),o.z.record(o.z.string(),o.z.unknown())]).optional(),namespaces:o.z.strictObject({namespaceIdentifier:o.z.string(),namespace:o.z.string()}).array().optional(),soapOperation:o.z.string().optional(),soapAction:o.z.string().optional(),useSoapContext:o.z.boolean().optional().default(!0),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),encodeQueryParams:o.z.boolean().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional()}),Ue=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=c.RequestClientFactory.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,s.safeEvaluateRecord)({...t,args:i},e):{},l={...a,customErrors:t?.customErrors},{baseUrl:u,url:d,method:f,response:p,authorization:m,customErrors:h,encodeQueryParams:g,args:_,soapOperation:v,namespaces:y,envelope:b,soapAction:x,useSoapContext:S}=He.parse(l),C=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,w=_?(0,c.parseRequestParameters)(_):{query:{},body:{},headers:{}},T=(0,c.createAuthorizationHeaders)((0,o.notMissing)(m)?m:Z.parse(C)),E={...w?.headers??{},...T},D=e.connector?.rateLimit,O=e.connector?.concurrency,k={...D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,soapOperation:v,namespaces:y,envelope:b,soapAction:x,soapContext:S?{username:e.credentials?.username,password:e.credentials?.password}:void 0},A;try{A=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:w?.query,encodeQueryParams:g,method:f,headers:E,body:w?.body,customErrorConfigs:h,requestConfig:k,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:We(p?.dataKey?A.data[p?.dataKey]:A.data,p),raw:A,statusCode:A?.status,message:A?.message}}},We=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ge=o.z.object({values:o.z.string().or(o.z.record(o.z.string(),o.z.unknown())).or(o.z.array(o.z.unknown()))}),Ke=o.z.object({data:o.z.unknown()}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Ge.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>(0,o.isString)(e)?(0,s.safeEvaluate)(e,t):(0,o.isObject)(e)?(0,s.safeEvaluateRecord)(e,t):e,qe=o.z.object({targetFieldKey:o.z.string(),type:o.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.z.boolean().default(!1),custom:o.z.boolean().default(!1),hidden:o.z.boolean().default(!1),properties:o.z.lazy(()=>qe).array().optional(),requiredScopes:o.z.string().array().optional()}),Je=o.z.object({fields:qe.array().optional(),dataSource:o.z.string()}),Ye=o.z.object({data:o.z.unknown()});let Xe=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if((0,o.isMissing)(e))return null;switch(t){case`string`:return(0,o.safeParseToString)({value:e});case`number`:return(0,o.safeParseToNumber)({value:e});case`boolean`:return(0,o.safeParseToBoolean)({value:e});case`datetime_string`:return(0,o.safeParseToDateTimeString)({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values(Xe).includes(e),Ze=__name(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>Qe(e,t)):Qe(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),Qe=__name((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Je.parse(t),i=(0,s.evaluate)(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&(0,o.notMissing)(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&(0,o.notMissing)(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&(0,o.notMissing)(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},$e=(0,o.zStrictObject)({content:o.z.string().meta({description:`The file content as base64 encoded string`}),contentType:o.z.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),et=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).default(`post`),authorization:Z.optional(),binaryContent:$e.meta({description:`Raw binary content for octet-stream uploads`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),tt=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?(0,s.safeEvaluateRecord)({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:l,url:u,method:d,response:f,authorization:p,binaryContent:m,args:h,customErrors:g}=et.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?(0,c.parseRequestParameters)(h):{query:{},body:{},headers:{}},y=(0,c.createAuthorizationHeaders)((0,o.notMissing)(p)?p:Z.parse(_)),b=Buffer.from(m.content,`base64`),x={"content-type":m.contentType??`application/octet-stream`,...v?.headers??{},...y},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T;try{T=await e.httpClient.request({url:`${l??``}${u}`,method:d,headers:x,queryParams:v?.query,payload:b,requestConfig:w,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let E=(0,c.translateCustomError)(T,g,e.credentials);return(0,c.isFailedStatusCode)(E?.status)?{block:e,successful:!1,errors:[(0,c.serializeHttpResponseError)(new c.HttpResponseError(E,E.message))],output:{statusCode:E.status,message:E.message}}:{block:e,successful:!0,output:{data:nt(f?.dataKey?E.data[f?.dataKey]:E.data,f),raw:E,statusCode:E?.status,message:E?.message}}},nt=__name((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),rt=(0,o.zStrictObject)({fieldName:o.z.string().meta({description:`The form field name for the file`}),content:o.z.string().meta({description:`The file content as base64 encoded string`}),filename:o.z.string().meta({description:`The filename to use in the upload`}),contentType:o.z.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),it=o.z.object({baseUrl:o.z.string().optional(),url:o.z.string(),method:o.z.enum(c.HttpMethods).default(`post`),authorization:Z.optional(),file:rt.meta({description:`The file to upload`}),additionalFields:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),condition:o.z.string().optional(),contentType:o.z.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:(0,o.zStrictObject)({collection:o.z.boolean().optional(),indexField:o.z.string().optional(),dataKey:o.z.string().optional()}).optional(),customErrors:c.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:(0,o.zStrictObject)({name:o.z.string(),value:o.z.unknown(),in:o.z.enum(c.RequestParameterLocations),spread:o.z.boolean().optional(),condition:o.z.string().optional(),arrayFormat:o.z.enum(c.QueryArrayFormats).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),at=(0,o.zStrictObject)({data:o.z.unknown().optional(),raw:o.z.unknown().optional(),statusCode:o.z.number(),message:o.z.string().optional()}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||(0,s.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,l=t?(0,s.safeEvaluateRecord)({...t,args:i,additionalFields:a},e):{},u={...l,customErrors:t?.customErrors},{baseUrl:d,url:f,method:p,response:m,authorization:h,file:g,additionalFields:v,args:y,customErrors:b}=it.parse(u),x=l?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,S=y?(0,c.parseRequestParameters)(y):{query:{},body:{},headers:{}},C=(0,c.createAuthorizationHeaders)((0,o.notMissing)(h)?h:Z.parse(x)),w=new _.default;if(v)for(let e of v){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);w.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let T=Buffer.from(g.content,`base64`);w.append(g.fieldName,T,{filename:g.filename,contentType:g.contentType});let E={...w.getHeaders(),...S?.headers??{},...C},D=e.connector?.rateLimit,O=e.connector?.concurrency,k=D!==void 0||O!==void 0?{rateLimits:D,concurrency:O}:void 0,A;try{A=await e.httpClient.request({url:`${d??``}${f}`,method:p,headers:E,queryParams:S?.query,payload:w,requestConfig:k,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let j=(0,c.translateCustomError)(A,b,e.credentials);return(0,c.isFailedStatusCode)(j?.status)?buildStepErrorOutput(new c.HttpResponseError(j,j.message),e):{block:e,successful:!0,output:{data:indexResponseData(m?.dataKey?j.data[m?.dataKey]:j.data,m),raw:j,statusCode:j?.status,message:j?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let ot=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const st={typecast:{v1:{fn:Ze},v2:{fn:typecastStepFunction,inputSchema:Je,outputSchema:Ye}},map_fields:{v1:{fn:pe},v2:{fn:mapFieldsStepFunction,inputSchema:_e,outputSchema:ve}},request:{v1:{fn:requestStepFunction,inputSchema:Oe,outputSchema:ke}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:de,outputSchema:fe}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:we,outputSchema:Te}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:He,outputSchema:Ue}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:ze,outputSchema:Be}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Ge,outputSchema:Ke}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:it,outputSchema:at}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:et,outputSchema:tt}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:ae,outputSchema:oe}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:se,outputSchema:ce}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:U,outputSchema:W}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:G,outputSchema:K}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Me,outputSchema:Ne}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:xe,outputSchema:Se}}},formatZodIssues=(e,t,n)=>e instanceof o.z.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},ct={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=st}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;exports.AUTHORIZATION_SCHEMA=Z,exports.ActionTypes=A,exports.AuthType=H,exports.BARE_JEXL_REQUIREMENT=T,exports.BROWSER_USE_INPUT_PARAMS=U,exports.BROWSER_USE_OUTPUT=W,exports.CODE_EXECUTION_LAMBDA_INPUT_PARAMS=G,exports.CODE_EXECUTION_LAMBDA_OUTPUT=K,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.ChangelogLabels=k,exports.CoreError=C,exports.DOWNLOAD_FILE_INPUT_PARAMS=ae,exports.DOWNLOAD_FILE_OUTPUT=oe,exports.EMIT_EVENT_INPUT_PARAMS=se,exports.EMIT_EVENT_OUTPUT=ce,exports.Effects=j,exports.ExecutionModes=I,exports.FORMAT_PATTERNS=E,exports.GROUP_DATA_INPUT_PARAMS=de,exports.GROUP_DATA_OUTPUT=fe,exports.INPUT_ENUM_REGISTRY=D,exports.InputFormats=P,exports.InputLocations=N,exports.InputTypes=F,exports.MAP_FIELDS_INPUT_PARAMS=_e,exports.MAP_FIELDS_OUTPUT=ve,exports.MCP_REQUEST_INPUT_PARAMS=xe,exports.MCP_REQUEST_OUTPUT=Se,exports.PAGINATED_REQUEST_INPUT_PARAMS=we,exports.PAGINATED_REQUEST_OUTPUT=Te,exports.REQUEST_INPUT_PARAMS=Oe,exports.REQUEST_OUTPUT=ke,exports.ReleaseStages=O,exports.SIGN_JWT_INPUT_PARAMS=Me,exports.SIGN_JWT_OUTPUT=Ne,exports.SOAP_PAGINATED_REQUEST_INPUT_PARAMS=ze,exports.SOAP_PAGINATED_REQUEST_OUTPUT=Be,exports.SOAP_REQUEST_INPUT_PARAMS=He,exports.SOAP_REQUEST_OUTPUT=Ue,exports.STATIC_VALUES_INPUT_PARAMS=Ge,exports.STATIC_VALUES_OUTPUT=Ke,exports.SchemaTypes=M,exports.SourceType=z,exports.StepFunctionName=ot,exports.StepFunctionsFactory=ct,exports.StepFunctionsRegistry=st,exports.StreamType=V,exports.TYPECAST_INPUT_PARAMS=Je,exports.TYPECAST_OUTPUT=Ye,exports.TransportType=B,exports.UPLOAD_BINARY_INPUT_PARAMS=et,exports.UPLOAD_BINARY_OUTPUT=tt,exports.UPLOAD_FILE_INPUT_PARAMS=it,exports.UPLOAD_FILE_OUTPUT=at,exports.areCursorsEqual=areCursorsEqual,exports.buildExpressionContext=buildExpressionContext,exports.computeDataSyncFingerprint=computeDataSyncFingerprint,exports.decodeCompositeId=decodeCompositeId,exports.encodeCompositeId=encodeCompositeId,exports.evaluateEventRouter=evaluateEventRouter,exports.evaluateExternalAccountIdExtractor=evaluateExternalAccountIdExtractor,exports.expandCursor=expandCursor,exports.getCategoryDetails=getCategoryDetails,exports.getInputEnumValues=getInputEnumValues,exports.getIteratorLocation=getIteratorLocation,exports.getPaginationKeys=getPaginationKeys,exports.isBareJexl=isBareJexl,exports.isCompositeId=isCompositeId,exports.isCoreError=isCoreError,exports.isCursorEmpty=isCursorEmpty,exports.isForeachStep=isForeachStep,exports.isValidCategory=isValidCategory,exports.isValidEnumRef=isValidEnumRef,exports.minifyCursor=minifyCursor,exports.stripIncrementalParams=stripIncrementalParams,exports.stripPaginationParams=stripPaginationParams,exports.updateCursor=updateCursor;
package/dist/index.d.cts CHANGED
@@ -3067,10 +3067,12 @@ type EventRouterRule = {
3067
3067
  when: string;
3068
3068
  then: {
3069
3069
  action: string;
3070
- input?: Record<string, unknown>;
3070
+ input?: Record<string, string>;
3071
3071
  };
3072
3072
  };
3073
3073
  type EventRouter = {
3074
+ delivery?: EventRouterRule[];
3075
+ itemsPath?: string;
3074
3076
  rules: EventRouterRule[];
3075
3077
  };
3076
3078
  type EventToEmit = {
@@ -3449,6 +3451,7 @@ type OlapSettings = {
3449
3451
  errorsOnly?: boolean;
3450
3452
  includeBackground?: boolean;
3451
3453
  truncation?: TruncationMode;
3454
+ piiRedactionEnabled?: boolean;
3452
3455
  };
3453
3456
  };
3454
3457
  type DefenderSettings = {
@@ -3696,6 +3699,10 @@ declare const isCompositeId: (value?: string | null) => boolean;
3696
3699
  //#region src/compositeIds/constants.d.ts
3697
3700
  declare const COMPOSITE_ID_LATEST_VERSION = 1;
3698
3701
  //#endregion
3702
+ //#region src/connector/bareJexl.d.ts
3703
+ declare const BARE_JEXL_REQUIREMENT = "must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation";
3704
+ declare const isBareJexl: (expression: string) => boolean;
3705
+ //#endregion
3699
3706
  //#region src/connector/dataSyncFingerprint.d.ts
3700
3707
  declare const computeDataSyncFingerprint: (config: DataSyncConfig) => string;
3701
3708
  //#endregion
@@ -3720,8 +3727,14 @@ type EvaluationContext = {
3720
3727
  type MatchedEventAction = {
3721
3728
  action: string;
3722
3729
  input?: Record<string, unknown>;
3730
+ event: unknown;
3731
+ eventIndex: number;
3732
+ };
3733
+ type EventRouterResult = {
3734
+ matches: MatchedEventAction[];
3735
+ totalEvents: number;
3723
3736
  };
3724
- declare const evaluateEventRouter: (connector: Connector, context: EvaluationContext) => MatchedEventAction | undefined;
3737
+ declare const evaluateEventRouter: (connector: Connector, context: EvaluationContext) => EventRouterResult;
3725
3738
  //#endregion
3726
3739
  //#region src/connector/formatPatterns.d.ts
3727
3740
  declare const FORMAT_PATTERNS: Record<InputFormat, RegExp>;
@@ -4974,4 +4987,4 @@ type Account = {
4974
4987
  originOwnerName?: string;
4975
4988
  };
4976
4989
  //#endregion
4977
- export { AUTHORIZATION_SCHEMA, type Account, type Action, type ActionAnnotations, type ActionCategory, type ActionExample, type ActionResponse, type ActionType, ActionTypes, type ActionValidationRule, type Assets, AuthType, type Authentication, type AuthenticationConfig, type AuthenticationField, type AuthenticationFieldValidation, type AuthenticationGuides, type AuthenticationNotice, BROWSER_USE_INPUT_PARAMS, BROWSER_USE_OUTPUT, type BaseIncrementalConfig, type BasePaginationConfig, type Block, type BlockContext, type BlockIndexedRecord, CODE_EXECUTION_LAMBDA_INPUT_PARAMS, CODE_EXECUTION_LAMBDA_OUTPUT, COMPOSITE_ID_LATEST_VERSION, type Category, type Changelog, type ChangelogLabel, ChangelogLabels, type Checkpoint, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, type ConnectorDocumentation, type ConnectorEvents, CoreError, type Cursor, type CursorPaginationConfig, DOWNLOAD_FILE_INPUT_PARAMS, DOWNLOAD_FILE_OUTPUT, type DataSyncConfig, type DefenderMetadata, type DefenderSettings, type DeltaTokenIncrementalConfig, type DocumentationReference, EMIT_EVENT_INPUT_PARAMS, EMIT_EVENT_OUTPUT, type Effect, Effects, type EnumOneOf, type EventRouter, type EventRouterRule, type EventToEmit, type ExecutionMode, ExecutionModes, type ExpressionContextOptions, FORMAT_PATTERNS, type FieldConfig, type FlowType, type ForeachStep, GROUP_DATA_INPUT_PARAMS, GROUP_DATA_OUTPUT, type Guide, type GuideImage, type GuideSection, type GuideStep, INPUT_ENUM_REGISTRY, type IncrementalConfig, type Input, type InputFormat, InputFormats, type InputLocation, InputLocations, type InputRules, type InputType, InputTypes, type InputVariant, type IntermediateStepSnapshot, type IteratorLocation, MAP_FIELDS_INPUT_PARAMS, MAP_FIELDS_OUTPUT, MCP_REQUEST_INPUT_PARAMS, MCP_REQUEST_OUTPUT, type MatchedEventAction, type OffsetPaginationConfig, type OnConditionError, PAGINATED_REQUEST_INPUT_PARAMS, PAGINATED_REQUEST_OUTPUT, type PagePaginationConfig, type PaginationConfig, REQUEST_INPUT_PARAMS, REQUEST_OUTPUT, type ReleaseStage, ReleaseStages, SIGN_JWT_INPUT_PARAMS, SIGN_JWT_OUTPUT, SOAP_PAGINATED_REQUEST_INPUT_PARAMS, SOAP_PAGINATED_REQUEST_OUTPUT, SOAP_REQUEST_INPUT_PARAMS, SOAP_REQUEST_OUTPUT, STATIC_VALUES_INPUT_PARAMS, STATIC_VALUES_OUTPUT, type Schema, type SchemaField, type SchemaType, SchemaTypes, type ScopeDefinition, type Settings, type SimpleStep, type Source, SourceType, type Step, type StepFunction, type StepFunctionMeta, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type StreamOutputData, StreamType, type SupportConfig, type SyncParams, type SyncedAction, TYPECAST_INPUT_PARAMS, TYPECAST_OUTPUT, type TestActionConfig, type TimeFilterIncrementalConfig, TransportType, UPLOAD_BINARY_INPUT_PARAMS, UPLOAD_BINARY_OUTPUT, UPLOAD_FILE_INPUT_PARAMS, UPLOAD_FILE_OUTPUT, type WebhookSetup, type WebhookSetupPhase, type WebhookSetupPhaseKind, areCursorsEqual, buildExpressionContext, computeDataSyncFingerprint, decodeCompositeId, encodeCompositeId, evaluateEventRouter, evaluateExternalAccountIdExtractor, expandCursor, getCategoryDetails, getInputEnumValues, getIteratorLocation, getPaginationKeys, isCompositeId, isCoreError, isCursorEmpty, isForeachStep, isValidCategory, isValidEnumRef, minifyCursor, stripIncrementalParams, stripPaginationParams, updateCursor };
4990
+ export { AUTHORIZATION_SCHEMA, type Account, type Action, type ActionAnnotations, type ActionCategory, type ActionExample, type ActionResponse, type ActionType, ActionTypes, type ActionValidationRule, type Assets, AuthType, type Authentication, type AuthenticationConfig, type AuthenticationField, type AuthenticationFieldValidation, type AuthenticationGuides, type AuthenticationNotice, BARE_JEXL_REQUIREMENT, BROWSER_USE_INPUT_PARAMS, BROWSER_USE_OUTPUT, type BaseIncrementalConfig, type BasePaginationConfig, type Block, type BlockContext, type BlockIndexedRecord, CODE_EXECUTION_LAMBDA_INPUT_PARAMS, CODE_EXECUTION_LAMBDA_OUTPUT, COMPOSITE_ID_LATEST_VERSION, type Category, type Changelog, type ChangelogLabel, ChangelogLabels, type Checkpoint, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, type ConnectorDocumentation, type ConnectorEvents, CoreError, type Cursor, type CursorPaginationConfig, DOWNLOAD_FILE_INPUT_PARAMS, DOWNLOAD_FILE_OUTPUT, type DataSyncConfig, type DefenderMetadata, type DefenderSettings, type DeltaTokenIncrementalConfig, type DocumentationReference, EMIT_EVENT_INPUT_PARAMS, EMIT_EVENT_OUTPUT, type Effect, Effects, type EnumOneOf, type EventRouter, type EventRouterResult, type EventRouterRule, type EventToEmit, type ExecutionMode, ExecutionModes, type ExpressionContextOptions, FORMAT_PATTERNS, type FieldConfig, type FlowType, type ForeachStep, GROUP_DATA_INPUT_PARAMS, GROUP_DATA_OUTPUT, type Guide, type GuideImage, type GuideSection, type GuideStep, INPUT_ENUM_REGISTRY, type IncrementalConfig, type Input, type InputFormat, InputFormats, type InputLocation, InputLocations, type InputRules, type InputType, InputTypes, type InputVariant, type IntermediateStepSnapshot, type IteratorLocation, MAP_FIELDS_INPUT_PARAMS, MAP_FIELDS_OUTPUT, MCP_REQUEST_INPUT_PARAMS, MCP_REQUEST_OUTPUT, type MatchedEventAction, type OffsetPaginationConfig, type OnConditionError, PAGINATED_REQUEST_INPUT_PARAMS, PAGINATED_REQUEST_OUTPUT, type PagePaginationConfig, type PaginationConfig, REQUEST_INPUT_PARAMS, REQUEST_OUTPUT, type ReleaseStage, ReleaseStages, SIGN_JWT_INPUT_PARAMS, SIGN_JWT_OUTPUT, SOAP_PAGINATED_REQUEST_INPUT_PARAMS, SOAP_PAGINATED_REQUEST_OUTPUT, SOAP_REQUEST_INPUT_PARAMS, SOAP_REQUEST_OUTPUT, STATIC_VALUES_INPUT_PARAMS, STATIC_VALUES_OUTPUT, type Schema, type SchemaField, type SchemaType, SchemaTypes, type ScopeDefinition, type Settings, type SimpleStep, type Source, SourceType, type Step, type StepFunction, type StepFunctionMeta, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type StreamOutputData, StreamType, type SupportConfig, type SyncParams, type SyncedAction, TYPECAST_INPUT_PARAMS, TYPECAST_OUTPUT, type TestActionConfig, type TimeFilterIncrementalConfig, TransportType, UPLOAD_BINARY_INPUT_PARAMS, UPLOAD_BINARY_OUTPUT, UPLOAD_FILE_INPUT_PARAMS, UPLOAD_FILE_OUTPUT, type WebhookSetup, type WebhookSetupPhase, type WebhookSetupPhaseKind, areCursorsEqual, buildExpressionContext, computeDataSyncFingerprint, decodeCompositeId, encodeCompositeId, evaluateEventRouter, evaluateExternalAccountIdExtractor, expandCursor, getCategoryDetails, getInputEnumValues, getIteratorLocation, getPaginationKeys, isBareJexl, isCompositeId, isCoreError, isCursorEmpty, isForeachStep, isValidCategory, isValidEnumRef, minifyCursor, stripIncrementalParams, stripPaginationParams, updateCursor };
package/dist/index.d.mts CHANGED
@@ -3066,10 +3066,12 @@ type EventRouterRule = {
3066
3066
  when: string;
3067
3067
  then: {
3068
3068
  action: string;
3069
- input?: Record<string, unknown>;
3069
+ input?: Record<string, string>;
3070
3070
  };
3071
3071
  };
3072
3072
  type EventRouter = {
3073
+ delivery?: EventRouterRule[];
3074
+ itemsPath?: string;
3073
3075
  rules: EventRouterRule[];
3074
3076
  };
3075
3077
  type EventToEmit = {
@@ -3448,6 +3450,7 @@ type OlapSettings = {
3448
3450
  errorsOnly?: boolean;
3449
3451
  includeBackground?: boolean;
3450
3452
  truncation?: TruncationMode;
3453
+ piiRedactionEnabled?: boolean;
3451
3454
  };
3452
3455
  };
3453
3456
  type DefenderSettings = {
@@ -3695,6 +3698,10 @@ declare const isCompositeId: (value?: string | null) => boolean;
3695
3698
  //#region src/compositeIds/constants.d.ts
3696
3699
  declare const COMPOSITE_ID_LATEST_VERSION = 1;
3697
3700
  //#endregion
3701
+ //#region src/connector/bareJexl.d.ts
3702
+ declare const BARE_JEXL_REQUIREMENT = "must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation";
3703
+ declare const isBareJexl: (expression: string) => boolean;
3704
+ //#endregion
3698
3705
  //#region src/connector/dataSyncFingerprint.d.ts
3699
3706
  declare const computeDataSyncFingerprint: (config: DataSyncConfig) => string;
3700
3707
  //#endregion
@@ -3719,8 +3726,14 @@ type EvaluationContext = {
3719
3726
  type MatchedEventAction = {
3720
3727
  action: string;
3721
3728
  input?: Record<string, unknown>;
3729
+ event: unknown;
3730
+ eventIndex: number;
3731
+ };
3732
+ type EventRouterResult = {
3733
+ matches: MatchedEventAction[];
3734
+ totalEvents: number;
3722
3735
  };
3723
- declare const evaluateEventRouter: (connector: Connector, context: EvaluationContext) => MatchedEventAction | undefined;
3736
+ declare const evaluateEventRouter: (connector: Connector, context: EvaluationContext) => EventRouterResult;
3724
3737
  //#endregion
3725
3738
  //#region src/connector/formatPatterns.d.ts
3726
3739
  declare const FORMAT_PATTERNS: Record<InputFormat, RegExp>;
@@ -4973,4 +4986,4 @@ type Account = {
4973
4986
  originOwnerName?: string;
4974
4987
  };
4975
4988
  //#endregion
4976
- export { AUTHORIZATION_SCHEMA, type Account, type Action, type ActionAnnotations, type ActionCategory, type ActionExample, type ActionResponse, type ActionType, ActionTypes, type ActionValidationRule, type Assets, AuthType, type Authentication, type AuthenticationConfig, type AuthenticationField, type AuthenticationFieldValidation, type AuthenticationGuides, type AuthenticationNotice, BROWSER_USE_INPUT_PARAMS, BROWSER_USE_OUTPUT, type BaseIncrementalConfig, type BasePaginationConfig, type Block, type BlockContext, type BlockIndexedRecord, CODE_EXECUTION_LAMBDA_INPUT_PARAMS, CODE_EXECUTION_LAMBDA_OUTPUT, COMPOSITE_ID_LATEST_VERSION, type Category, type Changelog, type ChangelogLabel, ChangelogLabels, type Checkpoint, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, type ConnectorDocumentation, type ConnectorEvents, CoreError, type Cursor, type CursorPaginationConfig, DOWNLOAD_FILE_INPUT_PARAMS, DOWNLOAD_FILE_OUTPUT, type DataSyncConfig, type DefenderMetadata, type DefenderSettings, type DeltaTokenIncrementalConfig, type DocumentationReference, EMIT_EVENT_INPUT_PARAMS, EMIT_EVENT_OUTPUT, type Effect, Effects, type EnumOneOf, type EventRouter, type EventRouterRule, type EventToEmit, type ExecutionMode, ExecutionModes, type ExpressionContextOptions, FORMAT_PATTERNS, type FieldConfig, type FlowType, type ForeachStep, GROUP_DATA_INPUT_PARAMS, GROUP_DATA_OUTPUT, type Guide, type GuideImage, type GuideSection, type GuideStep, INPUT_ENUM_REGISTRY, type IncrementalConfig, type Input, type InputFormat, InputFormats, type InputLocation, InputLocations, type InputRules, type InputType, InputTypes, type InputVariant, type IntermediateStepSnapshot, type IteratorLocation, MAP_FIELDS_INPUT_PARAMS, MAP_FIELDS_OUTPUT, MCP_REQUEST_INPUT_PARAMS, MCP_REQUEST_OUTPUT, type MatchedEventAction, type OffsetPaginationConfig, type OnConditionError, PAGINATED_REQUEST_INPUT_PARAMS, PAGINATED_REQUEST_OUTPUT, type PagePaginationConfig, type PaginationConfig, REQUEST_INPUT_PARAMS, REQUEST_OUTPUT, type ReleaseStage, ReleaseStages, SIGN_JWT_INPUT_PARAMS, SIGN_JWT_OUTPUT, SOAP_PAGINATED_REQUEST_INPUT_PARAMS, SOAP_PAGINATED_REQUEST_OUTPUT, SOAP_REQUEST_INPUT_PARAMS, SOAP_REQUEST_OUTPUT, STATIC_VALUES_INPUT_PARAMS, STATIC_VALUES_OUTPUT, type Schema, type SchemaField, type SchemaType, SchemaTypes, type ScopeDefinition, type Settings, type SimpleStep, type Source, SourceType, type Step, type StepFunction, type StepFunctionMeta, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type StreamOutputData, StreamType, type SupportConfig, type SyncParams, type SyncedAction, TYPECAST_INPUT_PARAMS, TYPECAST_OUTPUT, type TestActionConfig, type TimeFilterIncrementalConfig, TransportType, UPLOAD_BINARY_INPUT_PARAMS, UPLOAD_BINARY_OUTPUT, UPLOAD_FILE_INPUT_PARAMS, UPLOAD_FILE_OUTPUT, type WebhookSetup, type WebhookSetupPhase, type WebhookSetupPhaseKind, areCursorsEqual, buildExpressionContext, computeDataSyncFingerprint, decodeCompositeId, encodeCompositeId, evaluateEventRouter, evaluateExternalAccountIdExtractor, expandCursor, getCategoryDetails, getInputEnumValues, getIteratorLocation, getPaginationKeys, isCompositeId, isCoreError, isCursorEmpty, isForeachStep, isValidCategory, isValidEnumRef, minifyCursor, stripIncrementalParams, stripPaginationParams, updateCursor };
4989
+ export { AUTHORIZATION_SCHEMA, type Account, type Action, type ActionAnnotations, type ActionCategory, type ActionExample, type ActionResponse, type ActionType, ActionTypes, type ActionValidationRule, type Assets, AuthType, type Authentication, type AuthenticationConfig, type AuthenticationField, type AuthenticationFieldValidation, type AuthenticationGuides, type AuthenticationNotice, BARE_JEXL_REQUIREMENT, BROWSER_USE_INPUT_PARAMS, BROWSER_USE_OUTPUT, type BaseIncrementalConfig, type BasePaginationConfig, type Block, type BlockContext, type BlockIndexedRecord, CODE_EXECUTION_LAMBDA_INPUT_PARAMS, CODE_EXECUTION_LAMBDA_OUTPUT, COMPOSITE_ID_LATEST_VERSION, type Category, type Changelog, type ChangelogLabel, ChangelogLabels, type Checkpoint, type CompositeIdentifier, type CompositeIdentifierConfig, type CompositeIdentifierConnectorConfig, type Connector, type ConnectorDocumentation, type ConnectorEvents, CoreError, type Cursor, type CursorPaginationConfig, DOWNLOAD_FILE_INPUT_PARAMS, DOWNLOAD_FILE_OUTPUT, type DataSyncConfig, type DefenderMetadata, type DefenderSettings, type DeltaTokenIncrementalConfig, type DocumentationReference, EMIT_EVENT_INPUT_PARAMS, EMIT_EVENT_OUTPUT, type Effect, Effects, type EnumOneOf, type EventRouter, type EventRouterResult, type EventRouterRule, type EventToEmit, type ExecutionMode, ExecutionModes, type ExpressionContextOptions, FORMAT_PATTERNS, type FieldConfig, type FlowType, type ForeachStep, GROUP_DATA_INPUT_PARAMS, GROUP_DATA_OUTPUT, type Guide, type GuideImage, type GuideSection, type GuideStep, INPUT_ENUM_REGISTRY, type IncrementalConfig, type Input, type InputFormat, InputFormats, type InputLocation, InputLocations, type InputRules, type InputType, InputTypes, type InputVariant, type IntermediateStepSnapshot, type IteratorLocation, MAP_FIELDS_INPUT_PARAMS, MAP_FIELDS_OUTPUT, MCP_REQUEST_INPUT_PARAMS, MCP_REQUEST_OUTPUT, type MatchedEventAction, type OffsetPaginationConfig, type OnConditionError, PAGINATED_REQUEST_INPUT_PARAMS, PAGINATED_REQUEST_OUTPUT, type PagePaginationConfig, type PaginationConfig, REQUEST_INPUT_PARAMS, REQUEST_OUTPUT, type ReleaseStage, ReleaseStages, SIGN_JWT_INPUT_PARAMS, SIGN_JWT_OUTPUT, SOAP_PAGINATED_REQUEST_INPUT_PARAMS, SOAP_PAGINATED_REQUEST_OUTPUT, SOAP_REQUEST_INPUT_PARAMS, SOAP_REQUEST_OUTPUT, STATIC_VALUES_INPUT_PARAMS, STATIC_VALUES_OUTPUT, type Schema, type SchemaField, type SchemaType, SchemaTypes, type ScopeDefinition, type Settings, type SimpleStep, type Source, SourceType, type Step, type StepFunction, type StepFunctionMeta, StepFunctionName, type StepFunctionOutput, type StepFunctionParams, StepFunctionsFactory, stepFunctions as StepFunctionsRegistry, type StepsSnapshots, type StreamOutputData, StreamType, type SupportConfig, type SyncParams, type SyncedAction, TYPECAST_INPUT_PARAMS, TYPECAST_OUTPUT, type TestActionConfig, type TimeFilterIncrementalConfig, TransportType, UPLOAD_BINARY_INPUT_PARAMS, UPLOAD_BINARY_OUTPUT, UPLOAD_FILE_INPUT_PARAMS, UPLOAD_FILE_OUTPUT, type WebhookSetup, type WebhookSetupPhase, type WebhookSetupPhaseKind, areCursorsEqual, buildExpressionContext, computeDataSyncFingerprint, decodeCompositeId, encodeCompositeId, evaluateEventRouter, evaluateExternalAccountIdExtractor, expandCursor, getCategoryDetails, getInputEnumValues, getIteratorLocation, getPaginationKeys, isBareJexl, isCompositeId, isCoreError, isCursorEmpty, isForeachStep, isValidCategory, isValidEnumRef, minifyCursor, stripIncrementalParams, stripPaginationParams, updateCursor };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import{t as e}from"./chunk-BhWHdk3m.mjs";import{decodeFromBase64 as t,encodeToBase64 as n,getContentHash as r,getCountryAlpha2CodeByAlpha2Code as i,getCountryAlpha2CodeByAlpha3Code as a,getCountryAlpha2CodeByCitizenship as o,getCountryAlpha2CodeByCountryCode as s,getCountryAlpha2CodeByCountryName as c,getCountryAlpha3CodeByAlpha2Code as l,getCountryAlpha3CodeByAlpha3Code as u,getCountryAlpha3CodeByCountryCode as d,getCountryAlpha3CodeByCountryName as f,getCountryCodeByAlpha2Code as p,getCountryCodeByAlpha3Code as m,getCountryCodeByCountryCode as h,getCountryCodeByCountryName as g,getCountryNameByAlpha2Code as _,getCountryNameByAlpha3Code as v,getCountryNameByCountryCode as y,getCountryNameByCountryName as b,getCountrySubDivisionCodeBySubDivisionName as x,getCountrySubDivisionNameBySubDivisionCode as S,getCountrySubDivisionsByAlpha2Code as C,getDocumentFileFormatFromExtension as w,isMissing as T,isObject as E,isString as D,notMissing as O,safeParseToBoolean as ee,safeParseToDateTimeString as k,safeParseToNumber as A,safeParseToString as te,z as j,zStrictObject as M}from"@stackone/utils";import{evaluate as N,isExpression as P,isValidExpression as F,safeEvaluate as I,safeEvaluateRecord as L}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as R,HttpMethods as z,HttpResponseError as B,McpClient as V,QueryArrayFormats as H,RequestClientFactory as ne,RequestParameterLocations as U,buildHttpsAgent as re,createAuthorizationHeaders as W,getSigningStrategy as G,isFailedStatusCode as K,parseRequestParameters as q,serializeHttpResponseError as J,translateCustomError as Y}from"@stackone/transport";import{InvokeCommand as X,LambdaClient as ie}from"@aws-sdk/client-lambda";import{Readable as ae}from"node:stream";import Z from"mime-types";import{Saml20 as oe}from"saml";import{v4 as se}from"uuid";import{REDACT_CENSOR as Q}from"@stackone/redaction";import{createHash as ce,createPrivateKey as le,createPublicKey as ue}from"node:crypto";import{SignJWT as de}from"jose";import fe from"form-data";const pe=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=pe.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},me={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>me[e.toLowerCase()]??null,isValidCategory=e=>!!me[e.toLowerCase()],he=n(`so1!`),ge=RegExp(`(?<!\\\\):`,`g`),_e=RegExp(`(?<!\\\\),`,`g`),ve=1;var ye=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends ye{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!T(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!T(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(_e).forEach(e=>{let[n,i]=e.split(ge),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${he}${n(e)}`,decodeIdV1=e=>{if(!e.startsWith(he))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let n=e.split(he)[1];if(!n)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return t(n)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>T(e)?!1:e.startsWith(he),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return r({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if(T(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=I(`{{${n.result.trim()}}}`,t);if(!T(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if(!T(n))for(let e of n.rules){let n=I(`{{${e.when.trim()}}}`,t);if(n!==null&&n!==!1&&n!==void 0){let n=e.then.input?Object.fromEntries(Object.entries(e.then.input).map(([e,n])=>[e,I(`{{${String(n).trim()}}}`,t)])):void 0;return{action:e.then.action,input:n}}}},be={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},xe={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>xe[e],isValidEnumRef=e=>e in xe,Se=[`preview`,`beta`,`ga`,`deprecated`,`internal`],Ce=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],we=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],Te=[`read`,`write`,`delete`,`search`,`execute`],Ee=[`native`,`unified`],De=[`body`,`query`,`path`,`headers`],Oe=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],ke=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],Ae=[`sync`,`async`],je=M({r:j.record(j.string(),M({n:j.number().optional().nullable(),c:j.string().optional().nullable(),p:j.number().optional().nullable()})),v:j.number(),t:j.number()}),Me=M({remote:j.record(j.string(),M({pageNumber:j.number().optional(),providerPageCursor:j.string().optional(),position:j.number().optional()})),version:j.number(),timestamp:j.number()}),minifyCursor=e=>n(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if(D(e)){let n=t(e),r=JSON.parse(n);return expandCursorObject(je.parse(r))}else return Me.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,i=typeof t==`string`?expandCursor(t):t;if(n===null||i===null)return n===i;let{timestamp:a,...o}=n,{timestamp:s,...c}=i;return r(o)===r(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>T(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return(T(t)||r!==t.toString())&&(n=n&&T(i.pageNumber)&&T(i.position)&&T(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=T(n)&&T(r)&&T(i);return T(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof ye;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const Ne={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},Pe={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},Fe={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},Ie={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},Le=j.object({startUrl:j.string().url(),systemPrompt:j.string().optional(),viewport:M({width:j.number().int().positive(),height:j.number().int().positive()}).optional(),locale:j.string().optional(),budgets:M({maxDurationMs:j.number().int().positive(),maxSteps:j.number().int().positive()}),auth:M({sensitiveKeys:j.array(j.string().min(1)).optional(),requiresSession:j.boolean().optional(),allowedDomains:j.array(j.string().min(1)).optional()}).optional()}),Re=j.unknown(),ze=M({lambdaName:j.string(),region:j.string().optional(),endpoint:j.string().optional(),invocationType:j.enum([`RequestResponse`,`Event`,`DryRun`]).optional(),qualifier:j.string().optional(),args:M({name:j.string(),value:j.unknown(),condition:j.string().optional()}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:j.string().optional()}),Be=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),executedVersion:j.string().optional()}).optional(),Ve=M({strategy:j.literal(`aws4`),service:j.string(),region:j.string().optional()}),He=M({strategy:j.literal(`hmac`),algorithm:j.enum([`sha1`,`sha256`,`sha512`]).optional(),headerName:j.string().optional(),prefix:j.string().optional(),dateFormat:j.enum([`iso8601`,`rfc2822`]).optional(),includeHost:j.boolean().optional(),includeBodyHash:j.boolean().optional(),outputFormat:j.enum([`header`,`basic`]).optional(),username:j.string().optional()}),Ue=j.discriminatedUnion(`strategy`,[Ve,He]),We=M({type:j.literal(`none`),signing:Ue.optional(),redirectUri:j.string().optional()}),Ge=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional(),redirectUri:j.string().optional()}),Ke=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0),redirectUri:j.string().optional()}),qe=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),Je=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),redirectUri:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional(),additionalTokenFields:j.record(j.string(),j.string().optional()).optional(),callbackParams:j.record(j.string(),j.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))qe.has(r)&&t.addIssue({code:j.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional(),issuer:j.string().optional(),tokenResponse:M({acceptTokenTypes:j.array(j.string()).optional(),accessToken:j.string().min(1).optional(),refreshToken:j.string().min(1).optional()}).optional()}),$=j.discriminatedUnion(`type`,[We,Ge,Ke,Je]),Ye=M({certs:j.string().array().optional(),keys:j.string().array().optional()}).optional(),Xe=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).optional().default(`get`),authorization:$.optional(),responseMode:j.enum([`buffer`,`stream`]).optional().default(`buffer`),responseType:j.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`),encoding:j.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`),response:M({dataKey:j.string().optional(),fileNameKey:j.string().optional(),contentTypeKey:j.string().optional(),contentType:j.string().optional(),contentIsBase64:j.boolean().optional().default(!1),urlKey:j.string().optional(),forwardAuth:j.boolean().optional().default(!1)}).optional(),maxRedirects:j.number().optional().default(5),followRedirects:j.boolean().optional().default(!0),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),Ze=M({data:j.union([j.string(),j.instanceof(Buffer)]).optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),headers:j.record(j.string(),j.union([j.string(),j.array(j.string())])).optional(),contentDisposition:j.string().optional(),fileMetadata:M({contentType:j.string().optional(),contentLength:j.number().optional(),fileName:j.string().optional(),lastModified:j.string().optional(),etag:j.string().optional()}).optional(),finalUrl:j.string().optional()}).optional(),Qe=j.object({event:j.object({eventType:j.string(),eventId:j.coerce.string().optional(),eventDate:j.coerce.string().optional(),data:j.unknown().optional()}).optional()}),$e=j.record(j.string(),j.unknown()),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof B){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[J(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[J(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[J(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[J(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new ie(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),l=new X({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),u=await c.send(l),d=u.Payload?Buffer.from(u.Payload).toString(`utf-8`):``,f;if(d.length===0)f=void 0;else try{f=JSON.parse(d)}catch{f=d}return{statusCode:u.StatusCode??200,payload:f,functionError:u.FunctionError,executedVersion:u.ExecutedVersion}},et=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>P(e)||et.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>P(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,tt=e((e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;try{let n=N(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||I(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,s=typeof o==`string`&&!et.test(o),c=t?.qualifier,l=typeof c==`string`&&!hasExpressionMarker(c),u={...t?L(i===void 0?t:{...t,args:a},e):{},...s?{dataKey:o}:{},...l?{qualifier:c}:{}},d;try{d=ze.parse(u)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:f,region:p,endpoint:m,invocationType:h,qualifier:g,args:_,dataKey:v}=d,y;try{y=await n({lambdaName:f,payload:buildPayloadFromArgs(_),region:p,endpoint:m,invocationType:h,qualifier:g,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(y.functionError){let t=typeof y.payload==`object`&&y.payload!==null&&`errorMessage`in y.payload&&typeof y.payload.errorMessage==`string`?y.payload.errorMessage:`Lambda function error: ${y.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:y.functionError}],output:{statusCode:y.statusCode,message:t,data:y.payload,raw:y}}}return{block:e,successful:!0,output:{data:v?tt(y.payload,v):y.payload,raw:y,statusCode:y.statusCode,executedVersion:y.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?L({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:o,url:s,method:c,authorization:l,args:u,responseMode:d,responseType:f,encoding:p,response:m,maxRedirects:h,followRedirects:g}=Xe.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=u?q(u):{query:{},body:{},headers:{}},y=typeof v?.body==`string`?void 0:v?.body,b=W(O(l)?l:$.parse(_)),x={...v?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T=buildRequestContext(e);if(d===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:o??``,url:s,method:c,headers:x,queryParams:v?.query,body:y,maxRedirects:g?h:0,requestConfig:w,context:T,response:m,responseType:f,authHeaders:b});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:o??``,url:s,method:c,headers:x,queryParams:v?.query,body:y,responseType:f,encoding:p,response:m,maxRedirects:g?h:0,requestConfig:w,context:T,authHeaders:b})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:o,queryParams:s,body:c,maxRedirects:l,requestConfig:u,context:d,response:f,responseType:p,authHeaders:m}=e,h=`${r}${i}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if(O(f?.dataKey)||O(f?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:o,queryParams:s,body:c,responseType:p??`arraybuffer`,encoding:`none`,response:f,maxRedirects:l,requestConfig:u,context:d,authHeaders:m??{}}),h=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),g={...e.fileMetadata,contentLength:h.length};return{block:t,successful:!0,streamOutput:{stream:ae.from(h),headers:O(g.contentType)?{"content-type":g.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:g}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:h,method:a,headers:o,queryParams:s,payload:c,maxRedirects:l,requestConfig:u,context:d}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:o,context:s,authHeaders:c}=e,l=n.data;if(r.urlKey){let e=extractValueByPath(l,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?c:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:o,context:s}),u=encodeFileData(n.data,i),d=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(l,r.fileNameKey);typeof e==`string`&&(d.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(l,r.contentTypeKey);typeof e==`string`&&(d.contentType=e)}T(d.contentType)&&O(r.contentType)&&(d.contentType=r.contentType);let f=buildContentDisposition(d);return{data:u,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:f,fileMetadata:d,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(l,r.dataKey);if(T(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(l,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(l,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}T(a.contentType)&&O(r.contentType)&&(a.contentType=r.contentType);let o=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:o,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if(T(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=D(e[`content-type`])?e[`content-type`]:void 0,n=D(e[`content-length`])?e[`content-length`]:void 0,r=D(e[`content-disposition`])?e[`content-disposition`]:void 0,i=D(e[`last-modified`])?e[`last-modified`]:void 0,a=D(e.etag)?e.etag:void 0,o=n?parseInt(n,10):void 0,s=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(o)?void 0:o,fileName:s,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return Z.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?L(t,e):{},{event:r}=Qe.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},nt=j.object({stepsDataToGroup:j.array(j.string()),isSingleRecord:j.boolean().optional()}),rt=j.object({data:j.unknown()}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=nt.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...O(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},it=e(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=at(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=at(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),at=e((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=ot(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),ot=e((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=N(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return i;case`country_alpha3code_by_alpha3code`:return u;case`country_code_by_country_code`:return h;case`country_name_by_country_name`:return b;case`country_name_by_alpha3code`:return v;case`country_name_by_alpha2code`:return _;case`country_name_by_country_code`:return y;case`country_alpha3code_by_alpha2code`:return l;case`country_alpha3code_by_country_name`:return f;case`country_alpha3code_by_country_code`:return d;case`country_alpha2code_by_alpha3code`:return a;case`country_alpha2code_by_country_name`:return c;case`country_alpha2code_by_country_code`:return s;case`country_code_by_alpha2code`:return p;case`country_code_by_alpha3code`:return m;case`country_code_by_country_name`:return g;case`country_subdivisions_by_alpha2code`:return C;case`country_subdivision_code_by_subdivision_name`:return x;case`country_alpha2code_by_citizenship`:return o;case`country_subdivision_name_by_subdivision_code`:return S;case`document_file_format_from_extension`:return w;default:return}},st=M({targetFieldKey:j.string(),alias:j.string().optional(),expression:j.string().optional(),values:j.unknown().optional(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),enumMapper:M({matcher:j.string().or(M({matchExpression:j.string(),value:j.string()}).array())}).optional(),properties:j.lazy(()=>st).array().optional(),requiredScopes:j.string().array().optional()}),ct=j.object({fields:st.array(),dataSource:j.string(),externalSources:j.record(j.string(),j.string()).optional()}),lt=j.object({data:j.unknown()}),mergeSourceWithState=(e,t)=>E(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=ct.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),s=N(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!s)return{block:e,successful:!0};let c=Object.keys(a??{})?.reduce((e,t)=>(e[t]=N(a?.[t],o),e),{}),l;if(Array.isArray(s))l=s.map(e=>{let t=dt(r,{...e,external:c},o);return n.push(...t?.errors||[]),t?.record});else{let e=dt(r,{...s,external:c},o);l=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:l},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),o=dt(e.properties,a,r);return O(o?.errors)&&n.push(...o.errors),o?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=N(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=dt(e.properties,t,i);return O(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=dt(e.properties,t,i);return O(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=O(e.values)?e.values:t,a=dt(e.properties,i,r);return O(a?.errors)&&n.push(...a.errors),a?.record},ut=e((e,t,n,r,i)=>{if(!T(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),dt=e((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=ut(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if(F(e))try{return N(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return ft(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},ft=e((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=N(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=ft(e,t,n),i=O(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if(D(a)){let n=getEnumMatcher(a);return O(n)?{value:{value:(O(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if(N(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},pt=j.object({baseUrl:j.string().optional(),url:j.string().optional(),method:j.enum([`tools/call`,`tools/list`]).default(`tools/call`),toolName:j.string().optional(),timeout:j.number().int().positive().optional(),authorization:$.optional(),args:M({name:j.string(),value:j.unknown(),condition:j.string().optional()}).array().optional()}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),mt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),buildMcpClient=e=>new V(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if(O(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?L({...t,args:i},e):{},o;try{o=pt.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:s,url:c,method:l,toolName:u,timeout:d,authorization:f,args:p}=o,m=`${s??``}${c??``}`;if(!m)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let h=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,g;try{g=W(O(f)?f:$.parse(h??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let _=e.connector?.rateLimit,v=e.connector?.concurrency,y=n({serverUrl:m,headers:g,timeout:d,requestConfig:_!==void 0||v!==void 0?{rateLimits:_,concurrency:v}:void 0,context:buildRequestContext(e)});try{if(l===`tools/list`){let t=await y.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!u)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await y.callTool({name:u,arguments:buildToolArguments(p)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${u}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:u}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await y.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>oe.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},f={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+se()},p=Buffer.from(l(f)).toString(`base64`);return await u(1e3),p},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
1
+ import{t as e}from"./chunk-BhWHdk3m.mjs";import{decodeFromBase64 as t,encodeToBase64 as n,getContentHash as r,getCountryAlpha2CodeByAlpha2Code as i,getCountryAlpha2CodeByAlpha3Code as a,getCountryAlpha2CodeByCitizenship as o,getCountryAlpha2CodeByCountryCode as s,getCountryAlpha2CodeByCountryName as c,getCountryAlpha3CodeByAlpha2Code as l,getCountryAlpha3CodeByAlpha3Code as u,getCountryAlpha3CodeByCountryCode as d,getCountryAlpha3CodeByCountryName as f,getCountryCodeByAlpha2Code as p,getCountryCodeByAlpha3Code as m,getCountryCodeByCountryCode as h,getCountryCodeByCountryName as g,getCountryNameByAlpha2Code as _,getCountryNameByAlpha3Code as v,getCountryNameByCountryCode as y,getCountryNameByCountryName as b,getCountrySubDivisionCodeBySubDivisionName as x,getCountrySubDivisionNameBySubDivisionCode as S,getCountrySubDivisionsByAlpha2Code as C,getDocumentFileFormatFromExtension as w,isMissing as T,isObject as E,isString as D,notMissing as O,safeParseToBoolean as ee,safeParseToDateTimeString as k,safeParseToNumber as A,safeParseToString as te,z as j,zStrictObject as M}from"@stackone/utils";import{evaluate as N,isExpression as P,isValidExpression as F,safeEvaluate as I,safeEvaluateRecord as L}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as R,HttpMethods as z,HttpResponseError as B,McpClient as V,QueryArrayFormats as H,RequestClientFactory as ne,RequestParameterLocations as U,buildHttpsAgent as re,createAuthorizationHeaders as W,getSigningStrategy as G,isFailedStatusCode as K,parseRequestParameters as q,serializeHttpResponseError as J,translateCustomError as Y}from"@stackone/transport";import{InvokeCommand as X,LambdaClient as ie}from"@aws-sdk/client-lambda";import{Readable as ae}from"node:stream";import Z from"mime-types";import{Saml20 as oe}from"saml";import{v4 as se}from"uuid";import{REDACT_CENSOR as Q}from"@stackone/redaction";import{createHash as ce,createPrivateKey as le,createPublicKey as ue}from"node:crypto";import{SignJWT as de}from"jose";import fe from"form-data";const pe=[`context`,`inputs`,`steps`,`intermediateSteps`,`iterator`,`result`],buildExpressionContext=(e,t={})=>{let n=t.includeCredentials??e.context?.flowType===`refresh_authentication`,r=pe.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{});return n&&`credentials`in e&&(r.credentials=e.credentials),r},me={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`},iam:{title:`IAM`,key:`iam`,description:`Identity and Access Management`},internal:{title:`Internal`,key:`internal`,description:`Category for internal actions`},action:{title:`Action`,key:`action`,description:`Action`}},getCategoryDetails=e=>me[e.toLowerCase()]??null,isValidCategory=e=>!!me[e.toLowerCase()],he=n(`so1!`),ge=RegExp(`(?<!\\\\):`,`g`),_e=RegExp(`(?<!\\\\),`,`g`),ve=1;var ye=class CoreError extends Error{constructor({category:e,name:t,type:n,context:r,message:i}){super(i),this.name=t??`CoreError`,this.type=n,this.category=e,this.context=r,Error.captureStackTrace&&Error.captureStackTrace(this,CoreError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},BaseCompositeIdError=class extends ye{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},CompositeIdMissingHeaderError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},CompositeIdMissingBodyError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},CompositeIdUnknownIdentifierError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},CompositeIdUnsupportedVersionError=class extends BaseCompositeIdError{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const isSingleIdentifier=e=>!T(e)&&`value`in e&&e.value!==void 0,isMultipleIdentifier=e=>!T(e)&&`identifiers`in e&&e.identifiers!==void 0,encodeCompositeId=(e,t={version:1})=>{if(t.version===1)return encodeIdV1(getComposedIdV1(e,t.aliases));throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${t.version}`)},decodeCompositeId=(e,t={version:1})=>{let n=decodeId(e,t),r={};return n&&n.split(_e).forEach(e=>{let[n,i]=e.split(ge),a=getOriginalKey(n,t.aliases??{});r[a]=unescapeValue(i)}),r},getComposedIdV1=(e,t={})=>{if(isSingleIdentifier(e))return getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(isMultipleIdentifier(e))return e.identifiers.map(e=>getSingleIdentifierString({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(`,`);throw new CompositeIdUnknownIdentifierError},getSingleIdentifierString=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>[n?`id`:t[e.key]||e.key,escapeValue(e.value)].filter(Boolean).join(`:`),getOriginalKey=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,decodeId=(e,t)=>{if(t.version===1)return decodeIdV1(e);throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${t.version}`)},encodeIdV1=e=>`${he}${n(e)}`,decodeIdV1=e=>{if(!e.startsWith(he))throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${e}`);let n=e.split(he)[1];if(!n)throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${e}`);return t(n)},escapeValue=e=>[`,`,`:`].reduce((e,t)=>e.replace(t,`\\`+t),e),unescapeValue=e=>[`,`,`:`].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),isCompositeId=e=>T(e)?!1:e.startsWith(he),be=/\$\{([^}]+)\}/,xe=`must be a bare JEXL expression and must not contain '{{', '}}', or an interpolation`,isBareJexl=e=>!e.includes(`{{`)&&!e.includes(`}}`)&&!be.test(e),computeDataSyncFingerprint=e=>{let{incremental:t}=e;return r({indexField:Array.isArray(e.indexField)?e.indexField:[e.indexField],incremental:t?{type:t.type,iteratorKey:t.iterator.key,iteratorIn:t.iterator.in,format:`format`in t?t.format:null}:null})},evaluateExternalAccountIdExtractor=(e,t)=>{let n=e.events?.externalAccountIdExtractor;if(T(n)||typeof n.result!=`string`||n.result.trim().length===0)return;let r=I(`{{${n.result.trim()}}}`,t);if(!T(r)){if(typeof r==`string`){let e=r.trim();return e.length>0?e:void 0}if(typeof r==`number`||typeof r==`bigint`||typeof r==`boolean`)return String(r)}},resolveEvents=(e,t)=>{if(e===void 0)return[t.body];if(O(e)&&typeof e!=`string`)throw Error(`events.router.itemsPath must be a string, received ${typeof e}`);let n=O(e)?e.trim():``;if(n.length===0)throw Error(`events.router.itemsPath is declared but must not be blank`);if(!isBareJexl(n))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It ${xe}`);let r;try{r=N(`{{${n}}}`,t,{throwOnEvalError:!0})}catch(e){throw Error(`Failed to evaluate events.router.itemsPath: ${n}. ${e.message}`)}if(T(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. The path resolved to nothing. Check it against the delivery payload, and put rules that match the whole delivery under events.router.delivery`);if(!Array.isArray(r))throw Error(`Failed to evaluate events.router.itemsPath: ${n}. It did not resolve to a list of events`);return r},firstMatch=(e,t)=>{for(let n of e){if(typeof n.when!=`string`)throw Error(`events.router rule when must be a string, received ${typeof n.when}`);let e=n.when.trim();if(e.length===0)continue;let r=I(`{{${e}}}`,t);if(r===null||r===!1||r===void 0)continue;let i=T(n.then.input)?void 0:Object.fromEntries(Object.entries(n.then.input).map(([e,n])=>{if(typeof n!=`string`)throw Error(`events.router rule input ${e} must be a string, received ${typeof n}`);let r=n.trim();if(r.length===0)return[e,void 0];try{return[e,N(`{{${r}}}`,t)]}catch(t){throw Error(`Failed to evaluate events.router rule input ${e}: ${r}. ${t.message}`)}}));return{action:n.then.action,input:i,event:t.event,eventIndex:t.eventIndex}}},evaluateEventRouter=(e,t)=>{let n=e.events?.router;if(T(n))return{matches:[],totalEvents:0};if(O(n.delivery)){let e=firstMatch(n.delivery,{...t,event:t.body,eventIndex:0});if(O(e))return{matches:[e],totalEvents:1}}let r=resolveEvents(n.itemsPath,t),i=[];return r.forEach((e,r)=>{let a=firstMatch(n.rules,{...t,event:e,eventIndex:r});O(a)&&i.push(a)}),{matches:i,totalEvents:r.length}},Se={email:/^[^\s@]+@(?=[^\s@]+\.[^\s@])[^\s@]+$/,url:/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,date:/^\d{4}-\d{2}-\d{2}$/,datetime:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}(?::?\d{2})?)?$/},Ce={employment_status:[`active`,`inactive`,`terminated`,`pending`,`leave`],employment_type:[`full_time`,`part_time`,`contractor`,`intern`,`temporary`],gender:[`male`,`female`,`non_binary`,`other`,`prefer_not_to_say`],marital_status:[`single`,`married`,`divorced`,`widowed`,`domestic_partnership`]},getInputEnumValues=e=>Ce[e],isValidEnumRef=e=>e in Ce,we=[`preview`,`beta`,`ga`,`deprecated`,`internal`],Te=[`auth`,`downstream-change`,`bug-fix`,`new-actions`],Ee=[`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`test`,`event`,`unknown`],De=[`read`,`write`,`delete`,`search`,`execute`],Oe=[`native`,`unified`],ke=[`body`,`query`,`path`,`headers`],Ae=[`email`,`url`,`uuid`,`date`,`datetime`,`uri`],je=[`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`],Me=[`sync`,`async`],Ne=M({r:j.record(j.string(),M({n:j.number().optional().nullable(),c:j.string().optional().nullable(),p:j.number().optional().nullable()})),v:j.number(),t:j.number()}),Pe=M({remote:j.record(j.string(),M({pageNumber:j.number().optional(),providerPageCursor:j.string().optional(),position:j.number().optional()})),version:j.number(),timestamp:j.number()}),minifyCursor=e=>n(JSON.stringify(minifyCursorObject(e))),minifyCursorObject=e=>{let{remote:t,version:n,timestamp:r}=e;return{r:Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),v:n,t:r}},expandCursor=e=>{try{if(D(e)){let n=t(e),r=JSON.parse(n);return expandCursorObject(Ne.parse(r))}else return Pe.parse(e),e}catch{return null}},expandCursorObject=e=>{let{r:t,v:n,t:r}=e;return{remote:Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),version:n,timestamp:r}},areCursorsEqual=(e,t)=>{let n=typeof e==`string`?expandCursor(e):e,i=typeof t==`string`?expandCursor(t):t;if(n===null||i===null)return n===i;let{timestamp:a,...o}=n,{timestamp:s,...c}=i;return r(o)===r(c)},isCursorEmpty=({cursor:e,ignoreStepIndex:t})=>T(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return(T(t)||r!==t.toString())&&(n=n&&T(i.pageNumber)&&T(i.position)&&T(i.providerPageCursor)),n},!0),updateCursor=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=T(n)&&T(r)&&T(i);return T(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},isCoreError=e=>e instanceof ye;function stripPaginationParams(e,t){let n=getPaginationKeys(t);if(n.length===0)return e;let r=getIteratorLocation(t);if(!r)return e;let i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};for(let e of n)delete a[e];return{...e,[r]:a}}function getPaginationKeys(e){switch(e.type){case`cursor`:return[e.iterator.key];case`offset`:{let t=e;return[t.iterator.offsetKey,t.iterator.limitKey]}case`page`:{let t=e,n=[t.iterator.pageKey];return t.iterator.pageSizeKey&&n.push(t.iterator.pageSizeKey),n}default:return[]}}function getIteratorLocation(e){if(`iterator`in e&&typeof e.iterator==`object`&&e.iterator!==null)return e.iterator.in}function stripIncrementalParams(e,t){if(!t)return e;let{key:n,in:r}=t.iterator,i=e[r];if(!i||typeof i!=`object`)return e;let a={...i};return delete a[n],{...e,[r]:a}}const Fe={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},Ie={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},Le={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},Re={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},browserUseStepFunction=async()=>{throw Error(`browser_use step function cannot be executed synchronously — actions using this step must have executionMode: "async" so they are dispatched to the Temporal workflow runtime`)},ze=j.object({startUrl:j.string().url(),systemPrompt:j.string().optional(),viewport:M({width:j.number().int().positive(),height:j.number().int().positive()}).optional(),locale:j.string().optional(),budgets:M({maxDurationMs:j.number().int().positive(),maxSteps:j.number().int().positive()}),auth:M({sensitiveKeys:j.array(j.string().min(1)).optional(),requiresSession:j.boolean().optional(),allowedDomains:j.array(j.string().min(1)).optional()}).optional()}),Be=j.unknown(),Ve=M({lambdaName:j.string(),region:j.string().optional(),endpoint:j.string().optional(),invocationType:j.enum([`RequestResponse`,`Event`,`DryRun`]).optional(),qualifier:j.string().optional(),args:M({name:j.string(),value:j.unknown(),condition:j.string().optional()}).array().optional().meta({description:`Key/value pairs combined into the JSON payload sent to the Lambda function`}),dataKey:j.string().optional()}),He=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),executedVersion:j.string().optional()}).optional(),Ue=M({strategy:j.literal(`aws4`),service:j.string(),region:j.string().optional()}),We=M({strategy:j.literal(`hmac`),algorithm:j.enum([`sha1`,`sha256`,`sha512`]).optional(),headerName:j.string().optional(),prefix:j.string().optional(),dateFormat:j.enum([`iso8601`,`rfc2822`]).optional(),includeHost:j.boolean().optional(),includeBodyHash:j.boolean().optional(),outputFormat:j.enum([`header`,`basic`]).optional(),username:j.string().optional()}),Ge=j.discriminatedUnion(`strategy`,[Ue,We]),Ke=M({type:j.literal(`none`),signing:Ge.optional(),redirectUri:j.string().optional()}),qe=M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional(),redirectUri:j.string().optional()}),Je=M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0),redirectUri:j.string().optional()}),Ye=new Set([`accessToken`,`refreshToken`,`idToken`,`clientId`,`clientSecret`,`authentication_config_key`,`environment`]),Xe=M({type:j.literal(`oauth2`),authorizationUrl:j.string().optional(),redirectUri:j.string().optional(),authorizationParams:j.record(j.string(),j.string()).optional(),tokenUrl:j.string().optional(),tokenParams:j.record(j.string(),j.string()).optional(),tokenExpiresIn:j.number().optional(),tokenRefreshExpiresIn:j.number().optional(),token:j.string(),includeBearer:j.boolean().optional().default(!0),scopes:j.string().optional(),scopeDelimiter:j.string().optional(),customHeaders:j.record(j.string(),j.string()).optional(),pkce:j.boolean().optional(),additionalTokenFields:j.record(j.string(),j.string().optional()).optional(),callbackParams:j.record(j.string(),j.string().min(1)).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))Ye.has(r)&&t.addIssue({code:j.ZodIssueCode.custom,path:[n],message:`callbackParams must not target reserved credential key "${r}"`})}).optional(),issuer:j.string().optional(),tokenResponse:M({acceptTokenTypes:j.array(j.string()).optional(),accessToken:j.string().min(1).optional(),refreshToken:j.string().min(1).optional()}).optional()}),$=j.discriminatedUnion(`type`,[Ke,qe,Je,Xe]),Ze=M({certs:j.string().array().optional(),keys:j.string().array().optional()}).optional(),Qe=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).optional().default(`get`),authorization:$.optional(),responseMode:j.enum([`buffer`,`stream`]).optional().default(`buffer`),responseType:j.enum([`arraybuffer`,`blob`,`text`,`json`]).optional().default(`arraybuffer`),encoding:j.enum([`base64`,`utf8`,`binary`,`raw`,`none`]).optional().default(`base64`),response:M({dataKey:j.string().optional(),fileNameKey:j.string().optional(),contentTypeKey:j.string().optional(),contentType:j.string().optional(),contentIsBase64:j.boolean().optional().default(!1),urlKey:j.string().optional(),forwardAuth:j.boolean().optional().default(!1)}).optional(),maxRedirects:j.number().optional().default(5),followRedirects:j.boolean().optional().default(!0),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),$e=M({data:j.union([j.string(),j.instanceof(Buffer)]).optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),headers:j.record(j.string(),j.union([j.string(),j.array(j.string())])).optional(),contentDisposition:j.string().optional(),fileMetadata:M({contentType:j.string().optional(),contentLength:j.number().optional(),fileName:j.string().optional(),lastModified:j.string().optional(),etag:j.string().optional()}).optional(),finalUrl:j.string().optional()}).optional(),et=j.object({event:j.object({eventType:j.string(),eventId:j.coerce.string().optional(),eventDate:j.coerce.string().optional(),data:j.unknown().optional()}).optional()}),tt=j.record(j.string(),j.unknown()),sanitizeRaw=e=>{let t={};return e.status!=null&&(t.status=e.status),e.data!==void 0&&(t.data=e.data),e.headers!=null&&(t.headers=e.headers),e.requestUrl!=null&&(t.requestUrl=e.requestUrl),e.message!=null&&(t.message=e.message),t},isSerializedBuffer=e=>typeof e==`object`&&!!e&&e.type===`Buffer`&&Array.isArray(e.data),decodeBinaryBody=e=>{let t;if(Buffer.isBuffer(e)?t=e.toString(`utf8`):e instanceof ArrayBuffer?t=new TextDecoder().decode(new Uint8Array(e)):ArrayBuffer.isView(e)?t=new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):isSerializedBuffer(e)&&(t=Buffer.from(e.data).toString(`utf8`)),t===void 0)return e;try{return JSON.parse(t)}catch{return t}},decodeResponseBody=e=>({...e,data:decodeBinaryBody(e.data)}),isHttpLikeError=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`,extractTopLevelMessage=e=>{if(typeof e.message==`string`&&e.message.trim().length>0)return e.message},extractNestedErrorMessage=e=>{if(e.error!=null&&typeof e.error==`object`&&!Array.isArray(e.error)&&typeof e.error.message==`string`)return e.error.message;if(typeof e.error==`string`&&e.error.length>0)return e.error;if(typeof e.error_description==`string`&&e.error_description.length>0)return e.error_description},extractErrorMessage=(e,t)=>{let n=e.data;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractTopLevelMessage(n);if(e!=null)return e}if(typeof e.message==`string`&&e.message.length>0)return e.message;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=extractNestedErrorMessage(n);if(e!=null)return e}if(Array.isArray(n)&&n.length>0){let e=n[0];if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e,n=extractTopLevelMessage(t)??extractNestedErrorMessage(t);if(n!=null)return n}}return typeof n==`string`&&n.length>0?n:t},buildStepErrorOutput=(e,t)=>{if(e instanceof B){let n=e.message,r=decodeResponseBody(e.response);return{block:t,successful:!1,errors:[J(e)],output:{statusCode:r?.status??500,message:extractErrorMessage(r,n),data:r?.data,raw:sanitizeRaw(r)}}}if(isHttpLikeError(e)){let n=decodeResponseBody(e.response),r=e instanceof Error?e.message:`HTTP error: ${n.status??500}`;return{block:t,successful:!1,errors:[J(e)],output:{statusCode:n.status??500,message:extractErrorMessage(n,r),data:n.data,raw:sanitizeRaw(n)}}}return e instanceof Error?{block:t,successful:!1,errors:[J(e)],output:{statusCode:500,message:e.message}}:{block:t,successful:!1,errors:[J(e)],output:{statusCode:500,message:String(e)}}},isAwsCredentials=e=>!!e&&typeof e.accessKeyId==`string`&&typeof e.secretAccessKey==`string`,buildLambdaClientConfig=({region:e,endpoint:t,credentials:n})=>({region:e,...t?{endpoint:t}:{},...isAwsCredentials(n)?{credentials:{accessKeyId:n.accessKeyId,secretAccessKey:n.secretAccessKey,sessionToken:typeof n.sessionToken==`string`?n.sessionToken:void 0}}:t?{credentials:{accessKeyId:`local`,secretAccessKey:`local`}}:{}}),defaultClientFactory=e=>new ie(e),invokeLambda=async({lambdaName:e,payload:t,region:n,endpoint:r,invocationType:i=`RequestResponse`,qualifier:a,credentials:o,clientFactory:s=defaultClientFactory})=>{let c=s(buildLambdaClientConfig({region:n,endpoint:r,credentials:o})),l=new X({FunctionName:e,InvocationType:i,Qualifier:a,Payload:t?Buffer.from(JSON.stringify(t)):void 0}),u=await c.send(l),d=u.Payload?Buffer.from(u.Payload).toString(`utf-8`):``,f;if(d.length===0)f=void 0;else try{f=JSON.parse(d)}catch{f=d}return{statusCode:u.StatusCode??200,payload:f,functionError:u.FunctionError,executedVersion:u.ExecutedVersion}},nt=/\${[^}]+}/,isJsonPathLike=e=>{let t=e.trimStart();return t.startsWith(`$.`)||t.startsWith(`$[`)},hasExpressionMarker=e=>P(e)||nt.test(e)||isJsonPathLike(e),buildDataKeyExpression=e=>P(e)||e.trimStart().startsWith(`$`)?e:`$.${e}`,rt=e((e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;try{let n=N(buildDataKeyExpression(t),e);if(n!==void 0)return n}catch{}return e[t]},`resolveDataKey`),buildPayloadFromArgs=e=>{if(!(!e||e.length===0))return e.reduce((e,t)=>(e[t.name]=t.value,e),{})},codeExecutionLambdaStepFunction=async({block:e,params:t},n=invokeLambda)=>{let r=t?.args,i=Array.isArray(r)?r:void 0,isPlainObject=e=>typeof e==`object`&&!!e,a=i?i.filter(t=>{if(!isPlainObject(t))return!0;let n=t.condition;return typeof n!=`string`||I(n,e)===!0}).map(e=>isPlainObject(e)?{...e,condition:void 0}:e):void 0,o=t?.dataKey,s=typeof o==`string`&&!nt.test(o),c=t?.qualifier,l=typeof c==`string`&&!hasExpressionMarker(c),u={...t?L(i===void 0?t:{...t,args:a},e):{},...s?{dataKey:o}:{},...l?{qualifier:c}:{}},d;try{d=Ve.parse(u)}catch(t){return buildStepErrorOutput(t,e)}let{lambdaName:f,region:p,endpoint:m,invocationType:h,qualifier:g,args:_,dataKey:v}=d,y;try{y=await n({lambdaName:f,payload:buildPayloadFromArgs(_),region:p,endpoint:m,invocationType:h,qualifier:g,credentials:e.credentials})}catch(t){return buildStepErrorOutput(t,e)}if(y.functionError){let t=typeof y.payload==`object`&&y.payload!==null&&`errorMessage`in y.payload&&typeof y.payload.errorMessage==`string`?y.payload.errorMessage:`Lambda function error: ${y.functionError}`;return{block:e,successful:!1,errors:[{message:t,kind:`lambda_function_error`,functionError:y.functionError}],output:{statusCode:y.statusCode,message:t,data:y.payload,raw:y}}}return{block:e,successful:!0,output:{data:v?rt(y.payload,v):y.payload,raw:y,statusCode:y.statusCode,executedVersion:y.executedVersion}}},buildRequestContext=e=>({accountSecureId:e.context.accountSecureId,projectSecureId:e.context.projectSecureId,organizationId:e.context.organizationId,environment:e.context.environment,authConfigKey:e.context.authenticationType,provider:e.connector?.key,service:e.context.category,resource:e.connector?.key,action:e.action?.id}),downloadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?L({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:o,url:s,method:c,authorization:l,args:u,responseMode:d,responseType:f,encoding:p,response:m,maxRedirects:h,followRedirects:g}=Qe.parse(a),_=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=u?q(u):{query:{},body:{},headers:{}},y=typeof v?.body==`string`?void 0:v?.body,b=W(O(l)?l:$.parse(_)),x={...v?.headers??{},...b},S=e.connector?.rateLimit,C=e.connector?.concurrency,w=S!==void 0||C!==void 0?{rateLimits:S,concurrency:C}:void 0,T=buildRequestContext(e);if(d===`stream`)return performStreamDownload({block:e,httpClient:e.httpClient,baseUrl:o??``,url:s,method:c,headers:x,queryParams:v?.query,body:y,maxRedirects:g?h:0,requestConfig:w,context:T,response:m,responseType:f,authHeaders:b});try{return{block:e,successful:!0,output:await performDownload({httpClient:e.httpClient,baseUrl:o??``,url:s,method:c,headers:x,queryParams:v?.query,body:y,responseType:f,encoding:p,response:m,maxRedirects:g?h:0,requestConfig:w,context:T,authHeaders:b})}}catch(t){return buildStepErrorOutput(t,e)}},performStreamDownload=async e=>{let{block:t,httpClient:n,baseUrl:r,url:i,method:a,headers:o,queryParams:s,body:c,maxRedirects:l,requestConfig:u,context:d,response:f,responseType:p,authHeaders:m}=e,h=`${r}${i}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);if(O(f?.dataKey)||O(f?.urlKey))try{let e=await performDownload({httpClient:n,baseUrl:r,url:i,method:a,headers:o,queryParams:s,body:c,responseType:p??`arraybuffer`,encoding:`none`,response:f,maxRedirects:l,requestConfig:u,context:d,authHeaders:m??{}}),h=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data),g={...e.fileMetadata,contentLength:h.length};return{block:t,successful:!0,streamOutput:{stream:ae.from(h),headers:O(g.contentType)?{"content-type":g.contentType}:{},contentDisposition:e.contentDisposition,fileMetadata:g}}}catch(e){return buildStepErrorOutput(e,t)}if(!n.requestStream)throw Error(`HTTP client does not support streaming. Either implement requestStream method or use responseMode: "buffer".`);try{let e=await n.requestStream({url:h,method:a,headers:o,queryParams:s,payload:c,maxRedirects:l,requestConfig:u,context:d}),r=extractFileMetadata(e.headers),i=buildContentDisposition(r);return{block:t,successful:!0,streamOutput:{stream:e.stream,headers:e.headers,contentDisposition:i,fileMetadata:r}}}catch(e){return buildStepErrorOutput(e,t)}},performDownload=async e=>{let{httpClient:t,baseUrl:n,url:r,method:i,headers:a,queryParams:o,body:s,responseType:c,encoding:l,response:u,maxRedirects:d,requestConfig:f,context:p,authHeaders:m}=e,h=`${n}${r}`;if(!h.startsWith(`http://`)&&!h.startsWith(`https://`))throw Error(`Invalid URL: "${h}". URL must be absolute (start with http:// or https://). Either provide a baseUrl or ensure url is a complete URL.`);let g=u?.urlKey||u?.dataKey?`json`:c,_=await t.request({url:h,method:i,headers:a,queryParams:o,payload:s,responseType:g===`json`?void 0:g,maxRedirects:d,requestConfig:f,context:p});if(u?.urlKey||u?.dataKey)return handleJsonResponse({httpClient:t,result:_,response:u,encoding:l,maxRedirects:d,requestConfig:f,context:p,authHeaders:m});let v=encodeFileData(_.data,l),y=extractFileMetadata(_.headers),b=buildContentDisposition(y);return{data:v,raw:_,statusCode:_?.status,message:_?.message,headers:_.headers,contentDisposition:b,fileMetadata:y,finalUrl:_?.requestUrl}},handleJsonResponse=async e=>{let{httpClient:t,result:n,response:r,encoding:i,maxRedirects:a,requestConfig:o,context:s,authHeaders:c}=e,l=n.data;if(r.urlKey){let e=extractValueByPath(l,r.urlKey);if(typeof e==`string`){let n=await t.request({url:e,method:`get`,headers:r.forwardAuth?c:{},responseType:`arraybuffer`,maxRedirects:a,requestConfig:o,context:s}),u=encodeFileData(n.data,i),d=extractFileMetadata(n.headers);if(r.fileNameKey){let e=extractValueByPath(l,r.fileNameKey);typeof e==`string`&&(d.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(l,r.contentTypeKey);typeof e==`string`&&(d.contentType=e)}T(d.contentType)&&O(r.contentType)&&(d.contentType=r.contentType);let f=buildContentDisposition(d);return{data:u,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:f,fileMetadata:d,finalUrl:e}}}if(r.dataKey){let e=extractValueByPath(l,r.dataKey);if(T(e))throw Error(`No file content found at path: ${r.dataKey}`);let t;if(typeof e==`string`)t=r.contentIsBase64?i===`base64`?e:i===`none`?Buffer.from(e,`base64`):Buffer.from(e,`base64`).toString(i===`raw`?`binary`:i):encodeFileData(e,i);else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=encodeFileData(e,i);else throw Error(`Unexpected file content type at path: ${r.dataKey}`);let a={};if(r.fileNameKey){let e=extractValueByPath(l,r.fileNameKey);typeof e==`string`&&(a.fileName=e)}if(r.contentTypeKey){let e=extractValueByPath(l,r.contentTypeKey);typeof e==`string`&&(a.contentType=e)}T(a.contentType)&&O(r.contentType)&&(a.contentType=r.contentType);let o=buildContentDisposition(a);return{data:t,raw:n,statusCode:n?.status,message:n?.message,headers:n.headers,contentDisposition:o,fileMetadata:a}}throw Error(`JSON response handling requires either urlKey or dataKey to be specified`)},extractValueByPath=(e,t)=>{let n=(t.startsWith(`$.`)?t.slice(2):t).split(`.`),r=e;for(let e of n){if(T(r)||typeof r!=`object`)return;r=r[e]}return r},encodeFileData=(e,t)=>{if(t===`none`)return e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`string`?Buffer.from(e):Buffer.from(JSON.stringify(e));if(t===`raw`)return typeof e==`string`?e:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?Buffer.from(e).toString(`binary`):JSON.stringify(e);if(typeof e==`string`)return t===`base64`?Buffer.from(e).toString(`base64`):e;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let n=Buffer.from(e);switch(t){case`base64`:return n.toString(`base64`);case`utf8`:return n.toString(`utf8`);default:return n.toString(`binary`)}}return JSON.stringify(e)},extractFileMetadata=e=>{let t=D(e[`content-type`])?e[`content-type`]:void 0,n=D(e[`content-length`])?e[`content-length`]:void 0,r=D(e[`content-disposition`])?e[`content-disposition`]:void 0,i=D(e[`last-modified`])?e[`last-modified`]:void 0,a=D(e.etag)?e.etag:void 0,o=n?parseInt(n,10):void 0,s=extractFileName(r);return{contentType:t,contentLength:Number.isNaN(o)?void 0:o,fileName:s,lastModified:i,etag:a}},extractFileName=e=>{if(!e)return;let t=e.match(/filename\*=(?:UTF-8''|utf-8'')([^;\s]+)/i);if(t&&t[1])try{return decodeURIComponent(t[1])}catch{}let n=e.match(/filename=["']([^"']+)["']/);if(n&&n[1])return n[1];let r=e.match(/filename=([^;\s]+)/);if(r&&r[1])return r[1]},buildContentDisposition=e=>{let{fileName:t,contentType:n}=e,r=`attachment`;if(t)r=`attachment; filename="${t}"; filename*=UTF-8''${encodeURIComponent(t).replace(/['()]/g,escape)}`;else if(n){let e=getExtensionFromContentType(n);e&&(r=`attachment; filename="download.${e}"`)}return r},getExtensionFromContentType=e=>{let t=e.split(`;`)[0].trim().toLowerCase();return Z.extension(t)||void 0},emitEventStepFunction=async({block:e,params:t})=>{let n=t?L(t,e):{},{event:r}=et.parse(n);if(r&&e.emitEvent)try{await e.emitEvent({eventType:r.eventType,eventId:r.eventId,eventDate:r.eventDate,data:r.data})}catch(t){throw e.logger?.error({code:`EmitEventError`,message:`emitEvent callback failed: ${t.message}`}),t}else r&&!e.emitEvent&&e.logger?.warning({message:`emit_event step executed but no emitEvent callback provided on the block`});let{event:i,...a}=n;return{block:{...e},successful:!0,output:a}},it=j.object({stepsDataToGroup:j.array(j.string()),isSingleRecord:j.boolean().optional()}),at=j.object({data:j.unknown()}),groupDataStepFunction=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=it.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{t[e]={...O(t[e])?t[e]:{},[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},ot=e(async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i=buildExpressionContext(e),a;if(Array.isArray(e.result)){let o=e.result.length;a=e.result.map((e,a)=>{let s=st(e,t,extractSingleRecordBlockStepData(r,o,a),i);return n.push(...s.errors||[]),s.record})}else{let o=st(e.result,t,r,i);a=o.record,n.push(...o.errors||[])}return{block:{...e,result:a},successful:!0,errors:Object.keys(n).length>0?n:void 0}},`mapFieldsStepFunction`),extractSingleRecordBlockStepData=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),st=e((e,t,n,r)=>{if(!e||!n)return{record:e};let i={...r,unified:{...e},...typeof n==`object`?n:{}},a={},o=[],s={...e};for(let n of t){let{error:t,value:r}=ct(i,e.id,n);if(t){o.push(t);continue}n.custom?a[n.targetFieldKey]=r:s[n.targetFieldKey]=r}return{record:{...s,unified_custom_fields:Object.keys(a).length>0?a:void 0},errors:o.length>0?o:void 0}},`mapSingleRecord`),ct=e((e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=N(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},`extractFieldValue`),getEnumMatcher=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return i;case`country_alpha3code_by_alpha3code`:return u;case`country_code_by_country_code`:return h;case`country_name_by_country_name`:return b;case`country_name_by_alpha3code`:return v;case`country_name_by_alpha2code`:return _;case`country_name_by_country_code`:return y;case`country_alpha3code_by_alpha2code`:return l;case`country_alpha3code_by_country_name`:return f;case`country_alpha3code_by_country_code`:return d;case`country_alpha2code_by_alpha3code`:return a;case`country_alpha2code_by_country_name`:return c;case`country_alpha2code_by_country_code`:return s;case`country_code_by_alpha2code`:return p;case`country_code_by_alpha3code`:return m;case`country_code_by_country_name`:return g;case`country_subdivisions_by_alpha2code`:return C;case`country_subdivision_code_by_subdivision_name`:return x;case`country_alpha2code_by_citizenship`:return o;case`country_subdivision_name_by_subdivision_code`:return S;case`document_file_format_from_extension`:return w;default:return}},lt=M({targetFieldKey:j.string(),alias:j.string().optional(),expression:j.string().optional(),values:j.unknown().optional(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),enumMapper:M({matcher:j.string().or(M({matchExpression:j.string(),value:j.string()}).array())}).optional(),properties:j.lazy(()=>lt).array().optional(),requiredScopes:j.string().array().optional()}),ut=j.object({fields:lt.array(),dataSource:j.string(),externalSources:j.record(j.string(),j.string()).optional()}),dt=j.object({data:j.unknown()}),mergeSourceWithState=(e,t)=>E(e)?{...t,...e}:e,mapFieldsStepFunction=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i,externalSources:a}=ut.parse(t),o=buildExpressionContext(e,{includeCredentials:!0}),s=N(i,o);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!s)return{block:e,successful:!0};let c=Object.keys(a??{})?.reduce((e,t)=>(e[t]=N(a?.[t],o),e),{}),l;if(Array.isArray(s))l=s.map(e=>{let t=pt(r,{...e,external:c},o);return n.push(...t?.errors||[]),t?.record});else{let e=pt(r,{...s,external:c},o);l=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:l},errors:Object.keys(n).length>0?n:void 0}},handleObjectArrayFromValues=(e,t,n,r)=>{if(Array.isArray(e.values))return e.values.map(i=>{let a=evaluateExpressionsInObject(i,t),o=pt(e.properties,a,r);return O(o?.errors)&&n.push(...o.errors),o?.record}).filter(Boolean)},handleObjectArrayFromExpression=(e,t,n,r,i)=>{if(e.expression)try{let t=N(e.expression,n);if(Array.isArray(t))return t.map(t=>{let n=pt(e.properties,t,i);return O(n?.errors)&&r.push(...n.errors),n?.record}).filter(Boolean);{let n=pt(e.properties,t,i);return O(n?.errors)&&r.push(...n.errors),n?.record}}catch{r.push({message:`Invalid expression`,id:t?.id,targetField:e.targetFieldKey});return}},handleSingleObject=(e,t,n,r)=>{let i=O(e.values)?e.values:t,a=pt(e.properties,i,r);return O(a?.errors)&&n.push(...a.errors),a?.record},ft=e((e,t,n,r,i)=>{if(!T(e.properties))return e.array&&Array.isArray(e.values)?handleObjectArrayFromValues(e,n,r,i):e.array&&e.expression?handleObjectArrayFromExpression(e,t,n,r,i):handleSingleObject(e,t,r,i)},`handleObjectField`),pt=e((e,t,n)=>{if(!t)return;let r=mergeSourceWithState(t,n),i={},a=[],o={};for(let s of e){let e;if(s.type===`object`){if(e=ft(s,t,r,a,n),e===void 0)continue}else{let{error:n,value:i}=extractFieldValue(r,t?.id,s);if(e=i,n){a.push(n);continue}}s.custom?i[s.targetFieldKey]=e:o[s.targetFieldKey]=e}let s=Object.keys(i).length>0?{unified_custom_fields:i}:{};return{record:{...o,...s},errors:a.length>0?a:void 0}},`mapSingleRecord`),evaluateExpressionsInObject=(e,t)=>{if(e==null)return e;if(typeof e==`string`){if(F(e))try{return N(e,t)}catch{return e}return e}if(Array.isArray(e))return e.map(e=>evaluateExpressionsInObject(e,t));if(typeof e==`object`){let n={...e};for(let[e,r]of Object.entries(n))n[e]=evaluateExpressionsInObject(r,t);return n}return e},extractFieldValue=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return mt(n,t,e);case`enum`:return evaluateEnumValue(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},mt=e((e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=N(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},`evaluateValue`),evaluateEnumValue=(e,t,n)=>{let r=mt(e,t,n),i=O(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if(D(a)){let n=getEnumMatcher(a);return O(n)?{value:{value:(O(i)?n(i):null)??`unmapped_value`,source_value:i}}:{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e;if(N(t,n)===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},ht=j.object({baseUrl:j.string().optional(),url:j.string().optional(),method:j.enum([`tools/call`,`tools/list`]).default(`tools/call`),toolName:j.string().optional(),timeout:j.number().int().positive().optional(),authorization:$.optional(),args:M({name:j.string(),value:j.unknown(),condition:j.string().optional()}).array().optional()}).refine(e=>e.method!==`tools/call`||!!e.toolName,{message:`The 'toolName' parameter is required when method is 'tools/call'`,path:[`toolName`]}),gt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),buildMcpClient=e=>new V(e),buildToolArguments=e=>(e??[]).reduce((e,t)=>(e[t.name]=t.value,e),{}),parseJsonText=e=>{try{return JSON.parse(e)}catch{return e}},resolveToolData=e=>{if(O(e.structuredContent))return e.structuredContent;let[t,...n]=e.content;return n.length===0&&t?.type===`text`&&typeof t.text==`string`?parseJsonText(t.text):e.content},extractTextMessage=e=>e.content.find(e=>typeof e.text==`string`)?.text,mcpRequestStepFunction=async({block:e,params:t},n=buildMcpClient)=>{let r=t?.args,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?L({...t,args:i},e):{},o;try{o=ht.parse(a)}catch(t){return buildStepErrorOutput(t,e)}let{baseUrl:s,url:c,method:l,toolName:u,timeout:d,authorization:f,args:p}=o,m=`${s??``}${c??``}`;if(!m)return buildStepErrorOutput(Error(`MCP server URL is missing: set the connector baseUrl or the step url parameter`),e);let h=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,g;try{g=W(O(f)?f:$.parse(h??{type:`none`}))}catch(t){return buildStepErrorOutput(t,e)}let _=e.connector?.rateLimit,v=e.connector?.concurrency,y=n({serverUrl:m,headers:g,timeout:d,requestConfig:_!==void 0||v!==void 0?{rateLimits:_,concurrency:v}:void 0,context:buildRequestContext(e)});try{if(l===`tools/list`){let t=await y.listTools();return{block:e,successful:!0,output:{data:t.tools,raw:t,statusCode:200}}}if(!u)return buildStepErrorOutput(Error(`The 'toolName' parameter is required when method is 'tools/call'`),e);let t=await y.callTool({name:u,arguments:buildToolArguments(p)});if(t.isError){let n=extractTextMessage(t)??`MCP tool '${u}' returned an error`;return{block:e,successful:!1,errors:[{message:n,kind:`mcp_tool_error`,toolName:u}],output:{statusCode:502,message:n,data:resolveToolData(t),raw:t}}}return{block:e,successful:!0,output:{data:resolveToolData(t),raw:t,statusCode:200}}}catch(t){return buildStepErrorOutput(t,e)}finally{await y.close().catch(()=>void 0)}},generateSamlAssertion=async({cert:e,key:t,issuer:n,lifetime:r,clientId:i,nameId:a,tokenEndpoint:o,audience:s,nameIdentifierFormat:c,createSamlFn:l=e=>oe.create(e),sleepFn:u=e=>new Promise(t=>setTimeout(t,e))})=>{let d={api_key:i},f={cert:e,key:generatePrivateKey(t),issuer:n,lifetimeInSeconds:r,audiences:s,attributes:d,nameIdentifier:a,nameIdentifierFormat:c,recipient:o,sessionIndex:`_`+se()},p=Buffer.from(l(f)).toString(`base64`);return await u(1e3),p},generatePrivateKey=e=>{let t=Buffer.from(e,`base64`).toString(`utf-8`).split(`###`);if(t.length!==2)throw Error(`Invalid private key`);let n=t[0];return Buffer.from(`-----BEGIN PRIVATE KEY-----
2
2
  ${n}
3
- -----END PRIVATE KEY-----`)},ht=e(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),gt=e((e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;let n=I(ht(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if(T(e)||typeof e!=`object`)return null;if(ht(t)){let n=I(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if(T(e)||typeof e!=`object`||!e)return null;let n=I(ht(t)?t:`$.${t}`,e);return T(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&ht(n),a=r&&ht(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},_t=j.object({baseUrl:j.string(),url:j.string(),method:j.enum(z),authorization:$.optional(),saml:M({objectKey:j.string(),key:j.string(),clientId:j.string(),cert:j.unknown().optional(),issuer:j.string().optional(),lifetime:j.number().optional(),nameId:j.string().optional(),audience:j.string().optional(),nameIdentifierFormat:j.string().optional(),tokenEndpoint:j.string().optional()}).optional(),response:M({indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional(),nextKeyIn:j.enum([`data`,`headers`]).optional()}).optional(),iterator:M({key:j.string(),in:j.enum([`query`,`body`]),condition:j.string().optional(),mode:j.enum([`cursor`,`offset`,`page`]).optional(),startPage:j.number().int().min(0).max(2**53-1).optional(),maxPage:j.number().int().positive().max(1e4).optional()}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:j.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),cacheTTL:j.number().int().nonnegative().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),vt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=ne.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:i}=t,a=Number(e.inputs?.page_size),o=Number.isNaN(a)?25:a,s=i?i.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,c=t?L({...t,args:s},e):{},l={...c,customErrors:t?.customErrors,iterator:{...c?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,c?.response)},u=l.authorization;if(O(u)){let t=$.safeParse(u);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:d,url:f,method:p,response:m,authorization:h,iterator:g,cursor:_,customErrors:v,encodeQueryParams:y,args:b,saml:x,cacheTTL:S}=_t.parse(l),C=c?.authentication?.[e.context.authenticationType]?.[e.context.environment],w=C?.authorization,D=C?.certificates,ee=D?re(D):void 0,k=O(h)?h:$.parse(w);if(k.type===`none`&&O(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=b?q(b):{query:{},body:{},headers:{}},te=W(k),j={...A?.headers??{},...te},M=e.connector?.rateLimit,P=e.connector?.concurrency,F=M!==void 0||P!==void 0?{rateLimits:M,concurrency:P}:void 0,R=buildRequestContext(e),z=O(x)?{[x.objectKey]:await generateSamlAssertion({key:x.key,clientId:x.clientId,cert:x.cert,issuer:x.issuer,lifetime:x.lifetime,audience:x.audience,nameId:x.nameId,nameIdentifierFormat:x.nameIdentifierFormat,tokenEndpoint:x.tokenEndpoint})}:{},B=g.mode===`offset`,V=g.mode===`page`,H=g.maxPage??1e3,U=H+1,G=V?resolveInitialPage(_?.token,g.startPage??1):_?.token??null,K=null,J=null,Y=[],X=[],ie=[],ae=o,Z=_?.position??0,oe=!0,se=!0,Q=!0,ce=null;do{if(V&&Number(G)>U)return buildStepErrorOutput(maxPageExceededError(H,G),e);oe?oe=!1:B||(Z=0),G===null?B&&(g.in===`query`?A.query[g.key]=Z.toString():g.in===`body`&&(Array.isArray(A.body)||(A.body[g.key]=Z))):g.in===`query`?E(G)?Object.entries(G).forEach(([e,t])=>{A.query[`${g.key}[${e}]`]=t?.toString()??``}):A.query[g.key]=G.toString():g.in===`body`&&(Array.isArray(A.body)||(A.body[g.key]=G));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${d}${f}`,queryParams:{...A?.query},encodeQueryParams:y,method:p,headers:{...j},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...z},customErrorConfigs:v,requestConfig:F,httpsAgent:ee,credentials:e.credentials,context:R,cacheTTL:S})}catch(t){return buildStepErrorOutput(t,e)}if(K=G,X=m?.dataKey?gt(t.data,m.dataKey):t.data,!Array.isArray(X)){let n=V?` at page ${K}`:``,r=m?.dataKey?` at "${m.dataKey}"`:``,i=X===null?`null`:typeof X;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),ie.push(t),J=t?.status,se=!0;break}if(V){let t=r(X);if(t===ce){e.logger?.warning({message:`Pagination stopped at page ${K}: the provider returned the previous page again, so the page number is not advancing`}),se=!0;break}ce=t}if(V&&Number(K)>H&&X.length>0)return buildStepErrorOutput(maxPageExceededError(H,K),e);let i=B?X?.slice(0,ae):X?.slice(Z,Z+ae);ae-=i.length,Z+=i.length,ie.push(t),Y=Y.concat(i),J=t?.status,G=V?incrementPage(Number(K)):yt({result:t,response:m}),Q=O(g.condition)?I(g.condition,t.data)===!0:!0;let a=Z>=(X?.length??0),s=O(m?.nextKey),c=i.length===X.length&&ae===0;!B&&(s||V)&&a&&(Z=0,K=G),se=B?!Q||T(G)&&Y.length<o:V?a&&(!Q||Y.length<o):s?a&&(T(G)||!Q):!Q||T(G)&&Y.length<o||c}while((B||O(G))&&Q&&Y.length<o&&X?.length>0);let le=bt(Y,m),ue=se?void 0:K;return{block:e,successful:!0,output:{data:le,raw:ie,statusCode:J,next:V&&typeof ue==`number`?ue.toString():ue,position:se?void 0:Z}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,yt=e(({result:e,response:t})=>{if(T(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),bt=e((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),xt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:$.optional(),certificates:Ye,saml:M({objectKey:j.string(),key:j.string(),clientId:j.string(),cert:j.unknown().optional(),issuer:j.string().optional(),lifetime:j.number().optional(),nameId:j.string().optional(),audience:j.string().optional(),nameIdentifierFormat:j.string().optional(),tokenEndpoint:j.string().optional()}).optional(),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),cacheTTL:j.number().int().nonnegative().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),inline:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),St=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=ne.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,o=a&&isJexlExpression(a),s=t?L({...t,args:i},e):{},c={...s,customErrors:t?.customErrors,response:o?{...s?.response??{},dataKey:a}:s?.response},{baseUrl:l,url:u,method:d,response:f,authorization:p,certificates:m,customErrors:h,encodeQueryParams:g,args:_,saml:v,cacheTTL:y}=xt.parse(c),b=s?.authentication?.[e.context.authenticationType]?.[e.context.environment],x=b?.authorization,S=m??b?.certificates,C=S?re(S):void 0,w=_?q(_):{query:{},body:{},headers:{}},T=_?.some(e=>e.in===`body`&&e.inline===!0)??!1,E=O(p)?p:$.parse(x),D=W(E),ee={...w?.headers??{},...D},k=e.connector?.rateLimit,A=e.connector?.concurrency,te=k!==void 0||A!==void 0?{rateLimits:k,concurrency:A}:void 0,j=O(v)?{[v.objectKey]:await generateSamlAssertion({key:v.key,clientId:v.clientId,cert:v.cert,issuer:v.issuer,lifetime:v.lifetime,audience:v.audience,nameId:v.nameId,nameIdentifierFormat:v.nameIdentifierFormat,tokenEndpoint:v.tokenEndpoint})}:{},M=typeof w?.body==`string`||Array.isArray(w?.body)?w?.body:{...w?.body,...j};if(E.type===`none`&&E.signing?.strategy){if(g===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=E.signing,n=e.credentials??{};try{let e=G(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:d,url:`${l}${u}`,headers:ee,query:w?.query??{},body:M},n,t);Object.assign(ee,r)}catch(t){return buildStepErrorOutput(t,e)}}let P;try{P=await n.performRequest({httpClient:e.httpClient,url:`${l}${u}`,queryParams:w?.query,encodeQueryParams:g,method:d,headers:ee,body:M,customErrorConfigs:h,requestConfig:te,httpsAgent:C,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:y})}catch(t){return T&&(isErrorWithResponseBody(t)&&(t.response.body=Q),isErrorWithResponseConfigData(t)&&(t.response.config.data=Q)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Ct(f?.dataKey?resolveDataKey(P.data,f.dataKey):P.data,f),raw:T&&P&&`body`in P?{...P,body:Q}:P,statusCode:P?.status,message:P?.message}}},resolveDataKey=(e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;let n=I(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Ct=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),wt=j.union([j.string(),j.number()]),Tt=M({algorithm:j.literal(`RS256`),privateKey:j.string(),claims:j.record(j.string(),wt)}),Et=M({token:j.string(),expiresIn:j.number(),publicKeyFingerprint:j.string()}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${ce(`sha256`).update(t).digest(`base64`)}`},Dt=/^now$/,Ot=/^now\+(?<amount>\d+)(?<unit>[smh])$/,kt=`{publicKeyFingerprint}`,At={s:1,m:60,h:3600},jt=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(kt)?t.split(kt).join(r):t;if(!jt.has(e))return i;if(Dt.test(i))return n;let a=i.match(Ot);return a?.groups?n+Number(a.groups.amount)*At[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?L(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Tt.parse(n),o=le(i),s=computePublicKeyFingerprint(ue(o)),c=Math.floor(Date.now()/1e3),l={};for(let[e,t]of Object.entries(a))l[e]=resolveClaimValue(e,t,{now:c,publicKeyFingerprint:s});let{iat:u,exp:d}=l;if(typeof u!=`number`||typeof d!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(d<=u)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let f=await new de(l).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:f,expiresIn:d-u,publicKeyFingerprint:s}}}catch(t){return buildStepErrorOutput(t,e)}},Mt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:j.discriminatedUnion(`type`,[M({type:j.literal(`none`)}),M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),M({type:j.literal(`oauth2`),token:j.string(),includeBearer:j.boolean().optional().default(!0)})]).optional(),envelope:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),namespaces:j.strictObject({namespaceIdentifier:j.string(),namespace:j.string()}).array().optional(),soapOperation:j.string().optional(),soapAction:j.string().optional(),useSoapContext:j.boolean().optional().default(!0),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional(),nextKeyIn:j.enum([`data`,`headers`]).optional()}).optional(),iterator:M({key:j.string(),in:j.enum([`query`,`body`])}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),Nt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=ne.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,o=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?L({...t,args:o},e):{},c={...s,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,s?.response)},l=t?.envelope,{baseUrl:u,url:d,method:f,response:p,iterator:m,cursor:h,authorization:g,customErrors:_,encodeQueryParams:v,args:y,soapOperation:b,namespaces:x,soapAction:S,useSoapContext:C}=Mt.parse(c),w=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,E=y?q(y):{query:{},body:{},headers:{}},D=W(O(g)?g:$.parse(w)),ee={...E?.headers??{},...D},k=e.connector?.rateLimit,A=e.connector?.concurrency,te={...k!==void 0||A!==void 0?{rateLimits:k,concurrency:A}:void 0,soapOperation:b,namespaces:x,soapAction:S,soapContext:C?{username:e.credentials?.username,password:e.credentials?.password}:void 0},j=h?.token??null,M=null,P=null,F=[],I=[],R=[],z=a,B=h?.position??0,V=!0,H;do{V?V=!1:B=0,j!==null&&(m.in===`query`?E.query[m.key]=j.toString():m.in===`body`&&(E.body[m.key]=j));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:{...E?.query},encodeQueryParams:v,method:f,headers:ee,body:E?.body,customErrorConfigs:_,requestConfig:{...te,...O(l)&&{envelope:evaluateEnvelope(l,e,j)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}M=j,I=p?.dataKey?gt(t.data,p.dataKey):t.data,Array.isArray(I)||(I=I?[I]:[]);let r=I?.slice(B,B+z);z-=r.length,B+=r.length,R.push(t),F=F.concat(r),P=t?.status,j=resolveNextIterator({result:t,response:p});let i=B>=(I?.length??0),o=O(p?.nextKey),s=r.length===I.length&&z===0;o&&i&&(B=0,M=j),H=o?i&&T(j):T(j)&&F.length<a||s}while(O(j)&&F.length<a&&I?.length>0);return{block:e,successful:!0,output:{data:Pt(F,p),raw:R,statusCode:P,next:H?void 0:stringifyCursorToken(M),position:H?void 0:B}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?I(e,r):L(e,r)},resolveNextIterator=({result:e,response:t})=>{if(T(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},Pt=e((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ft=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:$.optional(),envelope:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),namespaces:j.strictObject({namespaceIdentifier:j.string(),namespace:j.string()}).array().optional(),soapOperation:j.string().optional(),soapAction:j.string().optional(),useSoapContext:j.boolean().optional().default(!0),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),It=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=ne.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?L({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:c,method:l,response:u,authorization:d,customErrors:f,encodeQueryParams:p,args:m,soapOperation:h,namespaces:g,envelope:_,soapAction:v,useSoapContext:y}=Ft.parse(o),b=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=m?q(m):{query:{},body:{},headers:{}},S=W(O(d)?d:$.parse(b)),C={...x?.headers??{},...S},w=e.connector?.rateLimit,T=e.connector?.concurrency,E={...w!==void 0||T!==void 0?{rateLimits:w,concurrency:T}:void 0,soapOperation:h,namespaces:g,envelope:_,soapAction:v,soapContext:y?{username:e.credentials?.username,password:e.credentials?.password}:void 0},D;try{D=await n.performRequest({httpClient:e.httpClient,url:`${s}${c}`,queryParams:x?.query,encodeQueryParams:p,method:l,headers:C,body:x?.body,customErrorConfigs:f,requestConfig:E,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Lt(u?.dataKey?D.data[u?.dataKey]:D.data,u),raw:D,statusCode:D?.status,message:D?.message}}},Lt=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Rt=j.object({values:j.string().or(j.record(j.string(),j.unknown())).or(j.array(j.unknown()))}),zt=j.object({data:j.unknown()}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Rt.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>D(e)?I(e,t):E(e)?L(e,t):e,Bt=j.object({targetFieldKey:j.string(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),properties:j.lazy(()=>Bt).array().optional(),requiredScopes:j.string().array().optional()}),Vt=j.object({fields:Bt.array().optional(),dataSource:j.string()}),Ht=j.object({data:j.unknown()});let Ut=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if(T(e))return null;switch(t){case`string`:return te({value:e});case`number`:return A({value:e});case`boolean`:return ee({value:e});case`datetime_string`:return k({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values(Ut).includes(e),Wt=e(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>Gt(e,t)):Gt(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),Gt=e((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&O(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Vt.parse(t),i=N(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&O(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&O(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Kt=M({content:j.string().meta({description:`The file content as base64 encoded string`}),contentType:j.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),qt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).default(`post`),authorization:$.optional(),binaryContent:Kt.meta({description:`Raw binary content for octet-stream uploads`}),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),Jt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?L({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:o,url:s,method:c,response:l,authorization:u,binaryContent:d,args:f,customErrors:p}=qt.parse(a),m=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,h=f?q(f):{query:{},body:{},headers:{}},g=W(O(u)?u:$.parse(m)),_=Buffer.from(d.content,`base64`),v={"content-type":d.contentType??`application/octet-stream`,...h?.headers??{},...g},y=e.connector?.rateLimit,b=e.connector?.concurrency,x=y!==void 0||b!==void 0?{rateLimits:y,concurrency:b}:void 0,S;try{S=await e.httpClient.request({url:`${o??``}${s}`,method:c,headers:v,queryParams:h?.query,payload:_,requestConfig:x,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[J(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let C=Y(S,p,e.credentials);return K(C?.status)?{block:e,successful:!1,errors:[J(new B(C,C.message))],output:{statusCode:C.status,message:C.message}}:{block:e,successful:!0,output:{data:Yt(l?.dataKey?C.data[l?.dataKey]:C.data,l),raw:C,statusCode:C?.status,message:C?.message}}},Yt=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Xt=M({fieldName:j.string().meta({description:`The form field name for the file`}),content:j.string().meta({description:`The file content as base64 encoded string`}),filename:j.string().meta({description:`The filename to use in the upload`}),contentType:j.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),Zt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).default(`post`),authorization:$.optional(),file:Xt.meta({description:`The file to upload`}),additionalFields:M({name:j.string(),value:j.unknown(),condition:j.string().optional(),contentType:j.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),Qt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,o=t?L({...t,args:i,additionalFields:a},e):{},s={...o,customErrors:t?.customErrors},{baseUrl:c,url:l,method:u,response:d,authorization:f,file:p,additionalFields:m,args:h,customErrors:g}=Zt.parse(s),_=o?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?q(h):{query:{},body:{},headers:{}},y=W(O(f)?f:$.parse(_)),b=new fe;if(m)for(let e of m){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);b.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let x=Buffer.from(p.content,`base64`);b.append(p.fieldName,x,{filename:p.filename,contentType:p.contentType});let S={...b.getHeaders(),...v?.headers??{},...y},C=e.connector?.rateLimit,w=e.connector?.concurrency,T=C!==void 0||w!==void 0?{rateLimits:C,concurrency:w}:void 0,E;try{E=await e.httpClient.request({url:`${c??``}${l}`,method:u,headers:S,queryParams:v?.query,payload:b,requestConfig:T,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let D=Y(E,g,e.credentials);return K(D?.status)?buildStepErrorOutput(new B(D,D.message),e):{block:e,successful:!0,output:{data:indexResponseData(d?.dataKey?D.data[d?.dataKey]:D.data,d),raw:D,statusCode:D?.status,message:D?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let $t=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const en={typecast:{v1:{fn:Wt},v2:{fn:typecastStepFunction,inputSchema:Vt,outputSchema:Ht}},map_fields:{v1:{fn:it},v2:{fn:mapFieldsStepFunction,inputSchema:ct,outputSchema:lt}},request:{v1:{fn:requestStepFunction,inputSchema:xt,outputSchema:St}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:nt,outputSchema:rt}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:_t,outputSchema:vt}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:Ft,outputSchema:It}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:Mt,outputSchema:Nt}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Rt,outputSchema:zt}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:Zt,outputSchema:Qt}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:qt,outputSchema:Jt}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:Xe,outputSchema:Ze}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:Qe,outputSchema:$e}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:Le,outputSchema:Re}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:ze,outputSchema:Be}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Tt,outputSchema:Et}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:pt,outputSchema:mt}}},formatZodIssues=(e,t,n)=>e instanceof j.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},tn={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=en}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;export{$ as AUTHORIZATION_SCHEMA,we as ActionTypes,Ie as AuthType,Le as BROWSER_USE_INPUT_PARAMS,Re as BROWSER_USE_OUTPUT,ze as CODE_EXECUTION_LAMBDA_INPUT_PARAMS,Be as CODE_EXECUTION_LAMBDA_OUTPUT,ve as COMPOSITE_ID_LATEST_VERSION,Ce as ChangelogLabels,ye as CoreError,Xe as DOWNLOAD_FILE_INPUT_PARAMS,Ze as DOWNLOAD_FILE_OUTPUT,Qe as EMIT_EVENT_INPUT_PARAMS,$e as EMIT_EVENT_OUTPUT,Te as Effects,Ae as ExecutionModes,be as FORMAT_PATTERNS,nt as GROUP_DATA_INPUT_PARAMS,rt as GROUP_DATA_OUTPUT,xe as INPUT_ENUM_REGISTRY,Oe as InputFormats,De as InputLocations,ke as InputTypes,ct as MAP_FIELDS_INPUT_PARAMS,lt as MAP_FIELDS_OUTPUT,pt as MCP_REQUEST_INPUT_PARAMS,mt as MCP_REQUEST_OUTPUT,_t as PAGINATED_REQUEST_INPUT_PARAMS,vt as PAGINATED_REQUEST_OUTPUT,xt as REQUEST_INPUT_PARAMS,St as REQUEST_OUTPUT,Se as ReleaseStages,Tt as SIGN_JWT_INPUT_PARAMS,Et as SIGN_JWT_OUTPUT,Mt as SOAP_PAGINATED_REQUEST_INPUT_PARAMS,Nt as SOAP_PAGINATED_REQUEST_OUTPUT,Ft as SOAP_REQUEST_INPUT_PARAMS,It as SOAP_REQUEST_OUTPUT,Rt as STATIC_VALUES_INPUT_PARAMS,zt as STATIC_VALUES_OUTPUT,Ee as SchemaTypes,Ne as SourceType,$t as StepFunctionName,tn as StepFunctionsFactory,en as StepFunctionsRegistry,Fe as StreamType,Vt as TYPECAST_INPUT_PARAMS,Ht as TYPECAST_OUTPUT,Pe as TransportType,qt as UPLOAD_BINARY_INPUT_PARAMS,Jt as UPLOAD_BINARY_OUTPUT,Zt as UPLOAD_FILE_INPUT_PARAMS,Qt as UPLOAD_FILE_OUTPUT,areCursorsEqual,buildExpressionContext,computeDataSyncFingerprint,decodeCompositeId,encodeCompositeId,evaluateEventRouter,evaluateExternalAccountIdExtractor,expandCursor,getCategoryDetails,getInputEnumValues,getIteratorLocation,getPaginationKeys,isCompositeId,isCoreError,isCursorEmpty,isForeachStep,isValidCategory,isValidEnumRef,minifyCursor,stripIncrementalParams,stripPaginationParams,updateCursor};
3
+ -----END PRIVATE KEY-----`)},_t=e(e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},`isJexlExpression`),vt=e((e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;let n=I(_t(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},`resolveDataKey`),resolveFromHeaders=(e,t)=>{if(T(e)||typeof e!=`object`)return null;if(_t(t)){let n=I(t,e);return typeof n==`string`&&n!==``||typeof n==`number`?n:null}let n=t.toLowerCase(),[,r]=Object.entries(e).find(([e])=>e?.toLowerCase()===n)??[];if(Array.isArray(r)){let e=r.find(e=>typeof e==`string`&&e!==``||typeof e==`number`);return typeof e==`string`||typeof e==`number`?e:null}return typeof r==`string`&&r!==``||typeof r==`number`?r:null},resolveFromData=(e,t)=>{if(T(e)||typeof e!=`object`||!e)return null;let n=I(_t(t)?t:`$.${t}`,e);return T(n)?null:typeof n==`string`||typeof n==`number`||typeof n==`object`?n:null},preserveJexlResponseKeys=(e,t)=>{let{nextKey:n,dataKey:r}=e?.response??{},i=n&&_t(n),a=r&&_t(r);return!i&&!a?t:{...t??{},...i?{nextKey:n}:{},...a?{dataKey:r}:{}}},yt=j.object({baseUrl:j.string(),url:j.string(),method:j.enum(z),authorization:$.optional(),saml:M({objectKey:j.string(),key:j.string(),clientId:j.string(),cert:j.unknown().optional(),issuer:j.string().optional(),lifetime:j.number().optional(),nameId:j.string().optional(),audience:j.string().optional(),nameIdentifierFormat:j.string().optional(),tokenEndpoint:j.string().optional()}).optional(),response:M({indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional(),nextKeyIn:j.enum([`data`,`headers`]).optional()}).optional(),iterator:M({key:j.string(),in:j.enum([`query`,`body`]),condition:j.string().optional(),mode:j.enum([`cursor`,`offset`,`page`]).optional(),startPage:j.number().int().min(0).max(2**53-1).optional(),maxPage:j.number().int().positive().max(1e4).optional()}).superRefine((e,t)=>{e.startPage!==void 0&&e.mode!==`page`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`startPage`],message:`startPage is only valid when iterator.mode is "page"`}),e.maxPage!==void 0&&e.mode!==`page`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`maxPage`],message:`maxPage is only valid when iterator.mode is "page"`});let n=e.maxPage??1e3;e.mode===`page`&&(e.startPage??1)>n&&t.addIssue({code:j.ZodIssueCode.custom,path:[`startPage`],message:`startPage must not exceed maxPage (${n})`})}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),cacheTTL:j.number().int().nonnegative().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),bt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),paginatedRequestStepFunction=async({block:e,params:t})=>{let n=ne.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:i}=t,a=Number(e.inputs?.page_size),o=Number.isNaN(a)?25:a,s=i?i.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,c=t?L({...t,args:s},e):{},l={...c,customErrors:t?.customErrors,iterator:{...c?.iterator??{},condition:t?.iterator?.condition},response:preserveJexlResponseKeys(t,c?.response)},u=l.authorization;if(O(u)){let t=$.safeParse(u);if(!t.success)return buildStepErrorOutput(Error(invalidStepAuthorizationMessage(t.error)),e)}let{baseUrl:d,url:f,method:p,response:m,authorization:h,iterator:g,cursor:_,customErrors:v,encodeQueryParams:y,args:b,saml:x,cacheTTL:S}=yt.parse(l),C=c?.authentication?.[e.context.authenticationType]?.[e.context.environment],w=C?.authorization,D=C?.certificates,ee=D?re(D):void 0,k=O(h)?h:$.parse(w);if(k.type===`none`&&O(k.signing))return buildStepErrorOutput(Error(`authorization.signing is not supported on paginated_request steps — every page changes the query string, so the signature would have to be recomputed per page; use a request step instead`),e);let A=b?q(b):{query:{},body:{},headers:{}},te=W(k),j={...A?.headers??{},...te},M=e.connector?.rateLimit,P=e.connector?.concurrency,F=M!==void 0||P!==void 0?{rateLimits:M,concurrency:P}:void 0,R=buildRequestContext(e),z=O(x)?{[x.objectKey]:await generateSamlAssertion({key:x.key,clientId:x.clientId,cert:x.cert,issuer:x.issuer,lifetime:x.lifetime,audience:x.audience,nameId:x.nameId,nameIdentifierFormat:x.nameIdentifierFormat,tokenEndpoint:x.tokenEndpoint})}:{},B=g.mode===`offset`,V=g.mode===`page`,H=g.maxPage??1e3,U=H+1,G=V?resolveInitialPage(_?.token,g.startPage??1):_?.token??null,K=null,J=null,Y=[],X=[],ie=[],ae=o,Z=_?.position??0,oe=!0,se=!0,Q=!0,ce=null;do{if(V&&Number(G)>U)return buildStepErrorOutput(maxPageExceededError(H,G),e);oe?oe=!1:B||(Z=0),G===null?B&&(g.in===`query`?A.query[g.key]=Z.toString():g.in===`body`&&(Array.isArray(A.body)||(A.body[g.key]=Z))):g.in===`query`?E(G)?Object.entries(G).forEach(([e,t])=>{A.query[`${g.key}[${e}]`]=t?.toString()??``}):A.query[g.key]=G.toString():g.in===`body`&&(Array.isArray(A.body)||(A.body[g.key]=G));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${d}${f}`,queryParams:{...A?.query},encodeQueryParams:y,method:p,headers:{...j},body:Array.isArray(A?.body)?A.body:{...typeof A?.body==`string`?void 0:A?.body,...z},customErrorConfigs:v,requestConfig:F,httpsAgent:ee,credentials:e.credentials,context:R,cacheTTL:S})}catch(t){return buildStepErrorOutput(t,e)}if(K=G,X=m?.dataKey?vt(t.data,m.dataKey):t.data,!Array.isArray(X)){let n=V?` at page ${K}`:``,r=m?.dataKey?` at "${m.dataKey}"`:``,i=X===null?`null`:typeof X;e.logger?.warning({message:`Pagination stopped${n}: expected an array of records${r} but received ${i}; treating it as an empty page`}),ie.push(t),J=t?.status,se=!0;break}if(V){let t=r(X);if(t===ce){e.logger?.warning({message:`Pagination stopped at page ${K}: the provider returned the previous page again, so the page number is not advancing`}),se=!0;break}ce=t}if(V&&Number(K)>H&&X.length>0)return buildStepErrorOutput(maxPageExceededError(H,K),e);let i=B?X?.slice(0,ae):X?.slice(Z,Z+ae);ae-=i.length,Z+=i.length,ie.push(t),Y=Y.concat(i),J=t?.status,G=V?incrementPage(Number(K)):xt({result:t,response:m}),Q=O(g.condition)?I(g.condition,t.data)===!0:!0;let a=Z>=(X?.length??0),s=O(m?.nextKey),c=i.length===X.length&&ae===0;!B&&(s||V)&&a&&(Z=0,K=G),se=B?!Q||T(G)&&Y.length<o:V?a&&(!Q||Y.length<o):s?a&&(T(G)||!Q):!Q||T(G)&&Y.length<o||c}while((B||O(G))&&Q&&Y.length<o&&X?.length>0);let le=St(Y,m),ue=se?void 0:K;return{block:e,successful:!0,output:{data:le,raw:ie,statusCode:J,next:V&&typeof ue==`number`?ue.toString():ue,position:se?void 0:Z}}},resolveInitialPage=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)&&n>=t?n:t},incrementPage=e=>e+1,maxPageExceededError=(e,t)=>Error(`Pagination exceeded iterator.maxPage (${e}) at page ${t}`),invalidStepAuthorizationMessage=e=>`step authorization is invalid, check its credential expressions resolve for this account: ${e.issues.map(e=>e.message).join(`; `)}`,xt=e(({result:e,response:t})=>{if(T(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey;return n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r)},`resolveNextIterator`),St=e((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Ct=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:$.optional(),certificates:Ze,saml:M({objectKey:j.string(),key:j.string(),clientId:j.string(),cert:j.unknown().optional(),issuer:j.string().optional(),lifetime:j.number().optional(),nameId:j.string().optional(),audience:j.string().optional(),nameIdentifierFormat:j.string().optional(),tokenEndpoint:j.string().optional()}).optional(),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),cacheTTL:j.number().int().nonnegative().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),inline:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}).superRefine((e,t)=>{let n=e.args??[],r=n.map((e,t)=>({arg:e,index:t})).filter(({arg:e})=>e.inline===!0),i=n.filter(e=>e.in===`body`).length;if(n.forEach((e,n)=>{e.inline===!0&&e.in!==`body`&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline is only valid when in is "body", got "${e.in}"`}),e.inline===!0&&e.spread&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with spread`})}),r.length>0&&i>1)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: an inline body arg must be the only "in: body" arg, found ${i}; arg conditions are not considered`});if(r.length>0&&e.saml!==void 0)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with the saml parameter`});if(r.length>0&&e.cacheTTL!==void 0&&e.cacheTTL>0)for(let{arg:e,index:n}of r)t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`inline`],message:`args.${e.name}: inline cannot be combined with a nonzero cacheTTL`});for(let{arg:e,index:n}of r)typeof e.value==`string`?e.value.length===0&&t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got an empty string`}):t.addIssue({code:j.ZodIssueCode.custom,path:[`args`,n,`value`],message:`args.${e.name}: inline value must be a non-empty string, got ${typeof e.value}`})}),wt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),isJexlExpression=e=>{let t=e.trim();return t.startsWith(`{{`)&&t.endsWith(`}}`)},isErrorWithResponseBody=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`body`in e.response,isErrorWithResponseConfigData=e=>typeof e==`object`&&!!e&&`response`in e&&e.response!=null&&typeof e.response==`object`&&`config`in e.response&&e.response.config!=null&&typeof e.response.config==`object`&&`data`in e.response.config,requestStepFunction=async({block:e,params:t})=>{let n=ne.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?.response?.dataKey,o=a&&isJexlExpression(a),s=t?L({...t,args:i},e):{},c={...s,customErrors:t?.customErrors,response:o?{...s?.response??{},dataKey:a}:s?.response},{baseUrl:l,url:u,method:d,response:f,authorization:p,certificates:m,customErrors:h,encodeQueryParams:g,args:_,saml:v,cacheTTL:y}=Ct.parse(c),b=s?.authentication?.[e.context.authenticationType]?.[e.context.environment],x=b?.authorization,S=m??b?.certificates,C=S?re(S):void 0,w=_?q(_):{query:{},body:{},headers:{}},T=_?.some(e=>e.in===`body`&&e.inline===!0)??!1,E=O(p)?p:$.parse(x),D=W(E),ee={...w?.headers??{},...D},k=e.connector?.rateLimit,A=e.connector?.concurrency,te=k!==void 0||A!==void 0?{rateLimits:k,concurrency:A}:void 0,j=O(v)?{[v.objectKey]:await generateSamlAssertion({key:v.key,clientId:v.clientId,cert:v.cert,issuer:v.issuer,lifetime:v.lifetime,audience:v.audience,nameId:v.nameId,nameIdentifierFormat:v.nameIdentifierFormat,tokenEndpoint:v.tokenEndpoint})}:{},M=typeof w?.body==`string`||Array.isArray(w?.body)?w?.body:{...w?.body,...j};if(E.type===`none`&&E.signing?.strategy){if(g===!1)return buildStepErrorOutput(Error(`encodeQueryParams: false is not supported when a request signing strategy is configured — signed canonical would not match the wire query`),e);let t=E.signing,n=e.credentials??{};try{let e=G(t.strategy);if(!e)throw Error(`Signing strategy "${t.strategy}" is not registered`);let r=e({method:d,url:`${l}${u}`,headers:ee,query:w?.query??{},body:M},n,t);Object.assign(ee,r)}catch(t){return buildStepErrorOutput(t,e)}}let P;try{P=await n.performRequest({httpClient:e.httpClient,url:`${l}${u}`,queryParams:w?.query,encodeQueryParams:g,method:d,headers:ee,body:M,customErrorConfigs:h,requestConfig:te,httpsAgent:C,credentials:e.credentials,context:buildRequestContext(e),cacheTTL:y})}catch(t){return T&&(isErrorWithResponseBody(t)&&(t.response.body=Q),isErrorWithResponseConfigData(t)&&(t.response.config.data=Q)),buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:Tt(f?.dataKey?resolveDataKey(P.data,f.dataKey):P.data,f),raw:T&&P&&`body`in P?{...P,body:Q}:P,statusCode:P?.status,message:P?.message}}},resolveDataKey=(e,t)=>{if(T(e)||typeof e!=`object`||!e)return e;let n=I(isJexlExpression(t)?t:`$.${t}`,e);return n===void 0?e[t]:n},Tt=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Et=j.union([j.string(),j.number()]),Dt=M({algorithm:j.literal(`RS256`),privateKey:j.string(),claims:j.record(j.string(),Et)}),Ot=M({token:j.string(),expiresIn:j.number(),publicKeyFingerprint:j.string()}),computePublicKeyFingerprint=e=>{let t=e.export({format:`der`,type:`spki`});return`SHA256:${ce(`sha256`).update(t).digest(`base64`)}`},kt=/^now$/,At=/^now\+(?<amount>\d+)(?<unit>[smh])$/,jt=`{publicKeyFingerprint}`,Mt={s:1,m:60,h:3600},Nt=new Set([`iat`,`exp`,`nbf`]),resolveClaimValue=(e,t,{now:n,publicKeyFingerprint:r})=>{if(typeof t==`number`)return t;let i=t.includes(jt)?t.split(jt).join(r):t;if(!Nt.has(e))return i;if(kt.test(i))return n;let a=i.match(At);return a?.groups?n+Number(a.groups.amount)*Mt[a.groups.unit]:i},signJwtStepFunction=async({block:e,params:t})=>{try{let n=t?L(t,e):void 0,{algorithm:r,privateKey:i,claims:a}=Dt.parse(n),o=le(i),s=computePublicKeyFingerprint(ue(o)),c=Math.floor(Date.now()/1e3),l={};for(let[e,t]of Object.entries(a))l[e]=resolveClaimValue(e,t,{now:c,publicKeyFingerprint:s});let{iat:u,exp:d}=l;if(typeof u!=`number`||typeof d!=`number`)throw Error(`signJwt requires numeric 'iat' and 'exp' claims (use 'now' / 'now+<N>s|m|h' tokens, or pass numbers directly)`);if(d<=u)throw Error(`signJwt requires 'exp' to be greater than 'iat'`);let f=await new de(l).setProtectedHeader({alg:r}).sign(o);return{block:{...e},successful:!0,output:{token:f,expiresIn:d-u,publicKeyFingerprint:s}}}catch(t){return buildStepErrorOutput(t,e)}},Pt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:j.discriminatedUnion(`type`,[M({type:j.literal(`none`)}),M({type:j.literal(`basic`),username:j.string().optional(),password:j.string().optional(),encoding:j.string().optional()}),M({type:j.literal(`bearer`),token:j.string(),includeBearer:j.boolean().optional().default(!0)}),M({type:j.literal(`oauth2`),token:j.string(),includeBearer:j.boolean().optional().default(!0)})]).optional(),envelope:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),namespaces:j.strictObject({namespaceIdentifier:j.string(),namespace:j.string()}).array().optional(),soapOperation:j.string().optional(),soapAction:j.string().optional(),useSoapContext:j.boolean().optional().default(!0),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional(),nextKey:j.string().optional(),nextKeyIn:j.enum([`data`,`headers`]).optional()}).optional(),iterator:M({key:j.string(),in:j.enum([`query`,`body`])}),cursor:M({token:j.string().optional().nullable(),position:j.number().optional().nullable()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),Ft=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional(),next:j.string().optional().nullable(),position:j.number().optional()}).optional(),soapPaginatedRequestStepFunction=async({block:e,params:t})=>{let n=ne.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=Number(e.inputs?.page_size),a=Number.isNaN(i)?25:i,o=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,s=t?L({...t,args:o},e):{},c={...s,customErrors:t?.customErrors,response:preserveJexlResponseKeys(t,s?.response)},l=t?.envelope,{baseUrl:u,url:d,method:f,response:p,iterator:m,cursor:h,authorization:g,customErrors:_,encodeQueryParams:v,args:y,soapOperation:b,namespaces:x,soapAction:S,useSoapContext:C}=Pt.parse(c),w=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,E=y?q(y):{query:{},body:{},headers:{}},D=W(O(g)?g:$.parse(w)),ee={...E?.headers??{},...D},k=e.connector?.rateLimit,A=e.connector?.concurrency,te={...k!==void 0||A!==void 0?{rateLimits:k,concurrency:A}:void 0,soapOperation:b,namespaces:x,soapAction:S,soapContext:C?{username:e.credentials?.username,password:e.credentials?.password}:void 0},j=h?.token??null,M=null,P=null,F=[],I=[],R=[],z=a,B=h?.position??0,V=!0,H;do{V?V=!1:B=0,j!==null&&(m.in===`query`?E.query[m.key]=j.toString():m.in===`body`&&(E.body[m.key]=j));let t;try{t=await n.performRequest({httpClient:e.httpClient,url:`${u}${d}`,queryParams:{...E?.query},encodeQueryParams:v,method:f,headers:ee,body:E?.body,customErrorConfigs:_,requestConfig:{...te,...O(l)&&{envelope:evaluateEnvelope(l,e,j)}},credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}M=j,I=p?.dataKey?vt(t.data,p.dataKey):t.data,Array.isArray(I)||(I=I?[I]:[]);let r=I?.slice(B,B+z);z-=r.length,B+=r.length,R.push(t),F=F.concat(r),P=t?.status,j=resolveNextIterator({result:t,response:p});let i=B>=(I?.length??0),o=O(p?.nextKey),s=r.length===I.length&&z===0;o&&i&&(B=0,M=j),H=o?i&&T(j):T(j)&&F.length<a||s}while(O(j)&&F.length<a&&I?.length>0);return{block:e,successful:!0,output:{data:It(F,p),raw:R,statusCode:P,next:H?void 0:stringifyCursorToken(M),position:H?void 0:B}}},stringifyCursorToken=e=>e===null?null:String(e),evaluateEnvelope=(e,t,n)=>{let r={...t,pageIterator:n};return typeof e==`string`?I(e,r):L(e,r)},resolveNextIterator=({result:e,response:t})=>{if(T(t?.nextKey))return null;let n=t?.nextKeyIn??`data`,r=t?.nextKey,i=n===`headers`?resolveFromHeaders(e.headers,r):resolveFromData(e.data,r);return typeof i==`string`||typeof i==`number`?i:null},It=e((e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Lt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z),authorization:$.optional(),envelope:j.union([j.string(),j.record(j.string(),j.unknown())]).optional(),namespaces:j.strictObject({namespaceIdentifier:j.string(),namespace:j.string()}).array().optional(),soapOperation:j.string().optional(),soapAction:j.string().optional(),useSoapContext:j.boolean().optional().default(!0),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),encodeQueryParams:j.boolean().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional()}),Rt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),soapRequestStepFunction=async({block:e,params:t})=>{let n=ne.build(`soap`);if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?L({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:c,method:l,response:u,authorization:d,customErrors:f,encodeQueryParams:p,args:m,soapOperation:h,namespaces:g,envelope:_,soapAction:v,useSoapContext:y}=Lt.parse(o),b=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,x=m?q(m):{query:{},body:{},headers:{}},S=W(O(d)?d:$.parse(b)),C={...x?.headers??{},...S},w=e.connector?.rateLimit,T=e.connector?.concurrency,E={...w!==void 0||T!==void 0?{rateLimits:w,concurrency:T}:void 0,soapOperation:h,namespaces:g,envelope:_,soapAction:v,soapContext:y?{username:e.credentials?.username,password:e.credentials?.password}:void 0},D;try{D=await n.performRequest({httpClient:e.httpClient,url:`${s}${c}`,queryParams:x?.query,encodeQueryParams:p,method:l,headers:C,body:x?.body,customErrorConfigs:f,requestConfig:E,credentials:e.credentials,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}return{block:e,successful:!0,output:{data:zt(u?.dataKey?D.data[u?.dataKey]:D.data,u),raw:D,statusCode:D?.status,message:D?.message}}},zt=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Bt=j.object({values:j.string().or(j.record(j.string(),j.unknown())).or(j.array(j.unknown()))}),Vt=j.object({data:j.unknown()}),staticValuesStepFunction=async({block:e,params:t})=>{let{values:n}=Bt.parse(t),r=Array.isArray(n)?n.map(t=>evaluateValue(t,e)):evaluateValue(n,e);return{block:{...e},successful:!0,output:{data:r}}},evaluateValue=(e,t)=>D(e)?I(e,t):E(e)?L(e,t):e,Ht=j.object({targetFieldKey:j.string(),type:j.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:j.boolean().default(!1),custom:j.boolean().default(!1),hidden:j.boolean().default(!1),properties:j.lazy(()=>Ht).array().optional(),requiredScopes:j.string().array().optional()}),Ut=j.object({fields:Ht.array().optional(),dataSource:j.string()}),Wt=j.object({data:j.unknown()});let Gt=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const typecast=({value:e,type:t,format:n})=>{if(T(e))return null;switch(t){case`string`:return te({value:e});case`number`:return A({value:e});case`boolean`:return ee({value:e});case`datetime_string`:return k({value:e,format:n});default:return e}},isFieldSupportedType=e=>Object.values(Gt).includes(e),Kt=e(async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>qt(e,t)):qt(e.result,t),{block:{...e,result:n},successful:!0}},`typecastStepFunction`),qt=e((e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;isFieldSupportedType(i)&&(!t.custom&&O(n[r])?n[r]=typecast({value:e[r],type:i}):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},`mapSingleRecord`),typecastStepFunction=async({block:e,params:t})=>{let{fields:n,dataSource:r}=Ut.parse(t),i=N(r,buildExpressionContext(e));if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>mapSingleRecord(e,n)):mapSingleRecord(i,n),{block:{...e},successful:!0,output:{data:a}}},handleObjectField=(e,t)=>!e.properties||!t?t:Array.isArray(t)?t.map(t=>typeof t==`object`&&t?mapSingleRecord(t,e.properties):t):typeof t==`object`&&t?mapSingleRecord(t,e.properties):t,mapSingleRecord=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i,array:a}=t;i===`object`?!t.custom&&O(n[r])?n[r]=handleObjectField(t,e[r]):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=handleObjectField(t,e.unified_custom_fields?.[r])):isFieldSupportedType(i)&&(!t.custom&&O(n[r])?(!a||!Array.isArray(n[r]))&&(n[r]=typecast({value:e[r],type:i})):n.unified_custom_fields&&O(n.unified_custom_fields?.[r])&&(!a||!Array.isArray(n.unified_custom_fields[r]))&&(n.unified_custom_fields[r]=typecast({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Jt=M({content:j.string().meta({description:`The file content as base64 encoded string`}),contentType:j.string().optional().meta({description:`The MIME type for the binary content (defaults to application/octet-stream)`})}),Yt=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).default(`post`),authorization:$.optional(),binaryContent:Jt.meta({description:`Raw binary content for octet-stream uploads`}),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),Xt=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),uploadBinaryStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n}=t,r=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,i=t?L({...t,args:r},e):{},a={...i,customErrors:t?.customErrors},{baseUrl:o,url:s,method:c,response:l,authorization:u,binaryContent:d,args:f,customErrors:p}=Yt.parse(a),m=i?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,h=f?q(f):{query:{},body:{},headers:{}},g=W(O(u)?u:$.parse(m)),_=Buffer.from(d.content,`base64`),v={"content-type":d.contentType??`application/octet-stream`,...h?.headers??{},...g},y=e.connector?.rateLimit,b=e.connector?.concurrency,x=y!==void 0||b!==void 0?{rateLimits:y,concurrency:b}:void 0,S;try{S=await e.httpClient.request({url:`${o??``}${s}`,method:c,headers:v,queryParams:h?.query,payload:_,requestConfig:x,context:buildRequestContext(e)})}catch(t){let n=t;return{block:e,successful:!1,errors:[J(t)],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let C=Y(S,p,e.credentials);return K(C?.status)?{block:e,successful:!1,errors:[J(new B(C,C.message))],output:{statusCode:C.status,message:C.message}}:{block:e,successful:!0,output:{data:Zt(l?.dataKey?C.data[l?.dataKey]:C.data,l),raw:C,statusCode:C?.status,message:C?.message}}},Zt=e((e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},`indexResponseData`),Qt=M({fieldName:j.string().meta({description:`The form field name for the file`}),content:j.string().meta({description:`The file content as base64 encoded string`}),filename:j.string().meta({description:`The filename to use in the upload`}),contentType:j.string().optional().meta({description:`The MIME type of the file (e.g., "image/png", "application/pdf")`})}),$t=j.object({baseUrl:j.string().optional(),url:j.string(),method:j.enum(z).default(`post`),authorization:$.optional(),file:Qt.meta({description:`The file to upload`}),additionalFields:M({name:j.string(),value:j.unknown(),condition:j.string().optional(),contentType:j.string().optional().meta({description:`The MIME type for this form field (e.g., "application/json")`})}).array().optional().meta({description:`Additional form fields to include in the multipart request`}),response:M({collection:j.boolean().optional(),indexField:j.string().optional(),dataKey:j.string().optional()}).optional(),customErrors:R.array().optional(),args:M({name:j.string(),value:j.unknown(),in:j.enum(U),spread:j.boolean().optional(),condition:j.string().optional(),arrayFormat:j.enum(H).optional()}).array().optional().meta({description:`Additional request parameters (query params, headers)`})}),en=M({data:j.unknown().optional(),raw:j.unknown().optional(),statusCode:j.number(),message:j.string().optional()}).optional(),uploadFileStepFunction=async({block:e,params:t})=>{if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:n,additionalFields:r}=t,i=n?n.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=r?r.filter(t=>!t.condition||N(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,o=t?L({...t,args:i,additionalFields:a},e):{},s={...o,customErrors:t?.customErrors},{baseUrl:c,url:l,method:u,response:d,authorization:f,file:p,additionalFields:m,args:h,customErrors:g}=$t.parse(s),_=o?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,v=h?q(h):{query:{},body:{},headers:{}},y=W(O(f)?f:$.parse(_)),b=new fe;if(m)for(let e of m){let t=typeof e.value==`object`?JSON.stringify(e.value):String(e.value);b.append(e.name,t,e.contentType?{contentType:e.contentType}:void 0)}let x=Buffer.from(p.content,`base64`);b.append(p.fieldName,x,{filename:p.filename,contentType:p.contentType});let S={...b.getHeaders(),...v?.headers??{},...y},C=e.connector?.rateLimit,w=e.connector?.concurrency,T=C!==void 0||w!==void 0?{rateLimits:C,concurrency:w}:void 0,E;try{E=await e.httpClient.request({url:`${c??``}${l}`,method:u,headers:S,queryParams:v?.query,payload:b,requestConfig:T,context:buildRequestContext(e)})}catch(t){return buildStepErrorOutput(t,e)}let D=Y(E,g,e.credentials);return K(D?.status)?buildStepErrorOutput(new B(D,D.message),e):{block:e,successful:!0,output:{data:indexResponseData(d?.dataKey?D.data[d?.dataKey]:D.data,d),raw:D,statusCode:D?.status,message:D?.message}}},indexResponseData=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e};let tn=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e.SOAP_REQUEST=`soap_request`,e.SOAP_PAGINATED_REQUEST=`soap_paginated_request`,e.STATIC_VALUES=`static_values`,e.UPLOAD_FILE=`upload_file`,e.UPLOAD_BINARY=`upload_binary`,e.DOWNLOAD_FILE=`download_file`,e.EMIT_EVENT=`emit_event`,e.BROWSER_USE=`browser_use`,e.CODE_EXECUTION_LAMBDA=`code_execution_lambda`,e.SIGN_JWT=`sign_jwt`,e.MCP_REQUEST=`mcp_request`,e}({});const nn={typecast:{v1:{fn:Kt},v2:{fn:typecastStepFunction,inputSchema:Ut,outputSchema:Wt}},map_fields:{v1:{fn:ot},v2:{fn:mapFieldsStepFunction,inputSchema:ut,outputSchema:dt}},request:{v1:{fn:requestStepFunction,inputSchema:Ct,outputSchema:wt}},group_data:{v1:{fn:groupDataStepFunction,inputSchema:it,outputSchema:at}},paginated_request:{v1:{fn:paginatedRequestStepFunction,inputSchema:yt,outputSchema:bt}},soap_request:{v1:{fn:soapRequestStepFunction,inputSchema:Lt,outputSchema:Rt}},soap_paginated_request:{v1:{fn:soapPaginatedRequestStepFunction,inputSchema:Pt,outputSchema:Ft}},static_values:{v1:{fn:staticValuesStepFunction,inputSchema:Bt,outputSchema:Vt}},upload_file:{v1:{fn:uploadFileStepFunction,inputSchema:$t,outputSchema:en}},upload_binary:{v1:{fn:uploadBinaryStepFunction,inputSchema:Yt,outputSchema:Xt}},download_file:{v1:{fn:downloadFileStepFunction,inputSchema:Qe,outputSchema:$e}},emit_event:{v1:{fn:emitEventStepFunction,inputSchema:et,outputSchema:tt}},browser_use:{v1:{fn:browserUseStepFunction,inputSchema:ze,outputSchema:Be}},code_execution_lambda:{v1:{fn:codeExecutionLambdaStepFunction,inputSchema:Ve,outputSchema:He}},sign_jwt:{v1:{fn:signJwtStepFunction,inputSchema:Dt,outputSchema:Ot}},mcp_request:{v1:{fn:mcpRequestStepFunction,inputSchema:ht,outputSchema:gt}}},formatZodIssues=(e,t,n)=>e instanceof j.ZodError?e.issues.map(e=>({...e,kind:t,functionName:n})):[{kind:t,functionName:n,message:e?.message??`unknown error`}],stepFunctionEnhancedWithSchemasValidation=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`input_schema_validation`,t)}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch(e){return{block:n,successful:!1,errors:formatZodIssues(e,`output_schema_validation`,t)}}return i},rn={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=nn}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:stepFunctionEnhancedWithSchemasValidation(i,e)}:i}},isForeachStep=e=>`iterator`in e&&typeof e.iterator==`string`;export{$ as AUTHORIZATION_SCHEMA,Ee as ActionTypes,Re as AuthType,xe as BARE_JEXL_REQUIREMENT,ze as BROWSER_USE_INPUT_PARAMS,Be as BROWSER_USE_OUTPUT,Ve as CODE_EXECUTION_LAMBDA_INPUT_PARAMS,He as CODE_EXECUTION_LAMBDA_OUTPUT,ve as COMPOSITE_ID_LATEST_VERSION,Te as ChangelogLabels,ye as CoreError,Qe as DOWNLOAD_FILE_INPUT_PARAMS,$e as DOWNLOAD_FILE_OUTPUT,et as EMIT_EVENT_INPUT_PARAMS,tt as EMIT_EVENT_OUTPUT,De as Effects,Me as ExecutionModes,Se as FORMAT_PATTERNS,it as GROUP_DATA_INPUT_PARAMS,at as GROUP_DATA_OUTPUT,Ce as INPUT_ENUM_REGISTRY,Ae as InputFormats,ke as InputLocations,je as InputTypes,ut as MAP_FIELDS_INPUT_PARAMS,dt as MAP_FIELDS_OUTPUT,ht as MCP_REQUEST_INPUT_PARAMS,gt as MCP_REQUEST_OUTPUT,yt as PAGINATED_REQUEST_INPUT_PARAMS,bt as PAGINATED_REQUEST_OUTPUT,Ct as REQUEST_INPUT_PARAMS,wt as REQUEST_OUTPUT,we as ReleaseStages,Dt as SIGN_JWT_INPUT_PARAMS,Ot as SIGN_JWT_OUTPUT,Pt as SOAP_PAGINATED_REQUEST_INPUT_PARAMS,Ft as SOAP_PAGINATED_REQUEST_OUTPUT,Lt as SOAP_REQUEST_INPUT_PARAMS,Rt as SOAP_REQUEST_OUTPUT,Bt as STATIC_VALUES_INPUT_PARAMS,Vt as STATIC_VALUES_OUTPUT,Oe as SchemaTypes,Fe as SourceType,tn as StepFunctionName,rn as StepFunctionsFactory,nn as StepFunctionsRegistry,Le as StreamType,Ut as TYPECAST_INPUT_PARAMS,Wt as TYPECAST_OUTPUT,Ie as TransportType,Yt as UPLOAD_BINARY_INPUT_PARAMS,Xt as UPLOAD_BINARY_OUTPUT,$t as UPLOAD_FILE_INPUT_PARAMS,en as UPLOAD_FILE_OUTPUT,areCursorsEqual,buildExpressionContext,computeDataSyncFingerprint,decodeCompositeId,encodeCompositeId,evaluateEventRouter,evaluateExternalAccountIdExtractor,expandCursor,getCategoryDetails,getInputEnumValues,getIteratorLocation,getPaginationKeys,isBareJexl,isCompositeId,isCoreError,isCursorEmpty,isForeachStep,isValidCategory,isValidEnumRef,minifyCursor,stripIncrementalParams,stripPaginationParams,updateCursor};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/core",
3
- "version": "3.33.0",
3
+ "version": "4.1.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",