@stackone/connect-sdk 3.17.0 → 3.18.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 +2 -2
- package/dist/index.d.cts +44 -17
- package/dist/index.d.mts +44 -17
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});let t=require("@stackone/utils"),n=require("path-to-regexp"),r=require("fs"),i=require("path"),a=require("@stackone/transport"),o=require("yaml"),s=require("@stackone/core"),c=require("@stackone/expressions"),l=require("@stackone/policy"),u=require("@stackone/defender"),d=require("@stackone/redaction"),f=require("@stackone/olap");const createBlock=async({connector:e,inputs:n,context:r,user:i,action:a,credentials:o,nextCursor:s,settings:c,logger:l,getHttpClient:u,getOlapClient:d,emitEvent:f})=>{if((0,t.isMissing)(u))throw Error(`getHttpClient function is required`);return{connector:e,inputs:n,fieldConfigs:[],context:r,user:i,action:a,credentials:o,nextCursor:s,httpClient:await u(),olapClient:d?await d():void 0,settings:c,logger:l,emitEvent:f}},getActionFromUrl=(e,n,r)=>{let i=r.toUpperCase();if(!e.actions)return;let a=testMatcher(n,i,Object.values(e.actions).filter(e=>(0,t.notMissing)(e.endpoint)).map(e=>({actionId:e.id,endpoint:e.endpoint})));if(a)return{action:e.actions?.[a.actionId],params:a.params}},removeLeadingAndTrailingSlashes=e=>{let t=e.startsWith(`/`)?e.slice(1):e;return t.endsWith(`/`)?t.slice(0,-1):t},testMatcher=(e,t,r)=>{let i=removeLeadingAndTrailingSlashes(e);for(let e of r)if(e.endpoint?.startsWith(t)){let r=(0,n.match)(removeLeadingAndTrailingSlashes(e.endpoint.replace(`${t} `,``).trim().replace(/\{([^}]+)\}/g,`:$1`)))(removeLeadingAndTrailingSlashes(i));if(r!==!1)return{actionId:e.actionId,path:e.endpoint,params:r.params}}},buildActionId=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,resolveActionId=(e,t)=>{let n=`${e}_`;return t.startsWith(n)?t:`${n}${t}`},findActionByActionId=(e,t)=>e.actions?.[resolveActionId(e.key,t)],findEventActionByActionId=(e,t)=>e.events?.actions?.[resolveActionId(e.key,t)],isActionAvailableForAuthType=(e,n)=>(0,t.isMissing)(e.authRequirements)||n in e.authRequirements,filterActionsByAuthType=(e,n)=>{if((0,t.isMissing)(n)||(0,t.isMissing)(e.actions))return e;let r={};for(let[t,i]of Object.entries(e.actions))isActionAvailableForAuthType(i,n)&&(r[t]=i);return{...e,actions:r}},p=Object.freeze([`AI`,`ATS`,`CMS`,`CRM`,`ERP`,`GRC`,`HRIS`,`IAM`,`IT`,`ITSM`,`LMS`,`MCP`,`SEO`,`VMS`]),m=[/client.?id/i,/client.?secret/i,/app.?secret/i],h=/(?:credentials|config|setup)\.([A-Za-z0-9_-]+)/g,computeCredentialsVerifiedByAuth=e=>{let t=!!(e.type===`oauth2`&&e.authorization?.authorizationUrl&&e.authorization?.tokenUrl),n=!!(e.type===`mcp`&&e.authorizationFlow),r=!!e.refreshAuthentication?.action;if(!(t||n||r))return!1;let i=[...e.setupFields??[],...e.configFields??[]].filter(e=>e.required===!0).map(e=>e.key);if((t||n)&&(i=i.filter(e=>!m.some(t=>t.test(e)))),i.length===0)return!0;let a=JSON.stringify([e.authorization,e.refreshAuthentication]),o=new Set;for(let e of a.matchAll(h))o.add(e[1]);return i.every(e=>o.has(e))},loadConnector=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=(0,r.readFileSync)(e,`utf8`);return!t.includes(`:`)||!t.includes(`$ref:`)?t:processYamlObject(t.split(`
|
|
2
2
|
`),(0,i.dirname)(e)).join(`
|
|
3
3
|
`)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},processYamlObject=(e,t)=>{let n=[];for(let r of e)if(isPartialReference(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=loadPartialFile(i,t).map(t=>` `.repeat(e)+t);n.push(...a)}else n.push(r);return n},isPartialReference=e=>e.includes(`$ref:`),loadPartialFile=(e,t)=>{let n=(0,i.resolve)((0,i.join)(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{return(0,r.readFileSync)(n,`utf8`).split(`
|
|
4
|
-
`).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},hasDelimiter=e=>e.includes(`{{`)||e.includes(`}}`),responseKeySchema=e=>t.z.string().refine(e=>(0,c.isExpression)(e)?(0,c.isValidExpression)(e):!hasDelimiter(e),{message:`Expression does not compile`}).meta({description:e}),g=(0,t.zStrictObject)({type:t.z.literal(`cursor`).meta({description:`Selects the cursor-based pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`}),nextKey:responseKeySchema("Response key for the next-page cursor: a dot-path into the action result, or a `{{ }}` expression evaluated against the result with response headers at `$.headers` (lowercased).")}).meta({description:`How records and the next-page cursor are located in the response.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter the next-page cursor is sent in.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."})}).meta({description:`Request parameter that carries the next-page cursor.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the resolved next-page cursor is `null`."})}),_=(0,t.zStrictObject)({type:t.z.literal(`offset`).meta({description:`Selects the offset-based pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`})}).meta({description:`How each page of records is located in the response.`}),iterator:(0,t.zStrictObject)({offsetKey:t.z.string().meta({description:`Request parameter set to the offset of the first record on each page.`}),limitKey:t.z.string().meta({description:`Request parameter set to the number of records requested per page.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."}),startOffset:t.z.number().int().min(0).optional().meta({description:"Offset sent on the first page. Defaults to `0`. Set to `1` for APIs that count records from 1 rather than 0, such as SCIM's `startIndex`."}),defaultLimit:t.z.number().optional().meta({description:"Number of records requested per page. Defaults to `100` when omitted."})}).meta({description:`Request parameters that page through results by offset and limit.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the data key returns no records."})}),v=(0,t.zStrictObject)({type:t.z.literal(`page`).meta({description:`Selects the page-number pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`})}).meta({description:`How each page of records is located in the response.`}),iterator:(0,t.zStrictObject)({pageKey:t.z.string().meta({description:`Request parameter set to the page number for each request.`}),pageSizeKey:t.z.string().optional().meta({description:`Request parameter set to the number of records requested per page. Omit when the endpoint takes no page-size parameter.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."}),startPage:t.z.number().optional().meta({description:"Page number requested for the first page. Defaults to `1` when omitted."}),defaultPageSize:t.z.number().optional().meta({description:"Number of records requested per page. Defaults to `100` when omitted."})}).meta({description:`Request parameters that page through results by page number.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the data key returns no records."})}),y=t.z.discriminatedUnion(`type`,[g,_,v]),b=(0,t.zStrictObject)({type:t.z.literal(`delta_token`).meta({description:`Selects the delta-token strategy where each sync sends the token returned by the previous sync.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter name the delta token is sent under.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the delta token: `query`, `body`, or `headers`."})}).meta({description:`Names the request parameter carrying the previous delta token and where on the request to place it.`}),response:(0,t.zStrictObject)({path:responseKeySchema("Response key for the delta token used on the next sync: a dot-path into the action result, or a `{{ }}` expression evaluated against the result with response headers at `$.headers` (lowercased)."),onlyOnFinalPage:t.z.boolean().optional().meta({description:"When `true`, read the delta token only from the final page of results."})}).meta({description:`Configures reading the next delta token from the response.`})}),x=(0,t.zStrictObject)({type:t.z.literal(`time_filter`).meta({description:`Selects the updated-since strategy where each sync requests only records changed after the last watermark.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter name the last-sync timestamp is sent under.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the timestamp parameter: `query`, `body`, or `headers`."})}).meta({description:`Names the request parameter carrying the last-sync timestamp and where on the request to place it.`}),format:t.z.enum([`iso8601`,`unix_seconds`,`unix_millis`]).meta({description:"Encoding of the timestamp value: `iso8601`, `unix_seconds`, or `unix_millis`."}),safetyBufferSeconds:t.z.number().int().nonnegative().default(60).meta({description:`Seconds subtracted from the run start time when falling back to the local clock so records near the boundary are not skipped.`}),response:(0,t.zStrictObject)({updatedAtPath:t.z.string().meta({description:`Path within each returned record to its last-updated timestamp, read to advance the watermark.`})}).optional().meta({description:`Configures reading the newest record timestamp from each page to advance the watermark.`})}),S=t.z.discriminatedUnion(`type`,[x,b]),hasCatastrophicBacktrackingRisk=e=>{let t=[],n=!1,r=/\{(\d+)(?:(,)(\d*))?\}/y,quantifierAt=t=>{let n=e[t];if(n===`*`||n===`+`)return{length:1,variable:!0,amplifying:!0};if(n===`?`)return{length:1,variable:!0,amplifying:!1};if(n===`{`){r.lastIndex=t;let n=r.exec(e);if(n){let e=Number(n[1]),t=n[2]===void 0?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let r=0;r<e.length;r++){let i=e[r];if(i===`\\`){r++;continue}if(n){i===`]`&&(n=!1);continue}if(i===`[`){n=!0;continue}if(i===`|`){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if(i===`(`){if(t.push({hasVariable:!1,hasAlternation:!1}),e[r+1]===`?`){let t=e[r+2]===`<`&&(e[r+3]===`=`||e[r+3]===`!`);r+=t?2:1}continue}if(i===`)`){let e=t.pop(),n=quantifierAt(r+1);if(n){if(n.amplifying&&(e?.hasVariable||e?.hasAlternation))return!0;r+=n.length}t.length>0&&((n?.variable||e?.hasVariable)&&(t[t.length-1].hasVariable=!0),e?.hasAlternation&&(t[t.length-1].hasAlternation=!0));continue}let a=quantifierAt(r);a&&(a.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),r+=a.length-1)}return!1},compilesAsRegex=e=>{try{return new RegExp(e),!0}catch{return!1}},C=Object.keys(s.FORMAT_PATTERNS),w=Object.keys(s.INPUT_ENUM_REGISTRY),compileFieldValidationRegex=e=>e.pattern===void 0?e.format?s.FORMAT_PATTERNS[e.format]:void 0:new RegExp(e.pattern),T=(0,t.zStrictObject)({pattern:t.z.string().optional().meta({description:"Regular expression the entered value must match. Provide this or `format`, not both."}),format:t.z.enum(C).optional().meta({description:"Named format the entered value must match, standing in for a common regular expression. Provide this or `pattern`, not both."}),errorMessage:t.z.string().min(1,`errorMessage cannot be empty when set`).optional().meta({description:`Message shown when the value fails the pattern or format check.`})}).check(e=>{let t=e.value;if(t.pattern!==void 0==(t.format!==void 0)){e.issues.push({code:`custom`,input:t,path:[],message:`validation: must declare exactly one of pattern or format — pattern subsumes format, so encode compound constraints as a single pattern`});return}if(t.pattern!==void 0){if(t.pattern.length===0){e.issues.push({code:`custom`,input:t,path:[`pattern`],message:`pattern cannot be empty when set`});return}if(!compilesAsRegex(t.pattern)){e.issues.push({code:`custom`,input:t,path:[`pattern`],message:`Invalid regex pattern`});return}hasCatastrophicBacktrackingRisk(t.pattern)&&e.issues.push({code:`custom`,input:t,path:[`pattern`],message:"Pattern risks catastrophic backtracking (variable-width quantifier or alternation nested inside a repeated group, e.g. `(a+)+`, `(a{2,4})+` or `(a|a)+`). It runs on every keystroke in the browser — rewrite without nesting, typically by flattening the repeated group into a single character class with a lookahead guarding label boundaries (e.g. `^([a-z0-9-]+\\.)+[a-z]{2,}$` becomes `^(?!\\.|.*\\.\\.)[a-z0-9.-]+\\.[a-z]{2,}$`)."})}}),E={key:t.z.string().meta({description:`Identifier the credential value is stored and referenced under.`}),label:t.z.string().meta({description:`Human-readable name shown for this field.`}),required:t.z.boolean().optional().default(!1).meta({description:`Whether the field must have a value.`}),secret:t.z.boolean().optional().default(!1).meta({description:`Encrypt the value at rest and mask it in the UI.`}),externalSystemAccountIdentifier:t.z.boolean().optional().meta({description:`Value identifies the account in the external system, used to match incoming webhook events to a linked account.`}),readOnly:t.z.boolean().optional().default(!1).meta({description:`Whether the field is displayed but cannot be edited by the user.`}),placeholder:t.z.string().optional().meta({description:`Example value shown in the empty input to hint the expected format.`}),description:t.z.string().optional().meta({description:`Helper text explaining what the user should enter.`}),tooltip:t.z.string().optional().meta({description:`Additional guidance shown on hover for this field.`}),value:t.z.string().optional().meta({description:`Preset or computed value for the field, such as a fixed default or a JEXL expression.`}),computed:t.z.boolean().optional().meta({description:"Field value is a JEXL expression in `value`, evaluated at runtime rather than entered by the user."})},collectComputedValueIssues=e=>e.computed===!0&&!e.value?[{path:[`value`],message:`A computed field must have a value (JEXL expression)`}]:[],collectValidationSupportIssues=e=>e.computed===!0?[{path:[`validation`],message:`validation: is not supported on computed fields — the value is a server-evaluated expression the customer never types`}]:e.readOnly===!0?[{path:[`validation`],message:`validation: is not supported on readOnly fields — the customer never edits the value, so there is nothing for client-side validation to check`}]:[],collectValidationExampleIssues=e=>{let t=compileFieldValidationRegex(e.validation);if(!t)return[];let n=[];return e.placeholder!==void 0&&!t.test(e.placeholder)&&n.push({path:[`validation`],message:`placeholder "${e.placeholder}" does not satisfy the field's own validation — fix the pattern/format or the placeholder`}),e.value!==void 0&&!t.test(e.value)&&n.push({path:[`validation`],message:`default value "${e.value}" does not satisfy the field's own validation — fix the pattern/format or the value`}),n},D=t.z.discriminatedUnion(`type`,[(0,t.zStrictObject)({...E,type:t.z.enum([`text`,`password`,`text_area`]).meta({description:`Input control rendered for this credential field.`}),validation:T.optional().meta({description:`Client-side validation constraint applied to the entered value.`})}),(0,t.zStrictObject)({...E,type:t.z.literal(`select`).meta({description:`Input control rendered for this credential field.`}),options:(0,t.zStrictObject)({value:t.z.string().meta({description:`Value stored when this option is selected.`}),label:t.z.string().meta({description:`Human-readable text shown for this option.`})}).array().meta({description:`Selectable choices offered for this field.`})})]).check(e=>{let t=e.value,n=`validation`in t?t.validation:void 0,r=n?collectValidationSupportIssues(t):[],i=[...collectComputedValueIssues(t),...r,...n&&r.length===0?collectValidationExampleIssues({...t,validation:n}):[]];for(let n of i)e.issues.push({code:`custom`,input:t,message:n.message,path:n.path})}),O=(0,t.zStrictObject)({targetFieldKey:t.z.string().meta({description:`Key of the field in the mapped output this configuration produces.`}),alias:t.z.string().optional().meta({description:`Alternate key name for this field when it forms part of a composite identifier.`}),expression:t.z.string().optional().meta({description:`Expression evaluated to derive the field value.`}),values:t.z.unknown().optional().meta({description:`Inline object or array used in place of the source record when mapping an object field's nested properties.`}),type:t.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:`Data type of the field's value, used by the typecast step function to convert it and by the map_fields step function to decide how to map it.`}),array:t.z.boolean().default(!1).meta({description:`Whether the field holds a list of values.`}),custom:t.z.boolean().default(!1).meta({description:`Whether the field is a provider-specific custom field rather than a unified one.`}),hidden:t.z.boolean().default(!1).meta({description:`Currently not in use.`}),enumMapper:(0,t.zStrictObject)({matcher:t.z.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or((0,t.zStrictObject)({matchExpression:t.z.string().meta({description:`JEXL expression checked against the record. The rule applies when it evaluates to true.`}),value:t.z.string().meta({description:`Value emitted when the expression matches.`})}).array()).meta({description:`Built-in country or format matcher name, or a list of custom match rules, used to translate provider enum values.`})}).optional().meta({description:`Mapping used to translate provider enum values to StackOne values.`}),properties:t.z.lazy(()=>O).array().optional().meta({description:`Nested field configurations for object or array fields.`}),requiredScopes:t.z.string().optional().meta({description:`Scopes this field depends on, validated at build time against the connector's scope definitions.`})}),k=t.z.union([(0,t.zStrictObject)({values:t.z.string().array().min(1).meta({description:`Explicit list of allowed enum values.`})}),(0,t.zStrictObject)({ref:t.z.string().meta({description:`Name of a shared enum definition supplying the allowed values. One of: ${w.map(e=>`\`${e}\``).join(`, `)}.`})})]),A=(0,t.zStrictObject)({minLength:t.z.number().optional().meta({description:`Minimum number of characters the value must have.`}),maxLength:t.z.number().optional().meta({description:`Maximum number of characters the value may have.`}),pattern:t.z.string().refine(e=>compilesAsRegex(e),{message:`Invalid regex pattern`}).optional().meta({description:`Regular expression the value must match.`}),format:t.z.enum(C).optional().meta({description:`Named format the value must conform to.`}),min:t.z.number().optional().meta({description:`Minimum numeric value allowed.`}),max:t.z.number().optional().meta({description:`Maximum numeric value allowed.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the value violates a rule.`})}),j=(0,t.zStrictObject)({field:t.z.string().meta({description:`Name of the other input this condition inspects.`}),equals:t.z.string().optional().meta({description:`Condition holds when the referenced field equals this value.`}),notEquals:t.z.string().optional().meta({description:`Condition holds when the referenced field does not equal this value.`}),present:t.z.boolean().optional().meta({description:`When true, the condition holds if the referenced field is present. When false, it holds if the field is absent.`})}).refine(e=>[e.equals!==void 0,e.notEquals!==void 0,e.present!==void 0].filter(Boolean).length===1,{message:`Condition must specify exactly one of: equals, notEquals, present`}),M=t.z.discriminatedUnion(`rule`,[(0,t.zStrictObject)({rule:t.z.literal(`atLeastOneOf`).meta({description:`Requires at least one of the listed inputs to be provided.`}),fields:t.z.string().array().min(2).meta({description:`Input names of which at least one must be provided.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})}),(0,t.zStrictObject)({rule:t.z.literal(`requiredIf`).meta({description:`Requires an input when another field satisfies a condition.`}),field:t.z.string().meta({description:`Input that becomes required when the condition holds.`}),condition:j.meta({description:`Condition under which the field is required.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})}),(0,t.zStrictObject)({rule:t.z.literal(`mutuallyExclusive`).meta({description:`Allows at most one of the listed inputs to be provided.`}),fields:t.z.string().array().min(2).meta({description:`Input names of which at most one may be provided.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})})]),N=t.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`]),P=t.z.lazy(()=>(0,t.zStrictObject)({type:N.meta({description:`Data type of this input variant.`}),description:t.z.string().optional().meta({description:`Explains what this variant represents.`}),array:t.z.boolean().optional().default(!1).meta({description:`Whether this variant holds a list of values.`}),properties:t.z.lazy(()=>F.omit({in:!0})).array().optional().meta({description:`Nested inputs when this variant is an object.`}),oneOf:k.optional().meta({description:`Allowed values when this variant is an enum.`}),rules:A.optional().meta({description:`Validation rules applied to this variant.`})}).check(e=>{let t=e.value;t.type===`enum`&&!t.oneOf&&e.issues.push({code:`custom`,message:`Variant with type 'enum' must declare oneOf`,input:t,path:[]})})),F=(0,t.zStrictObject)({name:t.z.string().meta({description:`Parameter name exposed to callers and mapped into the request.`}),type:N.optional().meta({description:`Data type of the input value.`}),required:t.z.boolean().meta({description:`Whether the caller must supply this input.`}),description:t.z.string().meta({description:`Explains the input for callers and generated tool schemas.`}),array:t.z.boolean().optional().default(!1).meta({description:`Whether the input accepts a list of values.`}),arrayFormat:t.z.enum([`repeat`,`brackets`,`comma`,`stringify`]).optional().meta({description:`How a list input's values are formatted in the request, such as repeated, comma-separated, or bracketed. Currently not in use.`}),in:t.z.enum([`body`,`query`,`path`,`headers`]).meta({description:`Part of the HTTP request this input is placed in.`}),properties:t.z.lazy(()=>F.omit({in:!0})).array().optional().meta({description:"Nested inputs when the input is an object. Each has the same shape as a top-level input, minus `in`."}),oneOf:k.optional().meta({description:`Allowed values when the input is an enum.`}),rules:A.optional().meta({description:`Validation rules applied to the input value.`}),variants:t.z.lazy(()=>P).array().min(2).optional().meta({description:"An input that accepts more than one type. Provide at least two variants, each defining one of those types the way an input does. The input itself sets no top-level `type`, `array`, `properties`, `oneOf`, or `rules`."})}).refine(e=>e.type!==`enum`||e.oneOf!==void 0,{message:`oneOf is required when type is 'enum'`}).refine(e=>e.type===`enum`||e.oneOf===void 0,{message:`oneOf is only allowed when type is 'enum'`}).refine(e=>e.rules&&(e.rules.minLength!==void 0||e.rules.maxLength!==void 0||e.rules.pattern!==void 0||e.rules.format!==void 0)?e.type===`string`||e.type===`datetime_string`:!0,{message:`String rules (minLength, maxLength, pattern, format) can only be used with string or datetime_string types`}).refine(e=>e.rules&&(e.rules.min!==void 0||e.rules.max!==void 0)?e.type===`number`:!0,{message:`Number rules (min, max) can only be used with number type`}).check(e=>{let t=e.value;t.variants?(t.type&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'type' must be absent`,input:t,path:[]}),t.array&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'array' must be absent`,input:t,path:[]}),t.properties&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'properties' must be absent`,input:t,path:[]}),t.oneOf&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'oneOf' must be absent`,input:t,path:[]}),t.rules&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'rules' must be absent — define rules inside each variant instead`,input:t,path:[]})):t.type||e.issues.push({code:`custom`,message:`'type' is required when 'variants' is absent`,input:t,path:[]})}),ee=t.z.object({exampleDescription:t.z.string().optional().meta({description:`Explains what this usage example demonstrates.`})}).catchall(t.z.unknown()),I=(0,t.zStrictObject)({functionName:t.z.string().meta({description:`Name of the step function to execute.`}),version:t.z.string().optional().meta({description:`Version of the step function to use.`}),parameters:t.z.record(t.z.string(),t.z.unknown()).meta({description:`Arguments passed to the step function.`})}),L=t.z.union([t.z.boolean(),t.z.literal(`break`)]).optional(),R=(0,t.zStrictObject)({stepId:t.z.string().meta({description:`Identifier for this step, used to reference its output.`}),description:t.z.string().meta({description:`Explains what this step does.`}),stepFunction:I.meta({description:`Step function executed by this step.`}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether this step runs.`}),onConditionError:L.meta({description:"How to behave when the condition expression errors: `false` (default) skips the step, `true` runs it anyway, and `break` halts the action."}),ignoreError:t.z.boolean().optional().meta({description:`Whether a failure in this step is ignored so execution continues.`})}),z=(0,t.zStrictObject)({stepId:t.z.string().meta({description:`Identifier for this step, used to reference its output.`}),description:t.z.string().meta({description:`Explains what this step does.`}),iterator:t.z.string().meta({description:"Expression that produces the array this step loops over. The step function(s) run once per item until the array is exhausted, halting early if an item fails and `ignoreError` is not set."}),stepFunction:I.optional().meta({description:"Step function run for each iterated item. Provide this or `stepFunctions`, not both."}),stepFunctions:I.array().optional().meta({description:"Step functions run in sequence for each iterated item. Provide this or `stepFunction`, not both."}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether this step runs.`}),onConditionError:L.meta({description:"How to behave when the condition expression errors: `false` (default) skips the step, `true` runs it anyway, and `break` halts the action."}),ignoreError:t.z.boolean().optional().meta({description:`Whether a failure in this step is ignored so execution continues.`})}).refine(e=>e.stepFunction!==void 0&&e.stepFunctions===void 0||e.stepFunction===void 0&&e.stepFunctions!==void 0,{message:`Exactly one of 'stepFunction' or 'stepFunctions' must be provided, not both`}),B=(0,t.zStrictObject)({allowed:t.z.boolean().meta({description:`Whether Data Sync is enabled for this action.`}),indexField:t.z.string().or(t.z.string().array()).meta({description:`Field or fields forming each record's primary key during sync. Must uniquely identify each record; a value shared across records collapses them and a record missing it is dropped.`}),dataKey:t.z.string().optional().meta({description:`Path within the step output to the records array, used when the action returns them in a single call rather than paginating.`}),pagination:y.optional().meta({description:`Pagination strategy used while syncing.`}),incremental:S.optional().meta({description:`Change-tracking configuration for incremental syncs.`}),maxPages:t.z.number().int().positive().optional().meta({description:`Maximum number of pages fetched in a single sync run.`}),maxDurationMinutes:t.z.number().int().positive().optional().meta({description:`Maximum time a single sync run may take.`})}),bareJexlMessage=e=>`${e} ${s.BARE_JEXL_REQUIREMENT}`,V=(0,t.zStrictObject)({when:t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`when`)}).meta({description:`JEXL expression evaluated against the incoming request. This rule is selected when the expression returns anything other than null, false, or undefined.`}),then:(0,t.zStrictObject)({action:t.z.string().meta({description:`Event action id invoked when the rule matches.`}),input:t.z.record(t.z.string(),t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`input`)})).optional().meta({description:`JEXL expressions evaluated against the incoming request whose results become the invoked action's input.`})}).meta({description:`Action to invoke when the rule matches.`})}),H=(0,t.zStrictObject)({delivery:V.array().optional().meta({description:"Rules matched against the whole delivery payload, rather than the individual events `itemsPath` splits it into. The first match short-circuits, so the per-event `rules` are skipped."}),itemsPath:t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`itemsPath`)}).optional().meta({description:"JEXL expression that splits a batched delivery payload into individual events, so each is routed on its own through `rules`. When omitted, the whole payload is treated as a single event."}),rules:V.array().meta({description:"Rules matched in order against each individual event, where the first match maps it to an event action. Skipped when a `delivery` rule matches."})}),U=(0,t.zStrictObject)({actionId:t.z.string().meta({description:`Identifier for the action, prefixed with the connector key to form its MCP tool name.`,impact:[`mcp`,`runtime`]}),categories:t.z.string().array().meta({description:`Business-domain classifications used for filtering the action.`,impact:[`ui`]}),actionType:t.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`event`,`unknown`]).meta({description:`Operation kind the engine treats this action as.`,impact:[`mcp`,`runtime`]}),effects:t.z.array(t.z.enum([`read`,`write`,`delete`,`search`,`execute`])).optional().meta({description:`Semantic effects the action performs, used for MCP annotations and dashboard filtering.`,impact:[`ui`,`mcp`]}),annotations:(0,t.zStrictObject)({title:t.z.string().optional().meta({description:`Human-readable title exposed to MCP clients.`}),readOnlyHint:t.z.boolean().optional().meta({description:`Whether the action only reads data.`}),destructiveHint:t.z.boolean().optional().meta({description:`Whether the action may delete or overwrite data.`}),idempotentHint:t.z.boolean().optional().meta({description:`Whether repeating the action has no additional effect.`}),openWorldHint:t.z.boolean().optional().meta({description:`Whether the action interacts with an open, external world.`})}).optional().meta({description:"Explicit MCP tool-annotation overrides. Any field set here wins over the hint derived from `effects`."}),executionMode:t.z.enum(s.ExecutionModes).optional().meta({description:"Whether the action runs synchronously or is dispatched to an async workflow. An action with a `browser_use` step must be `async`.",impact:[`runtime`]}),schema:t.z.string().optional().meta({description:`Name of the output schema the action conforms to.`,impact:[`mcp`,`runtime`]}),schemaType:t.z.enum([`native`,`unified`]).optional().default(`native`).meta({description:`Whether the output follows the native provider shape or the unified StackOne schema.`,impact:[`mcp`,`runtime`]}),entrypointUrl:t.z.string().optional().meta({description:"URL path of the action's primary request. Paired with `entrypointHttpMethod` to form the action key such as `GET /employees`, and used as the request log URL.",impact:[`runtime`]}),entrypointHttpMethod:t.z.string().optional().meta({description:`HTTP method of the primary request.`,impact:[`runtime`]}),label:t.z.string().meta({description:`Human-readable display name for the action.`,impact:[`ui`]}),description:t.z.string().meta({description:`Short description shown in the UI and MCP tool declarations.`,impact:[`ui`,`mcp`]}),details:t.z.string().optional().meta({description:"Extended context about the action for agents and developers. Used as the MCP tool description in place of `description` when set.",impact:[`mcp`]}),examples:ee.array().optional().meta({description:"Example input values for the action, each optionally labeled with `exampleDescription`."}),tags:t.z.string().array().optional().meta({description:`Free-form tags for grouping and filtering the action.`,impact:[`ui`,`mcp`]}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Maturity level of the action.`,impact:[`ui`,`mcp`]}),resources:t.z.string().optional().meta({description:`URL to provider documentation for this action.`,impact:[`ui`]}),responses:(0,t.zStrictObject)({statusCode:t.z.number().meta({description:`HTTP status code being documented.`}),description:t.z.string().meta({description:`What this response status means.`})}).array().optional().meta({description:`Documented HTTP responses the action can return.`}),requiredScopes:t.z.string().optional().meta({description:"Permission scopes required to run the action. Deprecated; use `authRequirements`."}),authRequirements:t.z.record(t.z.string(),t.z.string().array()).optional().meta({description:"Per-authentication-method scopes required to run the action. Supersedes the deprecated `requiredScopes`."}),inputs:F.array().optional().meta({description:`Parameters the action accepts, forming its tool input schema.`}),validationRules:M.array().optional().meta({description:`Cross-field validation rules applied to the action inputs.`}),cursor:(0,t.zStrictObject)({enabled:t.z.boolean().meta({description:`Whether cursor pagination is enabled. Only applies to list actions and has no effect on others.`}),pageSize:t.z.number().meta({description:`Number of records requested per page.`})}).optional().meta({description:`Engine-managed cursor pagination configuration.`}),compositeIdentifiers:(0,t.zStrictObject)({enabled:t.z.boolean().meta({description:`Whether composite identifiers are built for records.`}),version:t.z.number().optional().meta({description:`Version of the composite identifier encoding.`}),fields:(0,t.zStrictObject)({targetFieldKey:t.z.string().meta({description:`Key the composite identifier is written to.`}),remote:t.z.string().optional().meta({description:`Provider field the identifier component is read from.`}),components:t.z.string().array().meta({description:`Ordered output field keys whose values combine into the identifier.`})}).array().optional().meta({description:`Field mappings that make up each composite identifier.`})}).optional().meta({description:`Configuration for building a record id from multiple provider fields.`}),fieldConfigs:O.array().optional().meta({description:`Field-level mapping and typing configuration for the result.`}),steps:t.z.union([R,z]).array().meta({description:`Ordered steps executed to carry out the action. A single step runs one step function, and an iterator step runs step functions over each item of an array.`}),result:t.z.string().or(t.z.record(t.z.string(),t.z.unknown())).optional().meta({description:`Data returned to the caller, given as an expression or a map of output keys to expressions.`}),dataSync:B.optional().meta({description:`Data Sync configuration for bulk syncing this action's records.`}),providerEvents:t.z.string().array().nonempty().optional().meta({description:`Provider event names this action handles.`,impact:[`runtime`]}),prerequisiteActions:t.z.string().array().optional().meta({description:`Action ids this action declares as dependencies.`}),userScoped:t.z.boolean().optional().meta({description:"The action answers for the acting user, filtering the provider by `$.user`. The engine refuses the call when there is no acting user email.",impact:[`runtime`]})}),stepUsesBrowserUse=e=>`stepFunction`in e&&e.stepFunction?.functionName===s.StepFunctionName.BROWSER_USE?!0:`stepFunctions`in e&&e.stepFunctions?e.stepFunctions.some(e=>e.functionName===s.StepFunctionName.BROWSER_USE):!1,W=U.superRefine((e,n)=>{e.executionMode!==`async`&&e.steps.some(stepUsesBrowserUse)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`Actions containing a 'browser_use' step must declare executionMode: 'async' so they are dispatched to the Temporal workflow runtime`,path:[`executionMode`]})}).superRefine((e,n)=>{e.userScoped!==!0||e.dataSync?.allowed!==!0||n.addIssue({code:t.z.ZodIssueCode.custom,message:`A userScoped action cannot allow dataSync: a sync has no acting user to scope it by`,path:[`dataSync`,`allowed`]})}).superRefine((e,n)=>{let r=e.prerequisiteActions;if(!r)return;r.includes(e.actionId)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`prerequisiteActions contains a self-reference to '${e.actionId}'`,path:[`prerequisiteActions`]});let i=new Set;for(let e of r)i.has(e)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`prerequisiteActions contains duplicate entry '${e}'`,path:[`prerequisiteActions`]}),i.add(e)}),te=(0,t.zStrictObject)({schedule:t.z.string().optional().meta({description:`Cron expression for proactively refreshing credentials.`}),action:U.extend({actionType:t.z.literal(`refresh_token`).meta({description:"Operation kind for this action, always `refresh_token`."})}).meta({description:`Action executed to refresh the credentials.`})}),ne=(0,t.zStrictObject)({mainRatelimit:t.z.number().meta({description:`Maximum requests per second for each linked account, across all of the connector's endpoints.`}),subPools:t.z.array((0,t.zStrictObject)({subPoolKey:t.z.string().meta({description:`Identifier for this rate-limit sub-pool.`}),urlPattern:t.z.string().meta({description:`URL pattern the sub-pool's limit applies to.`}),rateLimit:t.z.number().meta({description:`Maximum requests per second for the matched URLs.`})})).optional().meta({description:`Per-URL-pattern rate limit overrides.`}),mappedRateLimitErrors:t.z.array((0,t.zStrictObject)({errorStatus:t.z.number().meta({description:`HTTP status code indicating a rate-limit error.`}),errorMessage:t.z.string().meta({description:`Provider error message identifying a rate-limit error.`}),errorMessagePath:t.z.string().optional().meta({description:`Path to the error message in the response body.`}),retryAfterPath:t.z.string().optional().meta({description:`Path to the retry-after value within the response headers, not the body.`}),retryAfterUnit:t.z.union([t.z.literal(`seconds`),t.z.literal(`milliseconds`),t.z.literal(`date`)]).optional().meta({description:`Unit the retry-after value is expressed in.`}),retryAfterValue:t.z.number().optional().meta({description:`Fixed delay to wait before retrying.`})})).optional().meta({description:`Provider responses that should be treated as rate-limit signals.`})}),re=(0,t.zStrictObject)({mainMaxConcurrency:t.z.number().meta({description:`Maximum number of concurrent in-flight requests per linked account.`}),subPools:t.z.array((0,t.zStrictObject)({subPoolKey:t.z.string().meta({description:`Identifier for this concurrency sub-pool.`}),urlPattern:t.z.string().meta({description:`URL pattern the sub-pool's limit applies to.`}),maxConcurrency:t.z.number().meta({description:`Maximum concurrent requests for the matched URLs.`})})).optional().meta({description:`Per-URL-pattern concurrency overrides.`})}),ie=(0,t.zStrictObject)({src:t.z.string().meta({description:`Image URL or a path relative to the connector.`}),alt:t.z.string().meta({description:`Alternative text describing the image.`})}),ae=(0,t.zStrictObject)({title:t.z.string().meta({description:`Heading for this guide step.`}),content:t.z.string().meta({description:`Body text describing what the user should do.`}),list:t.z.string().array().optional().meta({description:`Ordered items elaborating the step.`}),image:ie.optional().meta({description:`Illustrative image for the step.`}),displayScopes:t.z.boolean().optional().meta({description:`Whether the step shows badges for the actions its scopes unlock.`}),applicableScopes:t.z.string().optional().meta({description:`Scope names for which this step is shown. Space-separated, with any name that contains spaces wrapped in double quotes.`})}),oe=(0,t.zStrictObject)({title:t.z.string().meta({description:`Heading for this guide section.`}),content:t.z.string().meta({description:`Introductory text for the section.`}),list:t.z.string().array().optional().meta({description:`Ordered items elaborating the section.`}),image:ie.optional().meta({description:`Illustrative image for the section.`}),steps:ae.array().optional().meta({description:`Ordered steps making up the section.`}),applicableScopes:t.z.string().optional().meta({description:`Scope names for which this section is shown. Space-separated, with any name that contains spaces wrapped in double quotes.`})}),G=(0,t.zStrictObject)({warning:t.z.string().optional().meta({description:`Cautionary note shown at the top of the guide.`}),sections:oe.array().meta({description:`Ordered sections making up the guide.`})}),se=(0,t.zStrictObject)({config:G.optional().meta({description:`Guide for the credentials end-users enter per connection.`}),setup:G.optional().meta({description:`Guide for the credentials your team registers once.`})}),ce=(0,t.zStrictObject)({key:t.z.string().meta({description:`Identifier for the notice.`}),type:t.z.enum([`warning`,`info`]).default(`info`).meta({description:`Visual style of the notice.`}),description:t.z.string().meta({description:`Text shown in the notice.`}),position:t.z.enum([`top`,`bottom`]).default(`top`).meta({description:`Whether the notice appears above or below the fields.`}),anchor:t.z.string().optional().meta({description:`Field key the notice is shown above. Only valid when position is top.`})}).refine(e=>!(e.anchor&&e.position===`bottom`),{message:`anchor cannot be used with position: 'bottom'`,path:[`anchor`]}),le=(0,t.zStrictObject)({certs:t.z.string().array().optional().meta({description:`Client certificates used for mutual-TLS.`}),keys:t.z.string().array().optional().meta({description:`Private keys used for mutual-TLS.`})}).optional(),K=(0,t.zStrictObject)({label:t.z.string().meta({description:`Display name for this authentication method.`,impact:[`ui`]}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Maturity level of this authentication method. Defaults to the highest stage among the actions and events it can run.`,impact:[`ui`]}),authorization:s.AUTHORIZATION_SCHEMA.meta({description:`Runtime authorization strategy applied to outgoing requests.`}),certificates:le.meta({description:`Mutual-TLS certificates and keys for this method.`}),requiredScopes:t.z.string().optional().meta({description:`Scope names required by this authentication method. Space-separated, with any name that contains spaces wrapped in double quotes.`}),environments:(0,t.zStrictObject)({key:t.z.string().meta({description:`Identifier stored for the selected environment.`}),name:t.z.string().meta({description:`Human-readable environment name.`})}).array().meta({description:`Deployment targets selectable for this method.`}),support:(0,t.zStrictObject)({link:t.z.string().optional().meta({description:`URL to external setup documentation. Defaults to the generated connector guide on docs.stackone.com when omitted.`}),description:t.z.string().optional().meta({description:`Help text guiding the user through connecting.`}),guides:se.optional().meta({description:`Step-by-step connection guides.`})}).optional().meta({description:`Help resources shown while connecting with this method.`}),configFields:D.array().optional().meta({description:`Credentials the end-user enters when linking an account.`}),configNotices:ce.array().optional().meta({description:`Callouts shown while entering config fields.`}),setupFields:D.array().optional().meta({description:`Credentials entered when creating a Connector Profile.`}),setupNotices:ce.array().optional().meta({description:`Callouts shown while entering setup fields.`}),refreshAuthentication:te.optional().meta({description:`Configuration for refreshing expired credentials.`}),testActions:(0,t.zStrictObject)({action:t.z.string().or(W).meta({description:`Action id or definition executed to test the connection.`}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether the test action runs.`}),required:t.z.boolean().default(!0).meta({description:`Currently not in use.`})}).array().optional().meta({description:`Actions run to validate a connection after authentication.`})}),ue=K.extend({type:t.z.literal(`oauth2`).meta({description:`Selects the OAuth 2.0 authentication method.`}),grantType:t.z.enum([`authorization_code`,`client_credentials`]).default(`authorization_code`).meta({description:`OAuth grant flow used to obtain tokens.`})}),de=K.extend({type:t.z.literal(`custom`).meta({description:`Selects the custom authentication method.`})}),fe=K.extend({type:t.z.literal(`oidc`).meta({description:`Selects the OpenID Connect authentication method.`})}),pe=(0,t.zStrictObject)({serverUrl:t.z.string().optional().meta({description:`MCP server URL the connect flow authorizes against.`}),discovery:t.z.boolean().default(!0).meta({description:`Whether OAuth authorization-server metadata is discovered automatically.`}),clientRegistration:t.z.enum([`cimd`,`dcr`]).default(`cimd`).meta({description:`Client registration mechanism used with the MCP server.`}),scopes:t.z.string().array().optional().meta({description:`OAuth scopes requested during the MCP authorization flow.`})}),me=K.extend({type:t.z.literal(`mcp`).meta({description:`Selects the remote MCP server authentication method.`}),authorizationFlow:pe.optional().meta({description:`MCP OAuth authorization flow; static credentials are used when omitted.`})}),he=t.z.discriminatedUnion(`type`,[ue,de,fe,me]),collectAuthenticationKeyIssues=e=>{let t=new Set,n=[];for(let[r,i]of e.entries()){let e=Object.keys(i);e.length!==1&&n.push({message:`Each authentication configuration must use exactly one key, but this one has ${e.length}.`,path:[r]});for(let i of e)t.has(i)?n.push({message:`Duplicate authentication key '${i}'. Each authentication configuration must use a unique key.`,path:[r,i]}):t.add(i)}return n},ge=t.z.record(t.z.string(),he).array().check(e=>{for(let t of collectAuthenticationKeyIssues(e.value))e.issues.push({code:`custom`,input:e.value,message:t.message,path:t.path})}),q=(0,t.zStrictObject)({steps:t.z.union([R,z]).array().min(1).meta({description:`Ordered steps performed in this webhook phase.`}),result:t.z.string().optional().meta({description:`Value produced by the phase, such as the created webhook id.`})}),_e=q.extend({result:t.z.string().meta({description:"Expression selecting the value this phase produces, such as the created receiver's remote id (e.g. `$.steps.create.output.data.id`), which later phases reference as `${inputs.remoteId}`."})}),phaseContainsTemplate=(e,t)=>{let containsTemplate=e=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.some(containsTemplate):typeof e==`object`&&e?Object.values(e).some(containsTemplate):!1;return e.steps.some(e=>`stepFunction`in e&&e.stepFunction?containsTemplate(e.stepFunction.parameters):`stepFunctions`in e&&e.stepFunctions?e.stepFunctions.some(e=>containsTemplate(e.parameters)):!1)},ve=(0,t.zStrictObject)({creation:_e.meta({description:`Phase that registers the webhook receiver.`}),activation:q.optional().meta({description:"Optional phase that activates the receiver after creation. Must reference `${inputs.remoteId}` in at least one step parameter."}),deletion:q.meta({description:"Phase that removes the webhook receiver. Must reference `${inputs.remoteId}` in at least one step parameter."}),isConsolidated:t.z.boolean().optional().default(!1).meta({description:`Whether one receiver handles all events rather than one per event.`})}).superRefine((e,n)=>{e.activation&&!phaseContainsTemplate(e.activation,"${inputs.remoteId}")&&n.addIssue({code:t.z.ZodIssueCode.custom,message:"Activation phase must reference '${inputs.remoteId}' in at least one step parameter",path:[`activation`]}),phaseContainsTemplate(e.deletion,"${inputs.remoteId}")||n.addIssue({code:t.z.ZodIssueCode.custom,message:"Deletion phase must reference '${inputs.remoteId}' in at least one step parameter",path:[`deletion`]})}),ye=(0,t.zStrictObject)({setup:G.optional().meta({description:`Guide for configuring webhooks in the provider UI.`})}),be=(0,t.zStrictObject)({setup:ve.optional().meta({description:`Programmatic webhook lifecycle configuration.`}),guides:ye.optional().meta({description:`Manual webhook setup guides.`}),actions:U.extend({actionType:t.z.literal(`event`).meta({description:`Marks the action as an event handler.`}),requiresManualSetup:t.z.boolean().optional().meta({description:"Whether the webhook must be configured manually in the provider UI. Pair with `guides.setup` to document that setup."})}).array().optional().meta({description:`Event actions that process incoming provider events.`}),router:H.optional().meta({description:`Rules mapping incoming payloads to event actions.`}),externalAccountIdExtractor:U.extend({actionType:t.z.literal(`custom`).meta({description:`Marks the extractor as a custom action.`}),result:t.z.string().min(1).meta({description:`Expression evaluated against the incoming payload to extract the provider's external account identifier.`})}).optional().meta({description:"Action that reads the provider's external account identifier from an incoming payload so the event can be matched to a linked account. It is a `custom` action with a required `result`."})}),J=2e3,xe=(0,t.zStrictObject)({StackOne:t.z.string().meta({description:"Connector schema version, set to `1.0.0`."}),info:(0,t.zStrictObject)({title:t.z.string().meta({description:`Human-readable provider name shown in Hub and Dashboard.`,impact:[`ui`]}),version:t.z.string().meta({description:`Connector version following semantic versioning.`,impact:[`ui`,`runtime`]}),key:t.z.string().meta({description:`Unique lowercase identifier for the connector.`,impact:[`ui`,`mcp`,`runtime`]}),assets:(0,t.zStrictObject)({icon:t.z.string().meta({description:`URL to the provider logo.`,impact:[`ui`]})}).meta({description:`Visual assets for the connector.`}),description:t.z.string().meta({description:`Brief one-line summary of the connector.`,impact:[`ui`,`mcp`]}),details:t.z.string().optional().meta({description:`Extended description of capabilities and limitations.`,impact:[`ui`,`mcp`]}),changelog:(0,t.zStrictObject)({summary:t.z.string().meta({description:`Human-readable summary of the changes in this version.`}),labels:t.z.string().array().optional().meta({description:`Tags categorizing the changelog entry for filtering.`})}).optional().meta({description:`Description of what changed in this version.`})}).meta({description:`Connector metadata.`}),resources:t.z.string().optional().meta({description:`Source of information for the connector, usually a URL to the provider's documentation.`}),documentation:(0,t.zStrictObject)({references:(0,t.zStrictObject)({title:t.z.string().meta({description:`Link text for the reference.`}),url:t.z.string().meta({description:`URL of the referenced document.`}),description:t.z.string().optional().meta({description:`Explains what the reference covers.`})}).array().meta({description:`External documentation links.`})}).optional().meta({description:`External documentation links for the connector.`}),baseUrl:t.z.string().meta({description:`Root URL for all API requests. Supports expressions.`,impact:[`runtime`]}),scopeDefinitions:t.z.record(t.z.string(),(0,t.zStrictObject)({description:t.z.string().meta({description:`Explains what this scope grants.`}),includes:t.z.string().optional().meta({description:`Another scope this scope implies.`})})).optional().meta({description:`Requirements actions can depend on, keyed by name, such as OAuth scopes, pricing tiers, or feature flags.`}),authentication:ge.optional().meta({description:`Authentication methods the connector supports.`}),actions:W.array().optional().meta({description:`Actions the connector exposes.`}),events:be.optional().meta({description:`Event and webhook configuration for the connector.`}),rateLimit:ne.optional().meta({description:`Request rate-limit configuration for the connector.`}),concurrency:re.optional().meta({description:`Request concurrency configuration for the connector.`}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Default maturity level inherited by actions, events and authentication methods that do not declare their own. The stage of the connector itself is computed from theirs, never authored here.`,impact:[`ui`]}),forkedFrom:t.z.string().optional().meta({description:`Key of the connector this one was forked from. Not currently in use.`}),mcp:(0,t.zStrictObject)({instructions:t.z.string().max(J).optional().meta({description:`Guidance text surfaced to MCP clients (max 2000 characters).`,impact:[`mcp`]})}).optional().meta({description:`MCP-specific configuration for the connector.`})}).strict().superRefine((e,n)=>{let r=e.actions;if(!r)return;let i=new Set(r.map(e=>e.actionId));for(let e=0;e<r.length;e++){let a=r[e];if(a.prerequisiteActions)for(let r of a.prerequisiteActions)i.has(r)||n.addIssue({code:t.z.ZodIssueCode.custom,message:`Action '${a.actionId}' has prerequisiteActions entry '${r}' which does not match any actionId in this connector`,path:[`actions`,e,`prerequisiteActions`]})}let a=new Map;for(let e of r)e.prerequisiteActions?.length&&a.set(e.actionId,e.prerequisiteActions);let o=new Map(r.map((e,t)=>[e.actionId,t])),s=new Set,c=new Set,dfs=(e,r)=>{for(let i of a.get(e)??[])if(r.includes(i)){let e=r.slice(r.indexOf(i));if(e.length<2)continue;let a=[...e].sort().join(`,`);c.has(a)||(c.add(a),n.addIssue({code:t.z.ZodIssueCode.custom,message:`Circular prerequisiteActions dependency: ${e.join(` → `)} → ${e[0]}`,path:[`actions`,o.get(e[0])??0,`prerequisiteActions`]}))}else s.has(i)||dfs(i,[...r,i]);s.add(e)};for(let e of r)s.has(e.actionId)||dfs(e.actionId,[e.actionId])});var Y=class InternalConnectSDKError extends Error{constructor(e,t){super(t),this.name=`InternalConnectSDKError`,this.errorType=e,Error.captureStackTrace&&Error.captureStackTrace(this,InternalConnectSDKError)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},InvalidYamlFileError=class extends Y{constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},SchemaValidationError=class extends Y{constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}};const formatStepLocation=e=>e.kind===`action`?`action '${e.actionId}'`:`webhook setup phase '${e.phase}'`;var InvalidStepFunctionError=class extends Y{constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the ${formatStepLocation(e)}.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.location=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},InvalidStepFunctionParamsError=class extends Y{constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the ${formatStepLocation(e)}.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.location=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}},InvalidActionExampleError=class extends Y{constructor(e,t,n){let r=`Invalid example ${t} for action '${e}': ${n.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`;super(`INVALID_ACTION_EXAMPLE`,r),this.name=`InvalidActionExampleError`,this.actionId=e,this.exampleIndex=t,this.issues=n}},InvalidEnumReferenceError=class extends Y{constructor(e,t,n){let r=`Invalid enum reference "${n}" in action "${e}", input "${t}". Check that the enum is defined in INPUT_ENUM_REGISTRY.`;super(`INVALID_ENUM_REFERENCE`,r),this.name=`InvalidEnumReferenceError`,this.actionId=e,this.inputName=t,this.enumRef=n}},InvalidEventRouterReferenceError=class extends Y{constructor(e,t,n){let r=`Event router ${n} ${t} references unknown event action "${e}". Check that the operation is defined in events.actions.`;super(`INVALID_EVENT_ROUTER_REFERENCE`,r),this.name=`InvalidEventRouterReferenceError`,this.operation=e,this.ruleIndex=t,this.ruleKind=n}},InvalidEventRouterActionPrefixError=class extends Y{constructor(e,t,n,r){let i=`Event router ${r} ${t} action "${e}" must start with the connector key prefix "${n}_".`;super(`INVALID_EVENT_ROUTER_ACTION_PREFIX`,i),this.name=`InvalidEventRouterActionPrefixError`,this.operation=e,this.ruleIndex=t,this.connectorKey=n,this.ruleKind=r}},UnknownCallActionTargetError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which is not defined in this connector.`;super(`UNKNOWN_CALL_ACTION_TARGET`,r),this.name=`UnknownCallActionTargetError`,this.location=e,this.stepId=t,this.targetActionId=n}},SelfReferencingActionError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} calls its own action "${n}". An action cannot call itself.`;super(`SELF_REFERENCING_ACTION`,r),this.name=`SelfReferencingActionError`,this.location=e,this.stepId=t,this.actionId=n}},CircularActionReferenceError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} closes a call_action cycle: ${n.join(` -> `)}. Actions cannot call each other in a loop.`;super(`CIRCULAR_ACTION_REFERENCE`,r),this.name=`CircularActionReferenceError`,this.location=e,this.stepId=t,this.chain=n}},IncompatibleCallActionAuthError=class extends Y{constructor(e,t,n,r,i){let a=r.join(`, `),o=i?`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which does not support the authentication ${i.length===1?`config`:`configs`} ${i.map(e=>`"${e}"`).join(`, `)} its caller declares. "${n}" supports: ${a}.`:`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which is restricted to the authentication configs ${a}, but its caller declares no authRequirements and so runs on all of them. Declare authRequirements on the caller that "${n}" supports.`;super(`INCOMPATIBLE_CALL_ACTION_AUTH`,o),this.name=`IncompatibleCallActionAuthError`,this.location=e,this.stepId=t,this.calleeActionId=n,this.calleeAuthKeys=r,this.callerAuthKeys=i}},MissingScopeDefinitionError=class extends Y{constructor(e){super(`MISSING_SCOPE_DEFINITION`,`Missing scope definition. Check that the scope is defined in the scope definitions.`),this.name=`MissingScopeDefinitionError`,this.issues=e}},InvalidAuthRequirementsError=class extends Y{constructor(e){super(`INVALID_AUTH_REQUIREMENTS`,`Invalid authRequirements. Verify auth config keys are valid and not used alongside requiredScopes.`),this.name=`InvalidAuthRequirementsError`,this.issues=e}};const callEdgesOf=(e,t)=>{let n=[];for(let[r,i]of Object.entries(e))for(let e of(0,s.stepFunctionsOf)(i)){if(e.functionName!==s.StepFunctionName.CALL_ACTION)continue;let i=e.params?.actionId;typeof i==`string`&&n.push({stepId:r,targetActionId:buildActionId(t,i),yamlTargetId:i})}return n},incompatibleAuthKeys=(e,n)=>{if((0,t.isMissing)(n.authRequirements))return;let r=new Set(Object.keys(n.authRequirements));if((0,t.isMissing)(e.authRequirements))return[];let i=Object.keys(e.authRequirements).filter(e=>!r.has(e));return i.length>0?i:void 0},findCycle=e=>{let t=new Map;for(let n of e.keys()){if(t.has(n))continue;let r=[n],i=[{actionId:n,nextEdge:0}];for(t.set(n,`onPath`);i.length>0;){let n=i[i.length-1],a=e.get(n.actionId)??[];if(n.nextEdge>=a.length){t.set(n.actionId,`settled`),i.pop(),r.pop();continue}let o=a[n.nextEdge];if(n.nextEdge+=1,!e.has(o.targetActionId))continue;let s=t.get(o.targetActionId);if(s===`onPath`){let e=r.indexOf(o.targetActionId);return{ownerActionId:n.actionId,stepId:o.stepId,chain:[...r.slice(e),o.targetActionId]}}s!==`settled`&&(t.set(o.targetActionId,`onPath`),r.push(o.targetActionId),i.push({actionId:o.targetActionId,nextEdge:0}))}}},validateCallActionGraph=({connectorKey:e,actions:t,yamlActionIds:n=new Map,callOnlySites:r=[]})=>{let displayId=e=>n.get(e)??e,i=new Map(Object.values(t).map(t=>[t.id,callEdgesOf(t.steps,e)])),a=r.map(t=>({location:t.location,edges:callEdgesOf(t.steps,e)}));if(!([...i.values()].some(e=>e.length>0)||a.some(({edges:e})=>e.length>0)))return;for(let e of Object.values(t)){let n={kind:`action`,actionId:displayId(e.id)};for(let r of i.get(e.id)??[]){if(!(r.targetActionId in t))throw new UnknownCallActionTargetError(n,r.stepId,r.yamlTargetId);if(r.targetActionId===e.id)throw new SelfReferencingActionError(n,r.stepId,displayId(e.id));let i=t[r.targetActionId],a=incompatibleAuthKeys(e,i);if(a)throw new IncompatibleCallActionAuthError(n,r.stepId,displayId(i.id),Object.keys(i.authRequirements??{}),a.length>0?a:void 0)}}for(let{location:e,edges:n}of a)for(let r of n)if(!(r.targetActionId in t))throw new UnknownCallActionTargetError(e,r.stepId,r.yamlTargetId);let o=findCycle(i);if(o)throw new CircularActionReferenceError({kind:`action`,actionId:displayId(o.ownerActionId)},o.stepId,o.chain.map(displayId))},isCustomOwner=e=>(0,t.notMissing)(e)&&e!==`stackone`,isCustomConnector=e=>isCustomOwner(e.owner),Se=[`ga`,`preview`,`beta`,`internal`,`deprecated`],Ce=`preview`,highestReleaseStage=e=>e.reduce((e,n)=>(0,t.isMissing)(e)||Se.indexOf(n)<Se.indexOf(e)?n:e,void 0),computeActionStages=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,n.releaseStage??t])),reachableStages=(e,t,n)=>Object.entries(t??{}).filter(([,t])=>isActionAvailableForAuthType(t,e)).map(([e])=>n[e]),authTypeReleaseStage=e=>Object.values(e).map(e=>e.releaseStage).find(t.notMissing),computeReleaseStages=e=>{let t=e.releaseStage??Ce,n=computeActionStages(e.actions,t),r=computeActionStages(e.events?.actions,t),i=Object.fromEntries(Object.entries(e.authentication??{}).map(([i,a])=>[i,authTypeReleaseStage(a)??highestReleaseStage([...reachableStages(i,e.actions,n),...reachableStages(i,e.events?.actions,r)])??t]));return{connector:Object.values(i).includes(`ga`)?`ga`:t,actions:n,eventActions:r,authTypes:i}},stampActionStages=(e,t)=>{for(let[n,r]of Object.entries(e??{}))r.releaseStage=t[n]},applyComputedReleaseStages=e=>{if(isCustomConnector(e))return;let t=computeReleaseStages(e);stampActionStages(e.actions,t.actions),stampActionStages(e.events?.actions,t.eventActions);for(let[n,r]of Object.entries(e.authentication??{}))for(let e of Object.values(r))e.releaseStage=t.authTypes[n];e.releaseStage=t.connector},connectorStage=e=>e.releaseStage??Ce,isConnectorReleased=(e,t=[])=>isCustomConnector(e)||t.includes(connectorStage(e)),keepEntries=(e,t)=>Object.fromEntries(Object.entries(e??{}).filter(([e,n])=>t(e,n))),itemId=(e,t)=>t.id??e,buildProfileItems=(e,n)=>Object.entries(e??{}).map(([e,r])=>({id:itemId(e,r),releaseStage:r.releaseStage??n,...(0,t.notMissing)(r.authRequirements)?{authTypes:Object.keys(r.authRequirements)}:{}})),buildReleaseStageProfile=e=>{let t=connectorStage(e);return{releaseStage:t,authTypes:Object.fromEntries(Object.entries(e.authentication??{}).map(([e,n])=>[e,authTypeReleaseStage(n)??t])),actions:buildProfileItems(e.actions,t),eventActions:buildProfileItems(e.events?.actions,t)}},decideReleaseStages=({releaseStage:e,authTypes:n},r,i)=>{let a=Object.keys(n);if(isCustomOwner(r))return{authenticationKeys:new Set(a),isKept:()=>!0};if(!i.includes(e))return;let o=a.filter(e=>i.includes(n[e]));if(a.length>0&&o.length===0)return;let isReachable=e=>a.length===0||(0,t.isMissing)(e)||o.some(t=>e.includes(t));return{authenticationKeys:new Set(o),isKept:e=>i.includes(e.releaseStage)&&isReachable(e.authTypes)}},resolveReleaseStageProfile=(e,n,r=[])=>{let i=decideReleaseStages(e,n,r);if((0,t.isMissing)(i))return;let keptIds=e=>new Set(e.filter(i.isKept).map(e=>e.id));return{actionIds:keptIds(e.actions),eventActionIds:keptIds(e.eventActions),authenticationKeys:i.authenticationKeys}},countItems=e=>[...e.reduce((e,{releaseStage:n,authTypes:r})=>{let i=(0,t.notMissing)(r)?[...r].sort():void 0,a=JSON.stringify([n,i??null]);return e.set(a,{releaseStage:n,...(0,t.notMissing)(i)?{authTypes:i}:{},count:(e.get(a)?.count??0)+1})},new Map).values()],countReleaseStageProfile=e=>({releaseStage:e.releaseStage,authTypes:e.authTypes,actions:countItems(e.actions),eventActions:countItems(e.eventActions)}),resolveReleaseStageCounts=(e,n,r=[])=>{let i=decideReleaseStages(e,n,r);if((0,t.isMissing)(i))return;let keptCount=e=>e.filter(i.isKept).reduce((e,t)=>e+t.count,0);return{actionCount:keptCount(e.actions),eventActionCount:keptCount(e.eventActions),authenticationKeys:i.authenticationKeys}},applyReleaseStageToConnector=(e,n=[])=>{let r=resolveReleaseStageProfile(buildReleaseStageProfile(e),e.owner,n);if((0,t.isMissing)(r))return;let keepResolved=(e,t)=>keepEntries(e,(e,n)=>t.has(itemId(e,n))),i=e.events?.actions,a=e.authentication;return{...e,actions:keepResolved(e.actions,r.actionIds),...(0,t.notMissing)(i)?{events:{...e.events,actions:keepResolved(i,r.eventActionIds)}}:{},...(0,t.notMissing)(a)?{authentication:keepEntries(a,e=>r.authenticationKeys.has(e))}:{}}},formatValidationErrorResponse=e=>({statusCode:400,message:`Invalid request - validation failed`,errors:e.map(e=>({property:e.field,location:e.location,expected:e.expected,received:e.received,message:e.message}))}),getDefaultSuccessActionResponse=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The action was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token action was executed successfully.`};case`test`:return{statusCode:200,description:`The test action was executed successfully.`};case`event`:return{statusCode:200,description:`The event action was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown action type: ${e}`)}},getDefaultErrorActionResponses=()=>({400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}}),toKebabCase=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``),buildSupport=(e,n,r)=>{if((0,t.isMissing)(r))return;if((0,t.notMissing)(r.link))return r;let i=r.guides?.config?.sections,a=toKebabCase(n);return(0,t.notMissing)(i)&&i.length>0&&a!==``?{...r,link:`https://docs.stackone.com/connectors/${e}/guides/link-account/${a}`}:r},connectorUsesCallAction=e=>{let usesIt=e=>(e??[]).some(e=>e.stepFunction?.functionName===s.StepFunctionName.CALL_ACTION||e.stepFunctions?.some(e=>e.functionName===s.StepFunctionName.CALL_ACTION));if((e.actions??[]).some(e=>usesIt(e.steps))||(e.events?.actions??[]).some(e=>usesIt(e.steps))||usesIt(e.events?.externalAccountIdExtractor?.steps))return!0;let n=e.events?.setup;return[n?.creation,n?.activation,n?.deletion].some(e=>usesIt(e?.steps))?!0:(e.authentication??[]).some(e=>Object.values(e??{}).some(e=>(e?.testActions??[]).some(e=>!(0,t.isString)(e.action)&&usesIt(e.action?.steps))||usesIt(e?.refreshAuthentication?.action?.steps)))},buildYamlActionIds=e=>{let n=e.info.key,r=new Map,record=e=>r.set(buildActionId(n,e),e);for(let t of e.actions??[])record(t.actionId);for(let t of e.events?.actions??[])record(t.actionId);return(0,t.notMissing)(e.events?.externalAccountIdExtractor)&&record(e.events.externalAccountIdExtractor.actionId),r},collectCallOnlySites=(e,n,r)=>{let i=[],displayId=e=>n.get(e)??e;for(let t of Object.values(e.events?.actions??{}))i.push({location:{kind:`action`,actionId:displayId(t.id)},steps:t.steps});(0,t.notMissing)(r)&&i.push({location:{kind:`action`,actionId:displayId(r.id)},steps:r.steps});let a=e.events?.setup,o=[[`creation`,a?.creation],[`activation`,a?.activation],[`deletion`,a?.deletion]];for(let[e,n]of o)(0,t.notMissing)(n)&&i.push({location:{kind:`setupPhase`,phase:e},steps:n.steps});for(let n of Object.values(e.authentication??{}))for(let e of Object.values(n)){for(let n of e?.testActions??[])(0,t.isString)(n.action)||i.push({location:{kind:`action`,actionId:displayId(n.action.id)},steps:n.action.steps});let n=e?.refreshAuthentication?.action;(0,t.notMissing)(n)&&i.push({location:{kind:`action`,actionId:displayId(n.id)},steps:n.steps})}return i};function parseYamlConnector(e){try{let n=parseWithSchemaException(xe,(0,o.parse)(e)),r=parseScopeDefinitions(n.scopeDefinitions),i={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,details:n.info.details,changelog:n.info.changelog,resources:n.resources,documentation:n.documentation,rateLimit:n.rateLimit,concurrency:n.concurrency,releaseStage:n.releaseStage,forkedFrom:n.forkedFrom,mcp:n.mcp,scopeDefinitions:r},a=buildAuthenticationFromYaml(n),s={baseUrl:n.baseUrl,authentication:stripAuthenticationSetup(a)},c=buildActionsFromYaml(n,s);validateAuthRequirementsMutualExclusivity(n,c),i.actions=c;let l=buildSyncedActionsFromActions(c);(0,t.notMissing)(l)&&(i.syncedActions=l),hydrateTestActions(n,n.info.key,a,c,s),i.authentication=a,(0,t.notMissing)(c)&&(i.categories=getConnectorCategoriesFromActions(Object.values(c)));let u=buildEventActionsFromYaml(n,s),d=n.events?.router,f=(0,t.notMissing)(n.events?.externalAccountIdExtractor)?parseAction(n,[`events`,`externalAccountIdExtractor`],buildActionId(n.info.key,n.events.externalAccountIdExtractor.actionId),n.events.externalAccountIdExtractor,s,void 0):void 0,p=n.events?.setup,m=(0,t.notMissing)(p)?{isConsolidated:p.isConsolidated,creation:parseWebhookSetupPhase(`creation`,p.creation,s),activation:(0,t.notMissing)(p.activation)?parseWebhookSetupPhase(`activation`,p.activation,s):void 0,deletion:parseWebhookSetupPhase(`deletion`,p.deletion,s)}:void 0,h=n.events?.guides,g=(0,t.notMissing)(h)?(()=>{let e=h.setup;if(!(0,t.notMissing)(e))return{setup:void 0};let r=new Set(Object.keys(n.scopeDefinitions||{})),i=parseGuideSectionsRequiredScopes(e.sections,r,[`events`,`guides`,`setup`,`sections`]);return{setup:{warning:e.warning,sections:i??[]}}})():void 0;if(((0,t.notMissing)(u)||(0,t.notMissing)(d)||(0,t.notMissing)(f)||(0,t.notMissing)(m)||(0,t.notMissing)(g))&&(i.events={setup:m,guides:g,actions:u,router:d,externalAccountIdExtractor:f}),(0,t.notMissing)(d)){let e=Object.keys(i.events?.actions??{}),t=n.info.key;validateEventRouterRuleActions(d.delivery??[],`delivery rule`,t,e),validateEventRouterRuleActions(d.rules,`rule`,t,e)}if(applyComputedReleaseStages(i),connectorUsesCallAction(n)){let e=buildYamlActionIds(n);validateCallActionGraph({connectorKey:n.info.key,actions:c??{},yamlActionIds:e,callOnlySites:collectCallOnlySites(i,e,f)})}return i}catch(e){if(e instanceof Y)throw e;let t=e.message,n=t.match(/at line (\d+)/);throw new InvalidYamlFileError(n?parseInt(n[1],10):1,t)}}const parseScopeDefinitions=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))t[n]={name:n,description:r.description,includes:parseScopesString(r?.includes)};let n=new Set(Object.keys(t)),r=[];if(Object.values(t).forEach(e=>{e.includes&&e.includes.forEach(t=>{n.has(t)||r.push({message:`Scope '${t}' included in scope '${e.name}' is not defined.`,path:[`scopeDefinitions`,e.name],keys:[`includes`]})})}),r.length>0)throw new MissingScopeDefinitionError(r);return t},stripAuthenticationSetup=e=>{let t={};for(let[n,r]of Object.entries(e))if(Array.isArray(r))t[n]=r;else if(r&&typeof r==`object`){let{setupFields:e,setupNotices:i,configFields:a,configNotices:o,support:s,refreshAuthentication:c,testActions:l,requiredScopes:u,authorizationFlow:d,releaseStage:f,...p}=r;t[n]=stripAuthenticationSetup(p)}else t[n]=r;return t},hydrateTestActions=(e,n,r,i,a)=>{if(!r||!i)return;let o=0;for(let s of Object.values(r)){for(let r of Object.values(s))r.testActions=r.testActions?.map((r,s)=>{if((0,t.notMissing)(r.action))if(typeof r.action==`string`){let e=buildActionId(n,r.action),t=Object.values(i).find(t=>t.id===e);if(t)return{...r,action:t,isInline:!1}}else{let t=parseAction(e,[`authentication`,o,`testActions`,s],buildActionId(n,r.action.actionId),r.action,a);return{...r,action:t,isInline:!0}}return{...r,isInline:!1}});o++}},getConnectorCategoriesFromActions=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},we=/"([^"]*)"|(\S+)/g,parseScopesString=e=>{if(!(0,t.notMissing)(e))return;let n=[];for(let t of e.matchAll(we)){let e=(t[1]??t[2])?.trim();e&&e.length>0&&n.push(e)}return n},parseGuideSectionsRequiredScopes=(e,t,n)=>{if(!e?.length)return e;let r=[],i=e.map((e,i)=>{let a=e.applicableScopes,o=parseScopesString(typeof a==`string`?a:void 0);o&&o.forEach(e=>{t.has(e)||r.push({message:`Scope '${e}' included in guide section is not defined.`,path:[...n,i],keys:[`applicableScopes`]})});let s=Array.isArray(e.steps)?e.steps:void 0,c=s?.map((e,a)=>{let s=e.applicableScopes;if(!s||typeof s!=`string`){let{applicableScopes:t,...n}=e;return{...n,applicableScopes:void 0}}let c=parseScopesString(s);return c?.forEach(e=>{t.has(e)||r.push({message:`Scope '${e}' included in guide step is not defined.`,path:[...n,i,`steps`,a],keys:[`applicableScopes`]})}),o&&c&&c.forEach(e=>{o.includes(e)||r.push({message:`Scope '${e}' included in guide step is missing from scopes set for section.`,path:[...n,i,`steps`,a],keys:[`applicableScopes`]})}),{...e,applicableScopes:c}})??s,{applicableScopes:l,steps:u,...d}=e;return{...d,...o===void 0?{}:{applicableScopes:o},...c===void 0?{}:{steps:c}}});if(r.length>0)throw new MissingScopeDefinitionError(r);return i},parseSupportGuides=(e,n,r)=>{if((0,t.isMissing)(e))return e;let i=e.guides;if((0,t.isMissing)(i))return e;let a=parseGuideSectionsRequiredScopes(i.config?.sections,n,[...r,`guides`,`config`,`sections`]),o=parseGuideSectionsRequiredScopes(i.setup?.sections,n,[...r,`guides`,`setup`,`sections`]);return{...e,guides:{...i,config:a!==void 0&&i.config?{...i.config,sections:a}:i.config,setup:o!==void 0&&i.setup?{...i.setup,sections:o}:i.setup}}},resolveAuthorizationRedirectUri=(e,n)=>{let{authorization:r}=e,i=e.type===`oauth2`&&e.grantType===`authorization_code`&&(0,t.notMissing)(r?.authorizationUrl),a=e.type===`mcp`&&(0,t.notMissing)(e.authorizationFlow);if(!i&&!a||(0,t.isMissing)(r))return;let o=r.redirectUri;return(0,t.isString)(o)&&o.trim()!==``?o:`\${apiHostUri}/connect/${i?`oauth2`:`mcp`}/${n}/callback`},buildAuthenticationFromYaml=e=>{let n={},r=new Set(Object.keys(e.scopeDefinitions||{})),i=[],a=e.info.key;for(let[o,s]of(e.authentication??[]).entries()){let[c]=Object.keys(s);n[c]=s[c].environments.reduce((n,l)=>{let{key:u,name:d}=l,{environments:f,refreshAuthentication:p,testActions:m,requiredScopes:h,...g}=s[c],_=parseScopesString(h);Object.values(_??[]).forEach(e=>{r.has(e)||i.push({message:`Scope '${e}' included in authentication '${c}' is not defined.`,path:[`authentication`,o],keys:[`requiredScopes`]})});let v=(0,t.notMissing)(p)?{schedule:p.schedule,action:parseAction(e,[`authentication`,o,`refreshAuthentication`,`action`],buildActionId(a,p.action.actionId),p.action)}:void 0,y=(0,t.notMissing)(g.support)?parseSupportGuides(g.support,r,[`authentication`,o,c,`support`]):void 0,b=(0,t.notMissing)(y)?buildSupport(a,g.label,y):void 0,x=resolveAuthorizationRedirectUri(g,a),S=(0,t.notMissing)(x)?{...g.authorization,redirectUri:x}:g.authorization;return n[u]={...g,authorization:S,...(0,t.notMissing)(b)?{support:b}:{},refreshAuthentication:v,requiredScopes:_,envKey:u,envName:d,testActions:m},n},{})}if(i.length>0)throw new MissingScopeDefinitionError(i);return n},buildActionKey=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,inferActionKey=e=>e.actionType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,getEntrypointHttpMethod=e=>{if(e.actionType!==`refresh_token`)return e.entrypointHttpMethod??`get`},inferEntrypointUrl=e=>{if(!(e.actionType===`refresh_token`||(0,t.isMissing)(e.schema)))return e.actionType===`list`?`/${e.schema}`:`/${e.schema}/:id`},buildActionResponses=e=>{let t={success:getDefaultSuccessActionResponse(e.actionType),errors:getDefaultErrorActionResponses()};return e.responses?.reduce((e,t)=>((0,a.isSuccessStatusCode)(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e),t)??t},buildActionsFromYaml=(e,t)=>e.actions?.reduce((n,r,i)=>{let a=buildActionKey(r),o=inferActionKey(r),s=a??o,c=buildActionId(e.info.key,r.actionId);return n[c]=parseAction(e,[`actions`,i],c,r,t,s),n},{}),buildSyncedActionsFromActions=e=>{if(!(0,t.notMissing)(e))return;let n=Object.values(e).reduce((e,t)=>{if(t.dataSync?.allowed!==!0)return e;let n=`${t.id}_s1query`;return e[n]={id:n,baseActionId:t.id,label:t.label,description:t.description,actionType:t.actionType,entrypointHttpMethod:t.entrypointHttpMethod,inputs:t.inputs,validationRules:t.validationRules,hasRequiredInput:t.inputs?.some(e=>e.required)??!1,dataSync:t.dataSync},e},{});return Object.keys(n).length>0?n:void 0},buildEventActionsFromYaml=(e,t)=>e.events?.actions?.reduce((n,r,i)=>{let a=buildActionId(e.info.key,r.actionId);return n[a]=parseAction(e,[`events`,`actions`,i],a,r,t,void 0),n},{}),validateEnumInputs=(e,t)=>{if(t){for(let n of t)if(n.type===`enum`&&n.oneOf&&`ref`in n.oneOf&&!(0,s.isValidEnumRef)(n.oneOf.ref))throw new InvalidEnumReferenceError(e,n.name,n.oneOf.ref)}},validateVariantProperties=(e,t,n)=>{for(let r of t){let t=[...e,r.name];!r.variants&&!r.type&&n.push({message:`'type' is required when 'variants' is absent`,path:t,keys:[`type`]}),r.type===`enum`&&!r.oneOf&&n.push({message:`oneOf is required when type is 'enum'`,path:t,keys:[]}),r.type===`enum`&&r.oneOf&&`ref`in r.oneOf&&((0,s.isValidEnumRef)(r.oneOf.ref)||n.push({message:`Invalid enum reference '${r.oneOf.ref}'`,path:t,keys:[]})),r.type!==`enum`&&r.oneOf&&n.push({message:`oneOf is only allowed when type is 'enum'`,path:t,keys:[]}),r.variants&&validateInputVariants(e,[r],n),r.type===`object`&&r.properties&&validateVariantProperties(t,r.properties,n)}},validateInputVariants=(e,t,n)=>{if(t)for(let r of t){let t=[...e,r.name];if(r.variants){r.type&&n.push({message:`when 'variants' is present, 'type' must be absent`,path:t,keys:[`type`]}),r.array&&n.push({message:`when 'variants' is present, 'array' must be absent`,path:t,keys:[`array`]}),r.properties&&n.push({message:`when 'variants' is present, 'properties' must be absent`,path:t,keys:[`properties`]}),r.oneOf&&n.push({message:`when 'variants' is present, 'oneOf' must be absent`,path:t,keys:[`oneOf`]}),r.rules&&n.push({message:`when 'variants' is present, 'rules' must be absent — define rules inside each variant instead`,path:t,keys:[`rules`]}),r.variants.length<2&&n.push({message:`'variants' must contain at least 2 entries`,path:t,keys:[`variants`]});for(let e of r.variants)e.type===`enum`&&!e.oneOf&&n.push({message:`oneOf is required when type is 'enum'`,path:t,keys:[]}),e.type===`enum`&&e.oneOf&&`ref`in e.oneOf&&((0,s.isValidEnumRef)(e.oneOf.ref)||n.push({message:`Invalid enum reference '${e.oneOf.ref}'`,path:t,keys:[]})),e.type===`object`&&e.properties&&validateVariantProperties(t,e.properties,n)}else r.type||n.push({message:`'type' is required when 'variants' is absent`,path:t,keys:[`type`]});r.type===`object`&&r.properties&&validateInputVariants(t,r.properties,n)}},validateExamplesMatchInputs=(e,n,r)=>{if(!n||n.length===0)return;let i={};for(let e of r){let t=buildZodSchemaFromInputType(e);e.required||(t=t.optional()),i[e.name]=t}let a=t.z.object(i).strict();for(let t=0;t<n.length;t++){let{exampleDescription:r,...i}=n[t],o=a.safeParse(i);if(!o.success){let n=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:[]}));throw new InvalidActionExampleError(e,t,n)}}},validateActionRuleFieldReferences=(e,t,n,r)=>{if(!n||n.length===0)return;let i=new Set(r.map(e=>e.name)),a=[];for(let r of n){let n=[];switch(r.rule){case`atLeastOneOf`:case`mutuallyExclusive`:n.push(...r.fields);break;case`requiredIf`:n.push(r.field,r.condition.field);break}for(let o of n)i.has(o)||a.push({message:`Validation rule '${r.rule}' in action '${e}' references unknown field '${o}'`,path:[...t,`validationRules`],keys:[o]})}if(a.length>0)throw new SchemaValidationError(a)},validateDataSyncPaginationKeys=(e,t,n,r)=>{let i=n?.pagination;if(!i)return;let a=(0,s.getIteratorLocation)(i),o=(0,s.getPaginationKeys)(i);if(!a||o.length===0)return;let c=new Set(r.filter(e=>e.in===a).map(e=>e.name)),l=[];for(let n of o)c.has(n)||l.push({message:`Pagination iterator references key '${n}' in '${a}', but no input with that name and location is declared on action '${e}'.`,path:[...t,`dataSync`,`pagination`,`iterator`],keys:[n]});if(l.length>0)throw new SchemaValidationError(l)},validateDataSyncIncrementalKeys=(e,t,n,r)=>{let i=n?.incremental;if(!i)return;let{key:a,in:o}=i.iterator;if(!r.some(e=>e.in===o&&e.name===a))throw new SchemaValidationError([{message:`Incremental iterator references key '${a}' in '${o}', but no input with that name and location is declared on action '${e}'.`,path:[...t,`dataSync`,`incremental`,`iterator`],keys:[a]}])},validateEventRouterRuleActions=(e,t,n,r)=>{let i=`${n}_`;for(let[a,o]of e.entries()){let e=o.then.action;if(!e.startsWith(i))throw new InvalidEventRouterActionPrefixError(e,a,n,t);if(!r.includes(e))throw new InvalidEventRouterReferenceError(e,a,t)}},validateAuthRequirementsMutualExclusivity=(e,n)=>{if((0,t.isMissing)(n))return;let r=e.info.key,i=Object.values(n).some(e=>(0,t.notMissing)(e.authRequirements)),a=Object.values(n).some(e=>(0,t.notMissing)(e.requiredScopes)&&e.requiredScopes.length>0);if(i&&a)throw new InvalidAuthRequirementsError([{message:`Connector '${r}' cannot have both 'authRequirements' and 'requiredScopes'. To migrate, replace 'requiredScopes' with 'authRequirements' on all actions including test actions.`,path:[`actions`],keys:[`authRequirements`,`requiredScopes`]}])},getConnectorAuthKeys=e=>{let t=new Set;for(let n of e.authentication??[])for(let e of Object.keys(n))t.add(e);return t},parseAuthRequirements=(e,n,r,i,a)=>{if((0,t.isMissing)(i))return;if(Object.keys(i).length===0)throw new InvalidAuthRequirementsError([{message:`Action '${r}' has an empty authRequirements map. Either omit authRequirements (to allow all auth types) or specify at least one auth config key.`,path:[...n,`authRequirements`],keys:[]}]);let o=getConnectorAuthKeys(e),s=[],c={};for(let[e,t]of Object.entries(i)){if(!o.has(e)){s.push({message:`Action '${r}' references auth config key '${e}' which is not defined on this connector. Valid keys: ${[...o].join(`, `)}.`,path:[...n,`authRequirements`],keys:[e]});continue}for(let i of t)a.has(i)||s.push({message:`Undefined scope '${i}' in action '${r}' (auth: '${e}'). Ensure the scope is declared in scopeDefinitions.`,path:[...n,`authRequirements`,e],keys:[i]});c[e]=t}if(s.length>0)throw new InvalidAuthRequirementsError(s);return c},parseAction=(e,t,n,r,i,a)=>{let o=inferEntrypointUrl(r),c=buildActionResponses(r),l=buildCursorConfig(r),u=r.inputs||[];l.enabled&&(u?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),u?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1})),validateEnumInputs(n,u);let d=[];if(validateInputVariants(t,u,d),d.length>0)throw new SchemaValidationError(d);validateExamplesMatchInputs(n,r.examples,u),validateActionRuleFieldReferences(n,t,r.validationRules,u),validateDataSyncPaginationKeys(n,t,r.dataSync,u),validateDataSyncIncrementalKeys(n,t,r.dataSync,u);let f=getEntrypointHttpMethod(r),p=new Set(Object.keys(e.scopeDefinitions||{})),m=[],h=parseScopesString(r.requiredScopes);if(Object.values(h??[]).forEach(e=>{p.has(e)||m.push({message:`Scope '${e}' included in action '${r.actionId}' is not defined.`,path:t,keys:[`requiredScopes`]})}),m.length>0)throw new MissingScopeDefinitionError(m);let g=parseAuthRequirements(e,t,r.actionId,r.authRequirements,p);return{id:n,categories:r.categories,label:r.label,description:r.description,details:r.details,examples:r.examples,actionType:r.actionType,effects:r.effects,annotations:r.annotations,executionMode:r.executionMode,schemaType:r.schemaType??`native`,entrypointUrl:r.entrypointUrl??o,entrypointHttpMethod:f,endpoint:a,tags:r.tags,releaseStage:r.releaseStage,resources:r.resources,responses:c,cursor:l,compositeIdentifiers:parseCompositeIdentifiersConfig(r),requiredScopes:h,authRequirements:g,inputs:u,validationRules:r.validationRules,steps:parseSteps({kind:`action`,actionId:r.actionId},r.steps,i,n=>n.functionName!==`map_fields`&&n.functionName!==`typecast`?{}:parseFieldConfigs(e,t,n.parameters?.fields??r.fieldConfigs)??{}),result:r.result,dataSync:r.dataSync,dataSyncConfigFingerprint:r.dataSync?.allowed===!0?(0,s.computeDataSyncFingerprint)(r.dataSync):void 0,providerEvents:r.providerEvents,prerequisiteActions:r.prerequisiteActions,requiresManualSetup:r.requiresManualSetup,userScoped:r.userScoped}},parseWebhookSetupPhase=(e,t,n)=>({steps:parseSteps({kind:`setupPhase`,phase:e},t.steps,n),result:t.result}),parseSteps=(e,t,n,r)=>t.reduce((t,i)=>{let parseStepFunctionMeta=e=>{let{customErrors:t,...i}=e.parameters??{},a=r?.(e)??{};return{functionName:e.functionName,version:e.version,params:{...getDefaultRequestStepFunctionsParams({stepFunctionName:e.functionName,baseRequestParams:n,customErrors:t}),...a,...i}}},a={id:i.stepId,description:i.description,condition:i.condition,onConditionError:i.onConditionError,ignoreError:i.ignoreError};if(`iterator`in i&&i.iterator){if(`stepFunction`in i&&i.stepFunction){let n={...a,iterator:i.iterator,stepFunction:parseStepFunctionMeta(i.stepFunction)};validateStep(e,n),t[i.stepId]=n}else if(`stepFunctions`in i&&i.stepFunctions){let n={...a,iterator:i.iterator,stepFunctions:i.stepFunctions.map(parseStepFunctionMeta)};validateStepFunctions(e,n),t[i.stepId]=n}}else if(`stepFunction`in i&&i.stepFunction){let n={...a,stepFunction:parseStepFunctionMeta(i.stepFunction)};validateStep(e,n),t[i.stepId]=n}return t},{}),parseFieldConfigs=(e,n,r)=>{if((0,t.isMissing)(r)||!Array.isArray(r))return;let i=new Set(Object.keys(e.scopeDefinitions||{})),a=[],o=r.map((e,t)=>{if(typeof e!=`object`||!e)return;let r=parseScopesString(e.requiredScopes);return Object.values(r??[]).forEach(r=>{i.has(r)||a.push({message:`Scope '${r}' included in field config '${e.targetFieldKey}' is not defined.`,path:[...n,`fieldConfigs`,t],keys:[`requiredScopes`]})}),{...e,requiredScopes:r}});if(a.length>0)throw new MissingScopeDefinitionError(a);return{fields:o}},validateStep=(e,t)=>{let n=t.stepFunction.version??`1`,r=s.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new InvalidStepFunctionError(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&parseStepFunctionParamsWithSchemaException(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},validateStepFunctions=(e,t)=>{for(let n of t.stepFunctions){let r=n.version??`1`,i=s.StepFunctionsRegistry[n.functionName]?.[`v${r}`];if(!i)throw new InvalidStepFunctionError(e,t.id,n.functionName,r);let a=i.inputSchema;a&&parseStepFunctionParamsWithSchemaException(a,n.params,e,t.id,n.functionName,r)}},buildPathString=e=>e.reduce((e,t)=>typeof t==`number`?`${e}[${t}]`:typeof t==`string`?e?`${e}.${t}`:t:e,``),enrichVariantErrors=e=>{let isVariantDump=e=>e.message?.includes(`expected one of the following shapes`),t=e.filter(isVariantDump);if(t.length===0)return e;let n=Math.min(...t.map(e=>e.path?.length??0));return e.filter(e=>!isVariantDump(e)||(e.path?.length??0)<=n).map(e=>isVariantDump(e)&&e.path?.length>0?{...e,message:`The field '${buildPathString(e.path)}' ${e.message}`}:e)},parseActionInputs=(e,n)=>{if(!e.inputs)return{};let r=createInputsSchema(e.inputs),i;try{i=t.z.object(r).parse(n)}catch(e){throw e instanceof t.z.ZodError?new t.z.ZodError(enrichVariantErrors(e.issues)):e}let a={...i.headers??{},...i.query??{},...i.path??{},...i.body??{}};return e.validationRules&&e.validationRules.length>0&&validateActionRules(e.validationRules,a,e.inputs),a},createInputsSchema=e=>{let n=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),r={};for(let[e,i]of Object.entries(n)){let n={};for(let e of i){let t=buildZodSchemaFromInputType(e);e.description&&(t=t.meta({description:e.description})),e.required||(t=t.optional()),n[e.name]=t}Object.keys(n).length>0&&(r[e]=t.z.object(n))}return r},buildEnumZodSchema=(e,n)=>{if(!n)throw Error(`Enum input "${e}" requires oneOf definition`);let r;if(`values`in n)r=n.values;else if(`ref`in n){let t=(0,s.getInputEnumValues)(n.ref);if(!t)throw Error(`Unknown enum reference "${n.ref}" in input "${e}"`);r=t}else throw Error(`Invalid oneOf definition in input "${e}"`);if(r.length===0)throw Error(`Enum input "${e}" must have at least one allowed value`);return t.z.enum(r)},applyInputRules=(e,t,n)=>{let r=t.errorMessage;if(n===`string`||n===`datetime_string`){let n=e;if(t.minLength!==void 0&&(n=n.min(t.minLength,r)),t.maxLength!==void 0&&(n=n.max(t.maxLength,r)),t.pattern!==void 0&&(n=n.regex(new RegExp(t.pattern),r)),t.format!==void 0){let e=s.FORMAT_PATTERNS[t.format];e&&(n=n.regex(e,r??`Must be a valid ${t.format}`))}return n}if(n===`number`){let n=e;return t.min!==void 0&&(n=n.min(t.min,r)),t.max!==void 0&&(n=n.max(t.max,r)),n}return e},validateActionRules=(e,n,r)=>{let i=[],a={};if(r)for(let e of r)a[e.name]=e.in;let fieldPath=e=>{let t=a[e];return t?[t,e]:[e]};for(let t of e)switch(t.rule){case`atLeastOneOf`:if(!t.fields.some(e=>n[e]!==void 0&&n[e]!==null))for(let e of t.fields)i.push({code:`custom`,message:t.errorMessage??`At least one of [${t.fields.join(`, `)}] is required`,path:fieldPath(e),input:n});break;case`requiredIf`:{let e=n[t.condition.field],r=!1;if(t.condition.equals!==void 0)r=String(e)===t.condition.equals;else if(t.condition.notEquals!==void 0)r=String(e)!==t.condition.notEquals;else if(t.condition.present!==void 0){let n=e!=null;r=t.condition.present?n:!n}r&&(n[t.field]===void 0||n[t.field]===null)&&i.push({code:`custom`,message:t.errorMessage??`Field "${t.field}" is required when condition is met`,path:fieldPath(t.field),input:n});break}case`mutuallyExclusive`:{let e=t.fields.filter(e=>n[e]!==void 0&&n[e]!==null);if(e.length>1)for(let r of e)i.push({code:`custom`,message:t.errorMessage??`Fields [${t.fields.join(`, `)}] are mutually exclusive`,path:fieldPath(r),input:n});break}}if(i.length>0)throw new t.z.ZodError(i)},describeVariantShape=e=>{let t;switch(e.type){case`string`:case`datetime_string`:case`number`:case`boolean`:t=e.type;break;case`enum`:t=e.oneOf&&`values`in e.oneOf?e.oneOf.values.map(e=>`'${e}'`).join(` | `):`enum`;break;case`object`:t=e.properties&&e.properties.length>0?`{ ${e.properties.map(e=>{let t=e.required?``:`?`,n;return n=e.variants&&e.variants.length>=2?e.variants.map(describeVariantShape).join(` | `):e.type===`enum`&&e.oneOf&&`values`in e.oneOf?e.oneOf.values.map(e=>`'${e}'`).join(` | `):e.type??`unknown`,e.array&&(n+=`[]`),`${e.name}${t}: ${n}`}).join(`, `)} }`:`object`;break;default:t=`unknown`}return e.array&&(t+=`[]`),t},buildVariantsSchema=e=>{let n=e.map(e=>buildZodSchemaFromInputType(e,{strict:!0})),r=e.map(describeVariantShape).join(` | `);return t.z.any().check(e=>{for(let t of n)if(t.safeParse(e.value).success)return;e.issues.push({code:`custom`,message:`expected one of the following shapes: ${r}`,input:e.value,path:[]})})},buildZodSchemaFromInputType=(e,n)=>{if(e.variants&&e.variants.length>=2)return buildVariantsSchema(e.variants);let r;switch(e.type){case`string`:case`datetime_string`:r=t.z.string();break;case`number`:r=t.z.number();break;case`boolean`:r=t.z.boolean();break;case`enum`:r=buildEnumZodSchema(e.name,e.oneOf);break;case`object`:if(e.properties&&e.properties.length>0){let i={};for(let t of e.properties){let e=buildZodSchemaFromInputType(t,n);t.description&&(e=e.meta({description:t.description})),t.required||(e=e.optional()),i[t.name]=e}r=n?.strict?(0,t.zStrictObject)(i):t.z.object(i)}else r=t.z.record(t.z.string(),t.z.unknown());break;default:r=t.z.unknown()}return e.rules&&e.type&&(r=applyInputRules(r,e.rules,e.type)),e.array&&(r=t.z.array(r)),r},buildCursorConfig=e=>{let t=e.actionType===`list`,n=e.cursor??{enabled:t,pageSize:25};return{enabled:n.enabled&&t,pageSize:n.pageSize}},parseCompositeIdentifiersConfig=e=>{if(e.actionType===`refresh_token`||(0,t.isMissing)(e.compositeIdentifiers))return{enabled:!1};let n=[];for(let t of e.compositeIdentifiers?.fields??[]){let r=t.components.map(t=>({name:t,alias:e.fieldConfigs?.find(e=>e.targetFieldKey===t)?.alias}));n.push({targetFieldKey:t.targetFieldKey,remote:t.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:n.length>0?n:void 0}},getDefaultRequestStepFunctionsParams=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`||e===`soap_request`||e===`soap_paginated_request`||e===`download_file`||e===`upload_file`||e===`upload_binary`){let e=[{receivedStatus:500,targetStatus:502}],r=[...n&&Array.isArray(n)?n:[],...e];return{...t,customErrors:r}}else if(e===`mcp_request`)return{...t};else return{}},parseWithSchemaException=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;throw new SchemaValidationError(n.error.issues.map(e=>{let t=e?.keys??[];if(t.length===0&&e.code===`invalid_union`){let n=e;for(let e of n.errors??[]){let n=e?.find(e=>e.code===`unrecognized_keys`);if(n?.keys?.length){t=n.keys;break}}}return{code:e.code,message:e.message,input:e.input,path:e.path,keys:t}}),`Invalid connector schema`)},parseStepFunctionParamsWithSchemaException=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;throw new InvalidStepFunctionParamsError(n,r,i,a,o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]})))},validateYamlConnector=e=>{try{return{success:!0,connector:parseYamlConnector(e)}}catch(n){if(n instanceof SchemaValidationError||n instanceof MissingScopeDefinitionError||n instanceof InvalidAuthRequirementsError){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=(0,t.isMissing)(r)?n.path:[...n.path,r],o=getErrorLineNumber(a,e);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof InvalidYamlFileError)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof InvalidStepFunctionError)return{success:!1,errors:[{line:getErrorLineNumberInSteps(n.location,n.stepId,n.functionName,!1,e),message:n.message,field:stepLocationField(n.location)}]};else if(n instanceof UnknownCallActionTargetError||n instanceof SelfReferencingActionError||n instanceof CircularActionReferenceError||n instanceof IncompatibleCallActionAuthError)return{success:!1,errors:[{line:getErrorLineNumberInSteps(n.location,n.stepId,`call_action`,!1,e),message:n.message,field:stepLocationField(n.location)}]};else if(n instanceof InvalidEventRouterActionPrefixError||n instanceof InvalidEventRouterReferenceError)return{success:!1,errors:[{line:1,message:n.message,field:`events.router`}]};else if(n instanceof InvalidStepFunctionParamsError){let r=n.issues,i=[],a=stepLocationFieldPrefix(n.location);return r.forEach(r=>{let o=r?.keys?.[0],s=(0,t.isMissing)(o)?r.path:[...r.path,o],c=getErrorLineNumberInSteps(n.location,n.stepId,n.functionName,!0,e);i.push({line:c,message:r.message,field:`${a}${s.join(`.`)}`})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},getErrorLineNumber=(e,n)=>{let r=n.split(`
|
|
4
|
+
`).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},hasDelimiter=e=>e.includes(`{{`)||e.includes(`}}`),responseKeySchema=e=>t.z.string().refine(e=>(0,c.isExpression)(e)?(0,c.isValidExpression)(e):!hasDelimiter(e),{message:`Expression does not compile`}).meta({description:e}),g=(0,t.zStrictObject)({type:t.z.literal(`cursor`).meta({description:`Selects the cursor-based pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`}),nextKey:responseKeySchema("Response key for the next-page cursor: a dot-path into the action result, or a `{{ }}` expression evaluated against the result with response headers at `$.headers` (lowercased).")}).meta({description:`How records and the next-page cursor are located in the response.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter the next-page cursor is sent in.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."})}).meta({description:`Request parameter that carries the next-page cursor.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the resolved next-page cursor is `null`."})}),_=(0,t.zStrictObject)({type:t.z.literal(`offset`).meta({description:`Selects the offset-based pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`})}).meta({description:`How each page of records is located in the response.`}),iterator:(0,t.zStrictObject)({offsetKey:t.z.string().meta({description:`Request parameter set to the offset of the first record on each page.`}),limitKey:t.z.string().meta({description:`Request parameter set to the number of records requested per page.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."}),startOffset:t.z.number().int().min(0).optional().meta({description:"Offset sent on the first page. Defaults to `0`. Set to `1` for APIs that count records from 1 rather than 0, such as SCIM's `startIndex`."}),defaultLimit:t.z.number().optional().meta({description:"Number of records requested per page. Defaults to `100` when omitted."})}).meta({description:`Request parameters that page through results by offset and limit.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the data key returns no records."})}),v=(0,t.zStrictObject)({type:t.z.literal(`page`).meta({description:`Selects the page-number pagination strategy.`}),response:(0,t.zStrictObject)({dataKey:t.z.string().meta({description:`Response key holding the array of records for each page.`})}).meta({description:`How each page of records is located in the response.`}),iterator:(0,t.zStrictObject)({pageKey:t.z.string().meta({description:`Request parameter set to the page number for each request.`}),pageSizeKey:t.z.string().optional().meta({description:`Request parameter set to the number of records requested per page. Omit when the endpoint takes no page-size parameter.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the pagination parameters: `query`, `body`, or `headers`."}),startPage:t.z.number().optional().meta({description:"Page number requested for the first page. Defaults to `1` when omitted."}),defaultPageSize:t.z.number().optional().meta({description:"Number of records requested per page. Defaults to `100` when omitted."})}).meta({description:`Request parameters that page through results by page number.`}),stopCondition:t.z.string().optional().meta({description:"JEXL expression evaluated against each response to stop paging, with response headers at `$.headers` (lowercased). Defaults to stopping when the data key returns no records."})}),y=t.z.discriminatedUnion(`type`,[g,_,v]),b=(0,t.zStrictObject)({type:t.z.literal(`delta_token`).meta({description:`Selects the delta-token strategy where each sync sends the token returned by the previous sync.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter name the delta token is sent under.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the delta token: `query`, `body`, or `headers`."})}).meta({description:`Names the request parameter carrying the previous delta token and where on the request to place it.`}),response:(0,t.zStrictObject)({path:responseKeySchema("Response key for the delta token used on the next sync: a dot-path into the action result, or a `{{ }}` expression evaluated against the result with response headers at `$.headers` (lowercased)."),onlyOnFinalPage:t.z.boolean().optional().meta({description:"When `true`, read the delta token only from the final page of results."})}).meta({description:`Configures reading the next delta token from the response.`})}),x=(0,t.zStrictObject)({type:t.z.literal(`time_filter`).meta({description:`Selects the updated-since strategy where each sync requests only records changed after the last watermark.`}),iterator:(0,t.zStrictObject)({key:t.z.string().meta({description:`Request parameter name the last-sync timestamp is sent under.`}),in:t.z.enum([`query`,`body`,`headers`]).meta({description:"Where to add the timestamp parameter: `query`, `body`, or `headers`."})}).meta({description:`Names the request parameter carrying the last-sync timestamp and where on the request to place it.`}),format:t.z.enum([`iso8601`,`unix_seconds`,`unix_millis`]).meta({description:"Encoding of the timestamp value: `iso8601`, `unix_seconds`, or `unix_millis`."}),safetyBufferSeconds:t.z.number().int().nonnegative().default(60).meta({description:`Seconds subtracted from the run start time when falling back to the local clock so records near the boundary are not skipped.`}),response:(0,t.zStrictObject)({updatedAtPath:t.z.string().meta({description:`Path within each returned record to its last-updated timestamp, read to advance the watermark.`})}).optional().meta({description:`Configures reading the newest record timestamp from each page to advance the watermark.`})}),S=t.z.discriminatedUnion(`type`,[x,b]),hasCatastrophicBacktrackingRisk=e=>{let t=[],n=!1,r=/\{(\d+)(?:(,)(\d*))?\}/y,quantifierAt=t=>{let n=e[t];if(n===`*`||n===`+`)return{length:1,variable:!0,amplifying:!0};if(n===`?`)return{length:1,variable:!0,amplifying:!1};if(n===`{`){r.lastIndex=t;let n=r.exec(e);if(n){let e=Number(n[1]),t=n[2]===void 0?e:n[3]?Number(n[3]):1/0;return{length:n[0].length,variable:t>e,amplifying:t>=2}}}};for(let r=0;r<e.length;r++){let i=e[r];if(i===`\\`){r++;continue}if(n){i===`]`&&(n=!1);continue}if(i===`[`){n=!0;continue}if(i===`|`){t.length>0&&(t[t.length-1].hasAlternation=!0);continue}if(i===`(`){if(t.push({hasVariable:!1,hasAlternation:!1}),e[r+1]===`?`){let t=e[r+2]===`<`&&(e[r+3]===`=`||e[r+3]===`!`);r+=t?2:1}continue}if(i===`)`){let e=t.pop(),n=quantifierAt(r+1);if(n){if(n.amplifying&&(e?.hasVariable||e?.hasAlternation))return!0;r+=n.length}t.length>0&&((n?.variable||e?.hasVariable)&&(t[t.length-1].hasVariable=!0),e?.hasAlternation&&(t[t.length-1].hasAlternation=!0));continue}let a=quantifierAt(r);a&&(a.variable&&t.length>0&&(t[t.length-1].hasVariable=!0),r+=a.length-1)}return!1},compilesAsRegex=e=>{try{return new RegExp(e),!0}catch{return!1}},C=Object.keys(s.FORMAT_PATTERNS),w=Object.keys(s.INPUT_ENUM_REGISTRY),compileFieldValidationRegex=e=>e.pattern===void 0?e.format?s.FORMAT_PATTERNS[e.format]:void 0:new RegExp(e.pattern),T=(0,t.zStrictObject)({pattern:t.z.string().optional().meta({description:"Regular expression the entered value must match. Provide this or `format`, not both."}),format:t.z.enum(C).optional().meta({description:"Named format the entered value must match, standing in for a common regular expression. Provide this or `pattern`, not both."}),errorMessage:t.z.string().min(1,`errorMessage cannot be empty when set`).optional().meta({description:`Message shown when the value fails the pattern or format check.`})}).check(e=>{let t=e.value;if(t.pattern!==void 0==(t.format!==void 0)){e.issues.push({code:`custom`,input:t,path:[],message:`validation: must declare exactly one of pattern or format — pattern subsumes format, so encode compound constraints as a single pattern`});return}if(t.pattern!==void 0){if(t.pattern.length===0){e.issues.push({code:`custom`,input:t,path:[`pattern`],message:`pattern cannot be empty when set`});return}if(!compilesAsRegex(t.pattern)){e.issues.push({code:`custom`,input:t,path:[`pattern`],message:`Invalid regex pattern`});return}hasCatastrophicBacktrackingRisk(t.pattern)&&e.issues.push({code:`custom`,input:t,path:[`pattern`],message:"Pattern risks catastrophic backtracking (variable-width quantifier or alternation nested inside a repeated group, e.g. `(a+)+`, `(a{2,4})+` or `(a|a)+`). It runs on every keystroke in the browser — rewrite without nesting, typically by flattening the repeated group into a single character class with a lookahead guarding label boundaries (e.g. `^([a-z0-9-]+\\.)+[a-z]{2,}$` becomes `^(?!\\.|.*\\.\\.)[a-z0-9.-]+\\.[a-z]{2,}$`)."})}}),E={key:t.z.string().meta({description:`Identifier the credential value is stored and referenced under.`}),label:t.z.string().meta({description:`Human-readable name shown for this field.`}),required:t.z.boolean().optional().default(!1).meta({description:`Whether the field must have a value.`}),secret:t.z.boolean().optional().default(!1).meta({description:`Encrypt the value at rest and mask it in the UI.`}),externalSystemAccountIdentifier:t.z.boolean().optional().meta({description:`Value identifies the account in the external system, used to match incoming webhook events to a linked account.`}),readOnly:t.z.boolean().optional().default(!1).meta({description:`Whether the field is displayed but cannot be edited by the user.`}),placeholder:t.z.string().optional().meta({description:`Example value shown in the empty input to hint the expected format.`}),description:t.z.string().optional().meta({description:`Helper text explaining what the user should enter.`}),tooltip:t.z.string().optional().meta({description:`Additional guidance shown on hover for this field.`}),value:t.z.string().optional().meta({description:`Preset or computed value for the field, such as a fixed default or a JEXL expression.`}),computed:t.z.boolean().optional().meta({description:"Field value is a JEXL expression in `value`, evaluated at runtime rather than entered by the user."})},collectComputedValueIssues=e=>e.computed===!0&&!e.value?[{path:[`value`],message:`A computed field must have a value (JEXL expression)`}]:[],collectValidationSupportIssues=e=>e.computed===!0?[{path:[`validation`],message:`validation: is not supported on computed fields — the value is a server-evaluated expression the customer never types`}]:e.readOnly===!0?[{path:[`validation`],message:`validation: is not supported on readOnly fields — the customer never edits the value, so there is nothing for client-side validation to check`}]:[],collectValidationExampleIssues=e=>{let t=compileFieldValidationRegex(e.validation);if(!t)return[];let n=[];return e.placeholder!==void 0&&!t.test(e.placeholder)&&n.push({path:[`validation`],message:`placeholder "${e.placeholder}" does not satisfy the field's own validation — fix the pattern/format or the placeholder`}),e.value!==void 0&&!t.test(e.value)&&n.push({path:[`validation`],message:`default value "${e.value}" does not satisfy the field's own validation — fix the pattern/format or the value`}),n},D=t.z.discriminatedUnion(`type`,[(0,t.zStrictObject)({...E,type:t.z.enum([`text`,`password`,`text_area`]).meta({description:`Input control rendered for this credential field.`}),validation:T.optional().meta({description:`Client-side validation constraint applied to the entered value.`})}),(0,t.zStrictObject)({...E,type:t.z.literal(`select`).meta({description:`Input control rendered for this credential field.`}),options:(0,t.zStrictObject)({value:t.z.string().meta({description:`Value stored when this option is selected.`}),label:t.z.string().meta({description:`Human-readable text shown for this option.`})}).array().meta({description:`Selectable choices offered for this field.`})})]).check(e=>{let t=e.value,n=`validation`in t?t.validation:void 0,r=n?collectValidationSupportIssues(t):[],i=[...collectComputedValueIssues(t),...r,...n&&r.length===0?collectValidationExampleIssues({...t,validation:n}):[]];for(let n of i)e.issues.push({code:`custom`,input:t,message:n.message,path:n.path})}),O=(0,t.zStrictObject)({targetFieldKey:t.z.string().meta({description:`Key of the field in the mapped output this configuration produces.`}),alias:t.z.string().optional().meta({description:`Alternate key name for this field when it forms part of a composite identifier.`}),expression:t.z.string().optional().meta({description:`Expression evaluated to derive the field value.`}),values:t.z.unknown().optional().meta({description:`Inline object or array used in place of the source record when mapping an object field's nested properties.`}),type:t.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]).meta({description:`Data type of the field's value, used by the typecast step function to convert it and by the map_fields step function to decide how to map it.`}),array:t.z.boolean().default(!1).meta({description:`Whether the field holds a list of values.`}),custom:t.z.boolean().default(!1).meta({description:`Whether the field is a provider-specific custom field rather than a unified one.`}),hidden:t.z.boolean().default(!1).meta({description:`Currently not in use.`}),enumMapper:(0,t.zStrictObject)({matcher:t.z.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or((0,t.zStrictObject)({matchExpression:t.z.string().meta({description:`JEXL expression checked against the record. The rule applies when it evaluates to true.`}),value:t.z.string().meta({description:`Value emitted when the expression matches.`})}).array()).meta({description:`Built-in country or format matcher name, or a list of custom match rules, used to translate provider enum values.`})}).optional().meta({description:`Mapping used to translate provider enum values to StackOne values.`}),properties:t.z.lazy(()=>O).array().optional().meta({description:`Nested field configurations for object or array fields.`}),requiredScopes:t.z.string().optional().meta({description:`Scopes this field depends on, validated at build time against the connector's scope definitions.`})}),k=t.z.union([(0,t.zStrictObject)({values:t.z.string().array().min(1).meta({description:`Explicit list of allowed enum values.`})}),(0,t.zStrictObject)({ref:t.z.string().meta({description:`Name of a shared enum definition supplying the allowed values. One of: ${w.map(e=>`\`${e}\``).join(`, `)}.`})})]),A=(0,t.zStrictObject)({minLength:t.z.number().optional().meta({description:`Minimum number of characters the value must have.`}),maxLength:t.z.number().optional().meta({description:`Maximum number of characters the value may have.`}),pattern:t.z.string().refine(e=>compilesAsRegex(e),{message:`Invalid regex pattern`}).optional().meta({description:`Regular expression the value must match.`}),format:t.z.enum(C).optional().meta({description:`Named format the value must conform to.`}),min:t.z.number().optional().meta({description:`Minimum numeric value allowed.`}),max:t.z.number().optional().meta({description:`Maximum numeric value allowed.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the value violates a rule.`})}),j=(0,t.zStrictObject)({field:t.z.string().meta({description:`Name of the other input this condition inspects.`}),equals:t.z.string().optional().meta({description:`Condition holds when the referenced field equals this value.`}),notEquals:t.z.string().optional().meta({description:`Condition holds when the referenced field does not equal this value.`}),present:t.z.boolean().optional().meta({description:`When true, the condition holds if the referenced field is present. When false, it holds if the field is absent.`})}).refine(e=>[e.equals!==void 0,e.notEquals!==void 0,e.present!==void 0].filter(Boolean).length===1,{message:`Condition must specify exactly one of: equals, notEquals, present`}),M=t.z.discriminatedUnion(`rule`,[(0,t.zStrictObject)({rule:t.z.literal(`atLeastOneOf`).meta({description:`Requires at least one of the listed inputs to be provided.`}),fields:t.z.string().array().min(2).meta({description:`Input names of which at least one must be provided.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})}),(0,t.zStrictObject)({rule:t.z.literal(`requiredIf`).meta({description:`Requires an input when another field satisfies a condition.`}),field:t.z.string().meta({description:`Input that becomes required when the condition holds.`}),condition:j.meta({description:`Condition under which the field is required.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})}),(0,t.zStrictObject)({rule:t.z.literal(`mutuallyExclusive`).meta({description:`Allows at most one of the listed inputs to be provided.`}),fields:t.z.string().array().min(2).meta({description:`Input names of which at most one may be provided.`}),errorMessage:t.z.string().optional().meta({description:`Message shown when the rule is violated.`})})]),N=t.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`,`enum`]),P=t.z.lazy(()=>(0,t.zStrictObject)({type:N.meta({description:`Data type of this input variant.`}),description:t.z.string().optional().meta({description:`Explains what this variant represents.`}),array:t.z.boolean().optional().default(!1).meta({description:`Whether this variant holds a list of values.`}),properties:t.z.lazy(()=>F.omit({in:!0})).array().optional().meta({description:`Nested inputs when this variant is an object.`}),oneOf:k.optional().meta({description:`Allowed values when this variant is an enum.`}),rules:A.optional().meta({description:`Validation rules applied to this variant.`})}).check(e=>{let t=e.value;t.type===`enum`&&!t.oneOf&&e.issues.push({code:`custom`,message:`Variant with type 'enum' must declare oneOf`,input:t,path:[]})})),F=(0,t.zStrictObject)({name:t.z.string().meta({description:`Parameter name exposed to callers and mapped into the request.`}),type:N.optional().meta({description:`Data type of the input value.`}),required:t.z.boolean().meta({description:`Whether the caller must supply this input.`}),description:t.z.string().meta({description:`Explains the input for callers and generated tool schemas.`}),array:t.z.boolean().optional().default(!1).meta({description:`Whether the input accepts a list of values.`}),arrayFormat:t.z.enum([`repeat`,`brackets`,`comma`,`stringify`]).optional().meta({description:`How a list input's values are formatted in the request, such as repeated, comma-separated, or bracketed. Currently not in use.`}),in:t.z.enum([`body`,`query`,`path`,`headers`]).meta({description:`Part of the HTTP request this input is placed in.`}),properties:t.z.lazy(()=>F.omit({in:!0})).array().optional().meta({description:"Nested inputs when the input is an object. Each has the same shape as a top-level input, minus `in`."}),oneOf:k.optional().meta({description:`Allowed values when the input is an enum.`}),rules:A.optional().meta({description:`Validation rules applied to the input value.`}),variants:t.z.lazy(()=>P).array().min(2).optional().meta({description:"An input that accepts more than one type. Provide at least two variants, each defining one of those types the way an input does. The input itself sets no top-level `type`, `array`, `properties`, `oneOf`, or `rules`."})}).refine(e=>e.type!==`enum`||e.oneOf!==void 0,{message:`oneOf is required when type is 'enum'`}).refine(e=>e.type===`enum`||e.oneOf===void 0,{message:`oneOf is only allowed when type is 'enum'`}).refine(e=>e.rules&&(e.rules.minLength!==void 0||e.rules.maxLength!==void 0||e.rules.pattern!==void 0||e.rules.format!==void 0)?e.type===`string`||e.type===`datetime_string`:!0,{message:`String rules (minLength, maxLength, pattern, format) can only be used with string or datetime_string types`}).refine(e=>e.rules&&(e.rules.min!==void 0||e.rules.max!==void 0)?e.type===`number`:!0,{message:`Number rules (min, max) can only be used with number type`}).check(e=>{let t=e.value;t.variants?(t.type&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'type' must be absent`,input:t,path:[]}),t.array&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'array' must be absent`,input:t,path:[]}),t.properties&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'properties' must be absent`,input:t,path:[]}),t.oneOf&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'oneOf' must be absent`,input:t,path:[]}),t.rules&&e.issues.push({code:`custom`,message:`when 'variants' is present, 'rules' must be absent — define rules inside each variant instead`,input:t,path:[]})):t.type||e.issues.push({code:`custom`,message:`'type' is required when 'variants' is absent`,input:t,path:[]})}),ee=t.z.object({exampleDescription:t.z.string().optional().meta({description:`Explains what this usage example demonstrates.`})}).catchall(t.z.unknown()),I=(0,t.zStrictObject)({functionName:t.z.string().meta({description:`Name of the step function to execute.`}),version:t.z.string().optional().meta({description:`Version of the step function to use.`}),parameters:t.z.record(t.z.string(),t.z.unknown()).meta({description:`Arguments passed to the step function.`})}),L=t.z.union([t.z.boolean(),t.z.literal(`break`)]).optional(),R=(0,t.zStrictObject)({stepId:t.z.string().meta({description:`Identifier for this step, used to reference its output.`}),description:t.z.string().meta({description:`Explains what this step does.`}),stepFunction:I.meta({description:`Step function executed by this step.`}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether this step runs.`}),onConditionError:L.meta({description:"How to behave when the condition expression errors: `false` (default) skips the step, `true` runs it anyway, and `break` halts the action."}),ignoreError:t.z.boolean().optional().meta({description:`Whether a failure in this step is ignored so execution continues.`})}),z=(0,t.zStrictObject)({stepId:t.z.string().meta({description:`Identifier for this step, used to reference its output.`}),description:t.z.string().meta({description:`Explains what this step does.`}),iterator:t.z.string().meta({description:"Expression that produces the array this step loops over. The step function(s) run once per item until the array is exhausted, halting early if an item fails and `ignoreError` is not set."}),stepFunction:I.optional().meta({description:"Step function run for each iterated item. Provide this or `stepFunctions`, not both."}),stepFunctions:I.array().optional().meta({description:"Step functions run in sequence for each iterated item. Provide this or `stepFunction`, not both."}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether this step runs.`}),onConditionError:L.meta({description:"How to behave when the condition expression errors: `false` (default) skips the step, `true` runs it anyway, and `break` halts the action."}),ignoreError:t.z.boolean().optional().meta({description:`Whether a failure in this step is ignored so execution continues.`})}).refine(e=>e.stepFunction!==void 0&&e.stepFunctions===void 0||e.stepFunction===void 0&&e.stepFunctions!==void 0,{message:`Exactly one of 'stepFunction' or 'stepFunctions' must be provided, not both`}),B=(0,t.zStrictObject)({allowed:t.z.boolean().meta({description:`Whether Data Sync is enabled for this action.`}),indexField:t.z.string().or(t.z.string().array()).meta({description:`Field or fields forming each record's primary key during sync. Must uniquely identify each record; a value shared across records collapses them and a record missing it is dropped.`}),dataKey:t.z.string().optional().meta({description:`Path within the step output to the records array, used when the action returns them in a single call rather than paginating.`}),pagination:y.optional().meta({description:`Pagination strategy used while syncing.`}),incremental:S.optional().meta({description:`Change-tracking configuration for incremental syncs.`}),maxPages:t.z.number().int().positive().optional().meta({description:`Maximum number of pages fetched in a single sync run.`}),maxDurationMinutes:t.z.number().int().positive().optional().meta({description:`Maximum time a single sync run may take.`})}),bareJexlMessage=e=>`${e} ${s.BARE_JEXL_REQUIREMENT}`,V=(0,t.zStrictObject)({when:t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`when`)}).meta({description:`JEXL expression evaluated against the incoming request. This rule is selected when the expression returns anything other than null, false, or undefined.`}),then:(0,t.zStrictObject)({action:t.z.string().meta({description:`Event action id invoked when the rule matches.`}),input:t.z.record(t.z.string(),t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`input`)})).optional().meta({description:`JEXL expressions evaluated against the incoming request whose results become the invoked action's input.`})}).meta({description:`Action to invoke when the rule matches.`})}),H=(0,t.zStrictObject)({delivery:V.array().optional().meta({description:"Rules matched against the whole delivery payload, rather than the individual events `itemsPath` splits it into. The first match short-circuits, so the per-event `rules` are skipped."}),itemsPath:t.z.string().trim().min(1).refine(s.isBareJexl,{message:bareJexlMessage(`itemsPath`)}).optional().meta({description:"JEXL expression that splits a batched delivery payload into individual events, so each is routed on its own through `rules`. When omitted, the whole payload is treated as a single event."}),rules:V.array().meta({description:"Rules matched in order against each individual event, where the first match maps it to an event action. Skipped when a `delivery` rule matches."})}),U=(0,t.zStrictObject)({actionId:t.z.string().meta({description:`Identifier for the action, prefixed with the connector key to form its MCP tool name.`,impact:[`mcp`,`runtime`]}),categories:t.z.string().array().meta({description:`Business-domain classifications used for filtering the action.`,impact:[`ui`]}),actionType:t.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`event`,`unknown`]).meta({description:`Operation kind the engine treats this action as.`,impact:[`mcp`,`runtime`]}),effects:t.z.array(t.z.enum([`read`,`write`,`delete`,`search`,`execute`])).optional().meta({description:`Semantic effects the action performs, used for MCP annotations and dashboard filtering.`,impact:[`ui`,`mcp`]}),annotations:(0,t.zStrictObject)({title:t.z.string().optional().meta({description:`Human-readable title exposed to MCP clients.`}),readOnlyHint:t.z.boolean().optional().meta({description:`Whether the action only reads data.`}),destructiveHint:t.z.boolean().optional().meta({description:`Whether the action may delete or overwrite data.`}),idempotentHint:t.z.boolean().optional().meta({description:`Whether repeating the action has no additional effect.`}),openWorldHint:t.z.boolean().optional().meta({description:`Whether the action interacts with an open, external world.`})}).optional().meta({description:"Explicit MCP tool-annotation overrides. Any field set here wins over the hint derived from `effects`."}),executionMode:t.z.enum(s.ExecutionModes).optional().meta({description:"Whether the action runs synchronously or is dispatched to an async workflow. An action with a `browser_use` step must be `async`.",impact:[`runtime`]}),schema:t.z.string().optional().meta({description:`Name of the output schema the action conforms to.`,impact:[`mcp`,`runtime`]}),schemaType:t.z.enum([`native`,`unified`]).optional().default(`native`).meta({description:`Whether the output follows the native provider shape or the unified StackOne schema.`,impact:[`mcp`,`runtime`]}),entrypointUrl:t.z.string().optional().meta({description:"URL path of the action's primary request. Paired with `entrypointHttpMethod` to form the action key such as `GET /employees`, and used as the request log URL.",impact:[`runtime`]}),entrypointHttpMethod:t.z.string().optional().meta({description:`HTTP method of the primary request.`,impact:[`runtime`]}),label:t.z.string().meta({description:`Human-readable display name for the action.`,impact:[`ui`]}),description:t.z.string().meta({description:`Short description shown in the UI and MCP tool declarations.`,impact:[`ui`,`mcp`]}),details:t.z.string().optional().meta({description:"Extended context about the action for agents and developers. Used as the MCP tool description in place of `description` when set.",impact:[`mcp`]}),examples:ee.array().optional().meta({description:"Example input values for the action, each optionally labeled with `exampleDescription`."}),tags:t.z.string().array().optional().meta({description:`Free-form tags for grouping and filtering the action.`,impact:[`ui`,`mcp`]}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Maturity level of the action.`,impact:[`ui`,`mcp`]}),resources:t.z.string().optional().meta({description:`URL to provider documentation for this action.`,impact:[`ui`]}),responses:(0,t.zStrictObject)({statusCode:t.z.number().meta({description:`HTTP status code being documented.`}),description:t.z.string().meta({description:`What this response status means.`})}).array().optional().meta({description:`Documented HTTP responses the action can return.`}),requiredScopes:t.z.string().optional().meta({description:"Permission scopes required to run the action. Deprecated; use `authRequirements`."}),authRequirements:t.z.record(t.z.string(),t.z.string().array()).optional().meta({description:"Per-authentication-method scopes required to run the action. Supersedes the deprecated `requiredScopes`."}),inputs:F.array().optional().meta({description:`Parameters the action accepts, forming its tool input schema.`}),validationRules:M.array().optional().meta({description:`Cross-field validation rules applied to the action inputs.`}),cursor:(0,t.zStrictObject)({enabled:t.z.boolean().meta({description:`Whether cursor pagination is enabled. Only applies to list actions and has no effect on others.`}),pageSize:t.z.number().meta({description:`Number of records requested per page.`})}).optional().meta({description:`Engine-managed cursor pagination configuration.`}),compositeIdentifiers:(0,t.zStrictObject)({enabled:t.z.boolean().meta({description:`Whether composite identifiers are built for records.`}),version:t.z.number().optional().meta({description:`Version of the composite identifier encoding.`}),fields:(0,t.zStrictObject)({targetFieldKey:t.z.string().meta({description:`Key the composite identifier is written to.`}),remote:t.z.string().optional().meta({description:`Provider field the identifier component is read from.`}),components:t.z.string().array().meta({description:`Ordered output field keys whose values combine into the identifier.`})}).array().optional().meta({description:`Field mappings that make up each composite identifier.`})}).optional().meta({description:`Configuration for building a record id from multiple provider fields.`}),fieldConfigs:O.array().optional().meta({description:`Field-level mapping and typing configuration for the result.`}),steps:t.z.union([R,z]).array().meta({description:`Ordered steps executed to carry out the action. A single step runs one step function, and an iterator step runs step functions over each item of an array.`}),result:t.z.string().or(t.z.record(t.z.string(),t.z.unknown())).optional().meta({description:`Data returned to the caller, given as an expression or a map of output keys to expressions.`}),dataSync:B.optional().meta({description:`Data Sync configuration for bulk syncing this action's records.`}),providerEvents:t.z.string().array().nonempty().optional().meta({description:`Provider event names this action handles.`,impact:[`runtime`]}),prerequisiteActions:t.z.string().array().optional().meta({description:`Action ids this action declares as dependencies.`}),userScoped:t.z.boolean().or((0,t.zStrictObject)({identity:t.z.string().array().nonempty().meta({description:"JSONPath expressions evaluated against each record in the response's `data`. A record is kept only when one of them resolves to the caller's email; the engine drops every other record and refuses a single record that is not the caller's."})})).optional().meta({description:"The action answers for the acting user, filtering the provider by `$.user`. The engine refuses the call when there is no acting user email. The object form also checks each returned record against the caller.",impact:[`runtime`]})}),stepUsesBrowserUse=e=>`stepFunction`in e&&e.stepFunction?.functionName===s.StepFunctionName.BROWSER_USE?!0:`stepFunctions`in e&&e.stepFunctions?e.stepFunctions.some(e=>e.functionName===s.StepFunctionName.BROWSER_USE):!1,stepDownloadsFile=e=>`stepFunction`in e&&e.stepFunction?.functionName===s.StepFunctionName.DOWNLOAD_FILE||`stepFunctions`in e&&(e.stepFunctions??[]).some(e=>e.functionName===s.StepFunctionName.DOWNLOAD_FILE),W=U.superRefine((e,n)=>{e.executionMode!==`async`&&e.steps.some(stepUsesBrowserUse)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`Actions containing a 'browser_use' step must declare executionMode: 'async' so they are dispatched to the Temporal workflow runtime`,path:[`executionMode`]})}).superRefine((e,n)=>{(0,t.isObject)(e.userScoped)&&e.userScoped.identity.forEach((e,r)=>{e.startsWith(`$.`)||n.addIssue({code:t.z.ZodIssueCode.custom,message:`userScoped.identity entry '${e}' must be a JSONPath expression starting with $.`,path:[`userScoped`,`identity`,r]})})}).superRefine((e,n)=>{!(0,t.isObject)(e.userScoped)||!e.steps.some(stepDownloadsFile)||n.addIssue({code:t.z.ZodIssueCode.custom,message:`userScoped.identity cannot be used on an action that downloads a file: a stream has no records to check`,path:[`userScoped`,`identity`]})}).superRefine((e,n)=>{!e.userScoped||e.dataSync?.allowed!==!0||n.addIssue({code:t.z.ZodIssueCode.custom,message:`A userScoped action cannot allow dataSync: a sync has no acting user to scope it by`,path:[`dataSync`,`allowed`]})}).superRefine((e,n)=>{let r=e.prerequisiteActions;if(!r)return;r.includes(e.actionId)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`prerequisiteActions contains a self-reference to '${e.actionId}'`,path:[`prerequisiteActions`]});let i=new Set;for(let e of r)i.has(e)&&n.addIssue({code:t.z.ZodIssueCode.custom,message:`prerequisiteActions contains duplicate entry '${e}'`,path:[`prerequisiteActions`]}),i.add(e)}),te=(0,t.zStrictObject)({schedule:t.z.string().optional().meta({description:`Cron expression for proactively refreshing credentials.`}),action:U.extend({actionType:t.z.literal(`refresh_token`).meta({description:"Operation kind for this action, always `refresh_token`."})}).meta({description:`Action executed to refresh the credentials.`})}),ne=(0,t.zStrictObject)({mainRatelimit:t.z.number().meta({description:`Maximum requests per second for each linked account, across all of the connector's endpoints.`}),subPools:t.z.array((0,t.zStrictObject)({subPoolKey:t.z.string().meta({description:`Identifier for this rate-limit sub-pool.`}),urlPattern:t.z.string().meta({description:`URL pattern the sub-pool's limit applies to.`}),rateLimit:t.z.number().meta({description:`Maximum requests per second for the matched URLs.`})})).optional().meta({description:`Per-URL-pattern rate limit overrides.`}),mappedRateLimitErrors:t.z.array((0,t.zStrictObject)({errorStatus:t.z.number().meta({description:`HTTP status code indicating a rate-limit error.`}),errorMessage:t.z.string().meta({description:`Provider error message identifying a rate-limit error.`}),errorMessagePath:t.z.string().optional().meta({description:`Path to the error message in the response body.`}),retryAfterPath:t.z.string().optional().meta({description:`Path to the retry-after value within the response headers, not the body.`}),retryAfterUnit:t.z.union([t.z.literal(`seconds`),t.z.literal(`milliseconds`),t.z.literal(`date`)]).optional().meta({description:`Unit the retry-after value is expressed in.`}),retryAfterValue:t.z.number().optional().meta({description:`Fixed delay to wait before retrying.`})})).optional().meta({description:`Provider responses that should be treated as rate-limit signals.`})}),re=(0,t.zStrictObject)({mainMaxConcurrency:t.z.number().meta({description:`Maximum number of concurrent in-flight requests per linked account.`}),subPools:t.z.array((0,t.zStrictObject)({subPoolKey:t.z.string().meta({description:`Identifier for this concurrency sub-pool.`}),urlPattern:t.z.string().meta({description:`URL pattern the sub-pool's limit applies to.`}),maxConcurrency:t.z.number().meta({description:`Maximum concurrent requests for the matched URLs.`})})).optional().meta({description:`Per-URL-pattern concurrency overrides.`})}),ie=(0,t.zStrictObject)({src:t.z.string().meta({description:`Image URL or a path relative to the connector.`}),alt:t.z.string().meta({description:`Alternative text describing the image.`})}),ae=(0,t.zStrictObject)({title:t.z.string().meta({description:`Heading for this guide step.`}),content:t.z.string().meta({description:`Body text describing what the user should do.`}),list:t.z.string().array().optional().meta({description:`Ordered items elaborating the step.`}),image:ie.optional().meta({description:`Illustrative image for the step.`}),displayScopes:t.z.boolean().optional().meta({description:`Whether the step shows badges for the actions its scopes unlock.`}),applicableScopes:t.z.string().optional().meta({description:`Scope names for which this step is shown. Space-separated, with any name that contains spaces wrapped in double quotes.`})}),oe=(0,t.zStrictObject)({title:t.z.string().meta({description:`Heading for this guide section.`}),content:t.z.string().meta({description:`Introductory text for the section.`}),list:t.z.string().array().optional().meta({description:`Ordered items elaborating the section.`}),image:ie.optional().meta({description:`Illustrative image for the section.`}),steps:ae.array().optional().meta({description:`Ordered steps making up the section.`}),applicableScopes:t.z.string().optional().meta({description:`Scope names for which this section is shown. Space-separated, with any name that contains spaces wrapped in double quotes.`})}),G=(0,t.zStrictObject)({warning:t.z.string().optional().meta({description:`Cautionary note shown at the top of the guide.`}),sections:oe.array().meta({description:`Ordered sections making up the guide.`})}),se=(0,t.zStrictObject)({config:G.optional().meta({description:`Guide for the credentials end-users enter per connection.`}),setup:G.optional().meta({description:`Guide for the credentials your team registers once.`})}),ce=(0,t.zStrictObject)({key:t.z.string().meta({description:`Identifier for the notice.`}),type:t.z.enum([`warning`,`info`]).default(`info`).meta({description:`Visual style of the notice.`}),description:t.z.string().meta({description:`Text shown in the notice.`}),position:t.z.enum([`top`,`bottom`]).default(`top`).meta({description:`Whether the notice appears above or below the fields.`}),anchor:t.z.string().optional().meta({description:`Field key the notice is shown above. Only valid when position is top.`})}).refine(e=>!(e.anchor&&e.position===`bottom`),{message:`anchor cannot be used with position: 'bottom'`,path:[`anchor`]}),le=(0,t.zStrictObject)({certs:t.z.string().array().optional().meta({description:`Client certificates used for mutual-TLS.`}),keys:t.z.string().array().optional().meta({description:`Private keys used for mutual-TLS.`})}).optional(),K=(0,t.zStrictObject)({label:t.z.string().meta({description:`Display name for this authentication method.`,impact:[`ui`]}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Maturity level of this authentication method. Defaults to the highest stage among the actions and events it can run.`,impact:[`ui`]}),authorization:s.AUTHORIZATION_SCHEMA.meta({description:`Runtime authorization strategy applied to outgoing requests.`}),certificates:le.meta({description:`Mutual-TLS certificates and keys for this method.`}),requiredScopes:t.z.string().optional().meta({description:`Scope names required by this authentication method. Space-separated, with any name that contains spaces wrapped in double quotes.`}),environments:(0,t.zStrictObject)({key:t.z.string().meta({description:`Identifier stored for the selected environment.`}),name:t.z.string().meta({description:`Human-readable environment name.`})}).array().meta({description:`Deployment targets selectable for this method.`}),support:(0,t.zStrictObject)({link:t.z.string().optional().meta({description:`URL to external setup documentation. Defaults to the generated connector guide on docs.stackone.com when omitted.`}),description:t.z.string().optional().meta({description:`Help text guiding the user through connecting.`}),guides:se.optional().meta({description:`Step-by-step connection guides.`})}).optional().meta({description:`Help resources shown while connecting with this method.`}),configFields:D.array().optional().meta({description:`Credentials the end-user enters when linking an account.`}),configNotices:ce.array().optional().meta({description:`Callouts shown while entering config fields.`}),setupFields:D.array().optional().meta({description:`Credentials entered when creating a Connector Profile.`}),setupNotices:ce.array().optional().meta({description:`Callouts shown while entering setup fields.`}),refreshAuthentication:te.optional().meta({description:`Configuration for refreshing expired credentials.`}),testActions:(0,t.zStrictObject)({action:t.z.string().or(W).meta({description:`Action id or definition executed to test the connection.`}),condition:t.z.string().optional().meta({description:`JEXL expression gating whether the test action runs.`}),required:t.z.boolean().default(!0).meta({description:`Currently not in use.`})}).array().optional().meta({description:`Actions run to validate a connection after authentication.`})}),ue=K.extend({type:t.z.literal(`oauth2`).meta({description:`Selects the OAuth 2.0 authentication method.`}),grantType:t.z.enum([`authorization_code`,`client_credentials`]).default(`authorization_code`).meta({description:`OAuth grant flow used to obtain tokens.`})}),de=K.extend({type:t.z.literal(`custom`).meta({description:`Selects the custom authentication method.`})}),fe=K.extend({type:t.z.literal(`oidc`).meta({description:`Selects the OpenID Connect authentication method.`})}),pe=(0,t.zStrictObject)({serverUrl:t.z.string().optional().meta({description:`MCP server URL the connect flow authorizes against.`}),discovery:t.z.boolean().default(!0).meta({description:`Whether OAuth authorization-server metadata is discovered automatically.`}),clientRegistration:t.z.enum([`cimd`,`dcr`]).default(`cimd`).meta({description:`Client registration mechanism used with the MCP server.`}),scopes:t.z.string().array().optional().meta({description:`OAuth scopes requested during the MCP authorization flow.`})}),me=K.extend({type:t.z.literal(`mcp`).meta({description:`Selects the remote MCP server authentication method.`}),authorizationFlow:pe.optional().meta({description:`MCP OAuth authorization flow; static credentials are used when omitted.`})}),he=t.z.discriminatedUnion(`type`,[ue,de,fe,me]),collectAuthenticationKeyIssues=e=>{let t=new Set,n=[];for(let[r,i]of e.entries()){let e=Object.keys(i);e.length!==1&&n.push({message:`Each authentication configuration must use exactly one key, but this one has ${e.length}.`,path:[r]});for(let i of e)t.has(i)?n.push({message:`Duplicate authentication key '${i}'. Each authentication configuration must use a unique key.`,path:[r,i]}):t.add(i)}return n},ge=t.z.record(t.z.string(),he).array().check(e=>{for(let t of collectAuthenticationKeyIssues(e.value))e.issues.push({code:`custom`,input:e.value,message:t.message,path:t.path})}),q=(0,t.zStrictObject)({steps:t.z.union([R,z]).array().min(1).meta({description:`Ordered steps performed in this webhook phase.`}),result:t.z.string().optional().meta({description:`Value produced by the phase, such as the created webhook id.`})}),_e=q.extend({result:t.z.string().meta({description:"Expression selecting the value this phase produces, such as the created receiver's remote id (e.g. `$.steps.create.output.data.id`), which later phases reference as `${inputs.remoteId}`."})}),phaseContainsTemplate=(e,t)=>{let containsTemplate=e=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.some(containsTemplate):typeof e==`object`&&e?Object.values(e).some(containsTemplate):!1;return e.steps.some(e=>`stepFunction`in e&&e.stepFunction?containsTemplate(e.stepFunction.parameters):`stepFunctions`in e&&e.stepFunctions?e.stepFunctions.some(e=>containsTemplate(e.parameters)):!1)},ve=(0,t.zStrictObject)({creation:_e.meta({description:`Phase that registers the webhook receiver.`}),activation:q.optional().meta({description:"Optional phase that activates the receiver after creation. Must reference `${inputs.remoteId}` in at least one step parameter."}),deletion:q.meta({description:"Phase that removes the webhook receiver. Must reference `${inputs.remoteId}` in at least one step parameter."}),isConsolidated:t.z.boolean().optional().default(!1).meta({description:`Whether one receiver handles all events rather than one per event.`})}).superRefine((e,n)=>{e.activation&&!phaseContainsTemplate(e.activation,"${inputs.remoteId}")&&n.addIssue({code:t.z.ZodIssueCode.custom,message:"Activation phase must reference '${inputs.remoteId}' in at least one step parameter",path:[`activation`]}),phaseContainsTemplate(e.deletion,"${inputs.remoteId}")||n.addIssue({code:t.z.ZodIssueCode.custom,message:"Deletion phase must reference '${inputs.remoteId}' in at least one step parameter",path:[`deletion`]})}),ye=(0,t.zStrictObject)({setup:G.optional().meta({description:`Guide for configuring webhooks in the provider UI.`})}),be=(0,t.zStrictObject)({setup:ve.optional().meta({description:`Programmatic webhook lifecycle configuration.`}),guides:ye.optional().meta({description:`Manual webhook setup guides.`}),actions:U.extend({actionType:t.z.literal(`event`).meta({description:`Marks the action as an event handler.`}),requiresManualSetup:t.z.boolean().optional().meta({description:"Whether the webhook must be configured manually in the provider UI. Pair with `guides.setup` to document that setup."})}).array().optional().meta({description:`Event actions that process incoming provider events.`}),router:H.optional().meta({description:`Rules mapping incoming payloads to event actions.`}),externalAccountIdExtractor:U.extend({actionType:t.z.literal(`custom`).meta({description:`Marks the extractor as a custom action.`}),result:t.z.string().min(1).meta({description:`Expression evaluated against the incoming payload to extract the provider's external account identifier.`})}).optional().meta({description:"Action that reads the provider's external account identifier from an incoming payload so the event can be matched to a linked account. It is a `custom` action with a required `result`."})}),J=2e3,xe=(0,t.zStrictObject)({StackOne:t.z.string().meta({description:"Connector schema version, set to `1.0.0`."}),info:(0,t.zStrictObject)({title:t.z.string().meta({description:`Human-readable provider name shown in Hub and Dashboard.`,impact:[`ui`]}),version:t.z.string().meta({description:`Connector version following semantic versioning.`,impact:[`ui`,`runtime`]}),key:t.z.string().meta({description:`Unique lowercase identifier for the connector.`,impact:[`ui`,`mcp`,`runtime`]}),assets:(0,t.zStrictObject)({icon:t.z.string().meta({description:`URL to the provider logo.`,impact:[`ui`]})}).meta({description:`Visual assets for the connector.`}),description:t.z.string().meta({description:`Brief one-line summary of the connector.`,impact:[`ui`,`mcp`]}),details:t.z.string().optional().meta({description:`Extended description of capabilities and limitations.`,impact:[`ui`,`mcp`]}),changelog:(0,t.zStrictObject)({summary:t.z.string().meta({description:`Human-readable summary of the changes in this version.`}),labels:t.z.string().array().optional().meta({description:`Tags categorizing the changelog entry for filtering.`})}).optional().meta({description:`Description of what changed in this version.`})}).meta({description:`Connector metadata.`}),resources:t.z.string().optional().meta({description:`Source of information for the connector, usually a URL to the provider's documentation.`}),documentation:(0,t.zStrictObject)({references:(0,t.zStrictObject)({title:t.z.string().meta({description:`Link text for the reference.`}),url:t.z.string().meta({description:`URL of the referenced document.`}),description:t.z.string().optional().meta({description:`Explains what the reference covers.`})}).array().meta({description:`External documentation links.`})}).optional().meta({description:`External documentation links for the connector.`}),baseUrl:t.z.string().meta({description:`Root URL for all API requests. Supports expressions.`,impact:[`runtime`]}),scopeDefinitions:t.z.record(t.z.string(),(0,t.zStrictObject)({description:t.z.string().meta({description:`Explains what this scope grants.`}),includes:t.z.string().optional().meta({description:`Another scope this scope implies.`})})).optional().meta({description:`Requirements actions can depend on, keyed by name, such as OAuth scopes, pricing tiers, or feature flags.`}),authentication:ge.optional().meta({description:`Authentication methods the connector supports.`}),actions:W.array().optional().meta({description:`Actions the connector exposes.`}),events:be.optional().meta({description:`Event and webhook configuration for the connector.`}),rateLimit:ne.optional().meta({description:`Request rate-limit configuration for the connector.`}),concurrency:re.optional().meta({description:`Request concurrency configuration for the connector.`}),releaseStage:t.z.enum(s.ReleaseStages).optional().meta({description:`Default maturity level inherited by actions, events and authentication methods that do not declare their own. The stage of the connector itself is computed from theirs, never authored here.`,impact:[`ui`]}),forkedFrom:t.z.string().optional().meta({description:`Key of the connector this one was forked from. Not currently in use.`}),mcp:(0,t.zStrictObject)({instructions:t.z.string().max(J).optional().meta({description:`Guidance text surfaced to MCP clients (max 2000 characters).`,impact:[`mcp`]})}).optional().meta({description:`MCP-specific configuration for the connector.`})}).strict().superRefine((e,n)=>{let r=e.actions;if(!r)return;let i=new Set(r.map(e=>e.actionId));for(let e=0;e<r.length;e++){let a=r[e];if(a.prerequisiteActions)for(let r of a.prerequisiteActions)i.has(r)||n.addIssue({code:t.z.ZodIssueCode.custom,message:`Action '${a.actionId}' has prerequisiteActions entry '${r}' which does not match any actionId in this connector`,path:[`actions`,e,`prerequisiteActions`]})}let a=new Map;for(let e of r)e.prerequisiteActions?.length&&a.set(e.actionId,e.prerequisiteActions);let o=new Map(r.map((e,t)=>[e.actionId,t])),s=new Set,c=new Set,dfs=(e,r)=>{for(let i of a.get(e)??[])if(r.includes(i)){let e=r.slice(r.indexOf(i));if(e.length<2)continue;let a=[...e].sort().join(`,`);c.has(a)||(c.add(a),n.addIssue({code:t.z.ZodIssueCode.custom,message:`Circular prerequisiteActions dependency: ${e.join(` → `)} → ${e[0]}`,path:[`actions`,o.get(e[0])??0,`prerequisiteActions`]}))}else s.has(i)||dfs(i,[...r,i]);s.add(e)};for(let e of r)s.has(e.actionId)||dfs(e.actionId,[e.actionId])});var Y=class InternalConnectSDKError extends Error{constructor(e,t){super(t),this.name=`InternalConnectSDKError`,this.errorType=e,Error.captureStackTrace&&Error.captureStackTrace(this,InternalConnectSDKError)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},InvalidYamlFileError=class extends Y{constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},SchemaValidationError=class extends Y{constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}};const formatStepLocation=e=>e.kind===`action`?`action '${e.actionId}'`:`webhook setup phase '${e.phase}'`;var InvalidStepFunctionError=class extends Y{constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the ${formatStepLocation(e)}.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.location=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},InvalidStepFunctionParamsError=class extends Y{constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the ${formatStepLocation(e)}.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.location=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}},InvalidActionExampleError=class extends Y{constructor(e,t,n){let r=`Invalid example ${t} for action '${e}': ${n.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `)}`;super(`INVALID_ACTION_EXAMPLE`,r),this.name=`InvalidActionExampleError`,this.actionId=e,this.exampleIndex=t,this.issues=n}},InvalidEnumReferenceError=class extends Y{constructor(e,t,n){let r=`Invalid enum reference "${n}" in action "${e}", input "${t}". Check that the enum is defined in INPUT_ENUM_REGISTRY.`;super(`INVALID_ENUM_REFERENCE`,r),this.name=`InvalidEnumReferenceError`,this.actionId=e,this.inputName=t,this.enumRef=n}},InvalidEventRouterReferenceError=class extends Y{constructor(e,t,n){let r=`Event router ${n} ${t} references unknown event action "${e}". Check that the operation is defined in events.actions.`;super(`INVALID_EVENT_ROUTER_REFERENCE`,r),this.name=`InvalidEventRouterReferenceError`,this.operation=e,this.ruleIndex=t,this.ruleKind=n}},InvalidEventRouterActionPrefixError=class extends Y{constructor(e,t,n,r){let i=`Event router ${r} ${t} action "${e}" must start with the connector key prefix "${n}_".`;super(`INVALID_EVENT_ROUTER_ACTION_PREFIX`,i),this.name=`InvalidEventRouterActionPrefixError`,this.operation=e,this.ruleIndex=t,this.connectorKey=n,this.ruleKind=r}},UnknownCallActionTargetError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which is not defined in this connector.`;super(`UNKNOWN_CALL_ACTION_TARGET`,r),this.name=`UnknownCallActionTargetError`,this.location=e,this.stepId=t,this.targetActionId=n}},SelfReferencingActionError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} calls its own action "${n}". An action cannot call itself.`;super(`SELF_REFERENCING_ACTION`,r),this.name=`SelfReferencingActionError`,this.location=e,this.stepId=t,this.actionId=n}},CircularActionReferenceError=class extends Y{constructor(e,t,n){let r=`Step '${t}' in ${formatStepLocation(e)} closes a call_action cycle: ${n.join(` -> `)}. Actions cannot call each other in a loop.`;super(`CIRCULAR_ACTION_REFERENCE`,r),this.name=`CircularActionReferenceError`,this.location=e,this.stepId=t,this.chain=n}},IncompatibleCallActionAuthError=class extends Y{constructor(e,t,n,r,i){let a=r.join(`, `),o=i?`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which does not support the authentication ${i.length===1?`config`:`configs`} ${i.map(e=>`"${e}"`).join(`, `)} its caller declares. "${n}" supports: ${a}.`:`Step '${t}' in ${formatStepLocation(e)} calls action "${n}", which is restricted to the authentication configs ${a}, but its caller declares no authRequirements and so runs on all of them. Declare authRequirements on the caller that "${n}" supports.`;super(`INCOMPATIBLE_CALL_ACTION_AUTH`,o),this.name=`IncompatibleCallActionAuthError`,this.location=e,this.stepId=t,this.calleeActionId=n,this.calleeAuthKeys=r,this.callerAuthKeys=i}},MissingScopeDefinitionError=class extends Y{constructor(e){super(`MISSING_SCOPE_DEFINITION`,`Missing scope definition. Check that the scope is defined in the scope definitions.`),this.name=`MissingScopeDefinitionError`,this.issues=e}},InvalidAuthRequirementsError=class extends Y{constructor(e){super(`INVALID_AUTH_REQUIREMENTS`,`Invalid authRequirements. Verify auth config keys are valid and not used alongside requiredScopes.`),this.name=`InvalidAuthRequirementsError`,this.issues=e}};const callEdgesOf=(e,t)=>{let n=[];for(let[r,i]of Object.entries(e))for(let e of(0,s.stepFunctionsOf)(i)){if(e.functionName!==s.StepFunctionName.CALL_ACTION)continue;let i=e.params?.actionId;typeof i==`string`&&n.push({stepId:r,targetActionId:buildActionId(t,i),yamlTargetId:i})}return n},incompatibleAuthKeys=(e,n)=>{if((0,t.isMissing)(n.authRequirements))return;let r=new Set(Object.keys(n.authRequirements));if((0,t.isMissing)(e.authRequirements))return[];let i=Object.keys(e.authRequirements).filter(e=>!r.has(e));return i.length>0?i:void 0},findCycle=e=>{let t=new Map;for(let n of e.keys()){if(t.has(n))continue;let r=[n],i=[{actionId:n,nextEdge:0}];for(t.set(n,`onPath`);i.length>0;){let n=i[i.length-1],a=e.get(n.actionId)??[];if(n.nextEdge>=a.length){t.set(n.actionId,`settled`),i.pop(),r.pop();continue}let o=a[n.nextEdge];if(n.nextEdge+=1,!e.has(o.targetActionId))continue;let s=t.get(o.targetActionId);if(s===`onPath`){let e=r.indexOf(o.targetActionId);return{ownerActionId:n.actionId,stepId:o.stepId,chain:[...r.slice(e),o.targetActionId]}}s!==`settled`&&(t.set(o.targetActionId,`onPath`),r.push(o.targetActionId),i.push({actionId:o.targetActionId,nextEdge:0}))}}},validateCallActionGraph=({connectorKey:e,actions:t,yamlActionIds:n=new Map,callOnlySites:r=[]})=>{let displayId=e=>n.get(e)??e,i=new Map(Object.values(t).map(t=>[t.id,callEdgesOf(t.steps,e)])),a=r.map(t=>({location:t.location,edges:callEdgesOf(t.steps,e)}));if(!([...i.values()].some(e=>e.length>0)||a.some(({edges:e})=>e.length>0)))return;for(let e of Object.values(t)){let n={kind:`action`,actionId:displayId(e.id)};for(let r of i.get(e.id)??[]){if(!(r.targetActionId in t))throw new UnknownCallActionTargetError(n,r.stepId,r.yamlTargetId);if(r.targetActionId===e.id)throw new SelfReferencingActionError(n,r.stepId,displayId(e.id));let i=t[r.targetActionId],a=incompatibleAuthKeys(e,i);if(a)throw new IncompatibleCallActionAuthError(n,r.stepId,displayId(i.id),Object.keys(i.authRequirements??{}),a.length>0?a:void 0)}}for(let{location:e,edges:n}of a)for(let r of n)if(!(r.targetActionId in t))throw new UnknownCallActionTargetError(e,r.stepId,r.yamlTargetId);let o=findCycle(i);if(o)throw new CircularActionReferenceError({kind:`action`,actionId:displayId(o.ownerActionId)},o.stepId,o.chain.map(displayId))},isCustomOwner=e=>(0,t.notMissing)(e)&&e!==`stackone`,isCustomConnector=e=>isCustomOwner(e.owner),Se=[`ga`,`preview`,`beta`,`internal`,`deprecated`],Ce=`preview`,highestReleaseStage=e=>e.reduce((e,n)=>(0,t.isMissing)(e)||Se.indexOf(n)<Se.indexOf(e)?n:e,void 0),computeActionStages=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,n.releaseStage??t])),reachableStages=(e,t,n)=>Object.entries(t??{}).filter(([,t])=>isActionAvailableForAuthType(t,e)).map(([e])=>n[e]),authTypeReleaseStage=e=>Object.values(e).map(e=>e.releaseStage).find(t.notMissing),computeReleaseStages=e=>{let t=e.releaseStage??Ce,n=computeActionStages(e.actions,t),r=computeActionStages(e.events?.actions,t),i=Object.fromEntries(Object.entries(e.authentication??{}).map(([i,a])=>[i,authTypeReleaseStage(a)??highestReleaseStage([...reachableStages(i,e.actions,n),...reachableStages(i,e.events?.actions,r)])??t]));return{connector:Object.values(i).includes(`ga`)?`ga`:t,actions:n,eventActions:r,authTypes:i}},stampActionStages=(e,t)=>{for(let[n,r]of Object.entries(e??{}))r.releaseStage=t[n]},applyComputedReleaseStages=e=>{if(isCustomConnector(e))return;let t=computeReleaseStages(e);stampActionStages(e.actions,t.actions),stampActionStages(e.events?.actions,t.eventActions);for(let[n,r]of Object.entries(e.authentication??{}))for(let e of Object.values(r))e.releaseStage=t.authTypes[n];e.releaseStage=t.connector},connectorStage=e=>e.releaseStage??Ce,isConnectorReleased=(e,t=[])=>isCustomConnector(e)||t.includes(connectorStage(e)),keepEntries=(e,t)=>Object.fromEntries(Object.entries(e??{}).filter(([e,n])=>t(e,n))),itemId=(e,t)=>t.id??e,buildProfileItems=(e,n)=>Object.entries(e??{}).map(([e,r])=>({id:itemId(e,r),releaseStage:r.releaseStage??n,...(0,t.notMissing)(r.authRequirements)?{authTypes:Object.keys(r.authRequirements)}:{}})),buildReleaseStageProfile=e=>{let t=connectorStage(e);return{releaseStage:t,authTypes:Object.fromEntries(Object.entries(e.authentication??{}).map(([e,n])=>[e,authTypeReleaseStage(n)??t])),actions:buildProfileItems(e.actions,t),eventActions:buildProfileItems(e.events?.actions,t)}},decideReleaseStages=({releaseStage:e,authTypes:n},r,i)=>{let a=Object.keys(n);if(isCustomOwner(r))return{authenticationKeys:new Set(a),isKept:()=>!0};if(!i.includes(e))return;let o=a.filter(e=>i.includes(n[e]));if(a.length>0&&o.length===0)return;let isReachable=e=>a.length===0||(0,t.isMissing)(e)||o.some(t=>e.includes(t));return{authenticationKeys:new Set(o),isKept:e=>i.includes(e.releaseStage)&&isReachable(e.authTypes)}},resolveReleaseStageProfile=(e,n,r=[])=>{let i=decideReleaseStages(e,n,r);if((0,t.isMissing)(i))return;let keptIds=e=>new Set(e.filter(i.isKept).map(e=>e.id));return{actionIds:keptIds(e.actions),eventActionIds:keptIds(e.eventActions),authenticationKeys:i.authenticationKeys}},countItems=e=>[...e.reduce((e,{releaseStage:n,authTypes:r})=>{let i=(0,t.notMissing)(r)?[...r].sort():void 0,a=JSON.stringify([n,i??null]);return e.set(a,{releaseStage:n,...(0,t.notMissing)(i)?{authTypes:i}:{},count:(e.get(a)?.count??0)+1})},new Map).values()],countReleaseStageProfile=e=>({releaseStage:e.releaseStage,authTypes:e.authTypes,actions:countItems(e.actions),eventActions:countItems(e.eventActions)}),resolveReleaseStageCounts=(e,n,r=[])=>{let i=decideReleaseStages(e,n,r);if((0,t.isMissing)(i))return;let keptCount=e=>e.filter(i.isKept).reduce((e,t)=>e+t.count,0);return{actionCount:keptCount(e.actions),eventActionCount:keptCount(e.eventActions),authenticationKeys:i.authenticationKeys}},applyReleaseStageToConnector=(e,n=[])=>{let r=resolveReleaseStageProfile(buildReleaseStageProfile(e),e.owner,n);if((0,t.isMissing)(r))return;let keepResolved=(e,t)=>keepEntries(e,(e,n)=>t.has(itemId(e,n))),i=e.events?.actions,a=e.authentication;return{...e,actions:keepResolved(e.actions,r.actionIds),...(0,t.notMissing)(i)?{events:{...e.events,actions:keepResolved(i,r.eventActionIds)}}:{},...(0,t.notMissing)(a)?{authentication:keepEntries(a,e=>r.authenticationKeys.has(e))}:{}}},formatValidationErrorResponse=e=>({statusCode:400,message:`Invalid request - validation failed`,errors:e.map(e=>({property:e.field,location:e.location,expected:e.expected,received:e.received,message:e.message}))}),getDefaultSuccessActionResponse=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The action was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token action was executed successfully.`};case`test`:return{statusCode:200,description:`The test action was executed successfully.`};case`event`:return{statusCode:200,description:`The event action was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown action type: ${e}`)}},getDefaultErrorActionResponses=()=>({400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}}),toKebabCase=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``),buildSupport=(e,n,r)=>{if((0,t.isMissing)(r))return;if((0,t.notMissing)(r.link))return r;let i=r.guides?.config?.sections,a=toKebabCase(n);return(0,t.notMissing)(i)&&i.length>0&&a!==``?{...r,link:`https://docs.stackone.com/connectors/${e}/guides/link-account/${a}`}:r},connectorUsesCallAction=e=>{let usesIt=e=>(e??[]).some(e=>e.stepFunction?.functionName===s.StepFunctionName.CALL_ACTION||e.stepFunctions?.some(e=>e.functionName===s.StepFunctionName.CALL_ACTION));if((e.actions??[]).some(e=>usesIt(e.steps))||(e.events?.actions??[]).some(e=>usesIt(e.steps))||usesIt(e.events?.externalAccountIdExtractor?.steps))return!0;let n=e.events?.setup;return[n?.creation,n?.activation,n?.deletion].some(e=>usesIt(e?.steps))?!0:(e.authentication??[]).some(e=>Object.values(e??{}).some(e=>(e?.testActions??[]).some(e=>!(0,t.isString)(e.action)&&usesIt(e.action?.steps))||usesIt(e?.refreshAuthentication?.action?.steps)))},buildYamlActionIds=e=>{let n=e.info.key,r=new Map,record=e=>r.set(buildActionId(n,e),e);for(let t of e.actions??[])record(t.actionId);for(let t of e.events?.actions??[])record(t.actionId);return(0,t.notMissing)(e.events?.externalAccountIdExtractor)&&record(e.events.externalAccountIdExtractor.actionId),r},collectCallOnlySites=(e,n,r)=>{let i=[],displayId=e=>n.get(e)??e;for(let t of Object.values(e.events?.actions??{}))i.push({location:{kind:`action`,actionId:displayId(t.id)},steps:t.steps});(0,t.notMissing)(r)&&i.push({location:{kind:`action`,actionId:displayId(r.id)},steps:r.steps});let a=e.events?.setup,o=[[`creation`,a?.creation],[`activation`,a?.activation],[`deletion`,a?.deletion]];for(let[e,n]of o)(0,t.notMissing)(n)&&i.push({location:{kind:`setupPhase`,phase:e},steps:n.steps});for(let n of Object.values(e.authentication??{}))for(let e of Object.values(n)){for(let n of e?.testActions??[])(0,t.isString)(n.action)||i.push({location:{kind:`action`,actionId:displayId(n.action.id)},steps:n.action.steps});let n=e?.refreshAuthentication?.action;(0,t.notMissing)(n)&&i.push({location:{kind:`action`,actionId:displayId(n.id)},steps:n.steps})}return i};function parseYamlConnector(e){try{let n=parseWithSchemaException(xe,(0,o.parse)(e)),r=parseScopeDefinitions(n.scopeDefinitions),i={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,details:n.info.details,changelog:n.info.changelog,resources:n.resources,documentation:n.documentation,rateLimit:n.rateLimit,concurrency:n.concurrency,releaseStage:n.releaseStage,forkedFrom:n.forkedFrom,mcp:n.mcp,scopeDefinitions:r},a=buildAuthenticationFromYaml(n),s={baseUrl:n.baseUrl,authentication:stripAuthenticationSetup(a)},c=buildActionsFromYaml(n,s);validateAuthRequirementsMutualExclusivity(n,c),i.actions=c;let l=buildSyncedActionsFromActions(c);(0,t.notMissing)(l)&&(i.syncedActions=l),hydrateTestActions(n,n.info.key,a,c,s),i.authentication=a,(0,t.notMissing)(c)&&(i.categories=getConnectorCategoriesFromActions(Object.values(c)));let u=buildEventActionsFromYaml(n,s),d=n.events?.router,f=(0,t.notMissing)(n.events?.externalAccountIdExtractor)?parseAction(n,[`events`,`externalAccountIdExtractor`],buildActionId(n.info.key,n.events.externalAccountIdExtractor.actionId),n.events.externalAccountIdExtractor,s,void 0):void 0,p=n.events?.setup,m=(0,t.notMissing)(p)?{isConsolidated:p.isConsolidated,creation:parseWebhookSetupPhase(`creation`,p.creation,s),activation:(0,t.notMissing)(p.activation)?parseWebhookSetupPhase(`activation`,p.activation,s):void 0,deletion:parseWebhookSetupPhase(`deletion`,p.deletion,s)}:void 0,h=n.events?.guides,g=(0,t.notMissing)(h)?(()=>{let e=h.setup;if(!(0,t.notMissing)(e))return{setup:void 0};let r=new Set(Object.keys(n.scopeDefinitions||{})),i=parseGuideSectionsRequiredScopes(e.sections,r,[`events`,`guides`,`setup`,`sections`]);return{setup:{warning:e.warning,sections:i??[]}}})():void 0;if(((0,t.notMissing)(u)||(0,t.notMissing)(d)||(0,t.notMissing)(f)||(0,t.notMissing)(m)||(0,t.notMissing)(g))&&(i.events={setup:m,guides:g,actions:u,router:d,externalAccountIdExtractor:f}),(0,t.notMissing)(d)){let e=Object.keys(i.events?.actions??{}),t=n.info.key;validateEventRouterRuleActions(d.delivery??[],`delivery rule`,t,e),validateEventRouterRuleActions(d.rules,`rule`,t,e)}if(applyComputedReleaseStages(i),connectorUsesCallAction(n)){let e=buildYamlActionIds(n);validateCallActionGraph({connectorKey:n.info.key,actions:c??{},yamlActionIds:e,callOnlySites:collectCallOnlySites(i,e,f)})}return i}catch(e){if(e instanceof Y)throw e;let t=e.message,n=t.match(/at line (\d+)/);throw new InvalidYamlFileError(n?parseInt(n[1],10):1,t)}}const parseScopeDefinitions=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))t[n]={name:n,description:r.description,includes:parseScopesString(r?.includes)};let n=new Set(Object.keys(t)),r=[];if(Object.values(t).forEach(e=>{e.includes&&e.includes.forEach(t=>{n.has(t)||r.push({message:`Scope '${t}' included in scope '${e.name}' is not defined.`,path:[`scopeDefinitions`,e.name],keys:[`includes`]})})}),r.length>0)throw new MissingScopeDefinitionError(r);return t},stripAuthenticationSetup=e=>{let t={};for(let[n,r]of Object.entries(e))if(Array.isArray(r))t[n]=r;else if(r&&typeof r==`object`){let{setupFields:e,setupNotices:i,configFields:a,configNotices:o,support:s,refreshAuthentication:c,testActions:l,requiredScopes:u,authorizationFlow:d,releaseStage:f,...p}=r;t[n]=stripAuthenticationSetup(p)}else t[n]=r;return t},hydrateTestActions=(e,n,r,i,a)=>{if(!r||!i)return;let o=0;for(let s of Object.values(r)){for(let r of Object.values(s))r.testActions=r.testActions?.map((r,s)=>{if((0,t.notMissing)(r.action))if(typeof r.action==`string`){let e=buildActionId(n,r.action),t=Object.values(i).find(t=>t.id===e);if(t)return{...r,action:t,isInline:!1}}else{let t=parseAction(e,[`authentication`,o,`testActions`,s],buildActionId(n,r.action.actionId),r.action,a);return{...r,action:t,isInline:!0}}return{...r,isInline:!1}});o++}},getConnectorCategoriesFromActions=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},we=/"([^"]*)"|(\S+)/g,parseScopesString=e=>{if(!(0,t.notMissing)(e))return;let n=[];for(let t of e.matchAll(we)){let e=(t[1]??t[2])?.trim();e&&e.length>0&&n.push(e)}return n},parseGuideSectionsRequiredScopes=(e,t,n)=>{if(!e?.length)return e;let r=[],i=e.map((e,i)=>{let a=e.applicableScopes,o=parseScopesString(typeof a==`string`?a:void 0);o&&o.forEach(e=>{t.has(e)||r.push({message:`Scope '${e}' included in guide section is not defined.`,path:[...n,i],keys:[`applicableScopes`]})});let s=Array.isArray(e.steps)?e.steps:void 0,c=s?.map((e,a)=>{let s=e.applicableScopes;if(!s||typeof s!=`string`){let{applicableScopes:t,...n}=e;return{...n,applicableScopes:void 0}}let c=parseScopesString(s);return c?.forEach(e=>{t.has(e)||r.push({message:`Scope '${e}' included in guide step is not defined.`,path:[...n,i,`steps`,a],keys:[`applicableScopes`]})}),o&&c&&c.forEach(e=>{o.includes(e)||r.push({message:`Scope '${e}' included in guide step is missing from scopes set for section.`,path:[...n,i,`steps`,a],keys:[`applicableScopes`]})}),{...e,applicableScopes:c}})??s,{applicableScopes:l,steps:u,...d}=e;return{...d,...o===void 0?{}:{applicableScopes:o},...c===void 0?{}:{steps:c}}});if(r.length>0)throw new MissingScopeDefinitionError(r);return i},parseSupportGuides=(e,n,r)=>{if((0,t.isMissing)(e))return e;let i=e.guides;if((0,t.isMissing)(i))return e;let a=parseGuideSectionsRequiredScopes(i.config?.sections,n,[...r,`guides`,`config`,`sections`]),o=parseGuideSectionsRequiredScopes(i.setup?.sections,n,[...r,`guides`,`setup`,`sections`]);return{...e,guides:{...i,config:a!==void 0&&i.config?{...i.config,sections:a}:i.config,setup:o!==void 0&&i.setup?{...i.setup,sections:o}:i.setup}}},resolveAuthorizationRedirectUri=(e,n)=>{let{authorization:r}=e,i=e.type===`oauth2`&&e.grantType===`authorization_code`&&(0,t.notMissing)(r?.authorizationUrl),a=e.type===`mcp`&&(0,t.notMissing)(e.authorizationFlow);if(!i&&!a||(0,t.isMissing)(r))return;let o=r.redirectUri;return(0,t.isString)(o)&&o.trim()!==``?o:`\${apiHostUri}/connect/${i?`oauth2`:`mcp`}/${n}/callback`},buildAuthenticationFromYaml=e=>{let n={},r=new Set(Object.keys(e.scopeDefinitions||{})),i=[],a=e.info.key;for(let[o,s]of(e.authentication??[]).entries()){let[c]=Object.keys(s);n[c]=s[c].environments.reduce((n,l)=>{let{key:u,name:d}=l,{environments:f,refreshAuthentication:p,testActions:m,requiredScopes:h,...g}=s[c],_=parseScopesString(h);Object.values(_??[]).forEach(e=>{r.has(e)||i.push({message:`Scope '${e}' included in authentication '${c}' is not defined.`,path:[`authentication`,o],keys:[`requiredScopes`]})});let v=(0,t.notMissing)(p)?{schedule:p.schedule,action:parseAction(e,[`authentication`,o,`refreshAuthentication`,`action`],buildActionId(a,p.action.actionId),p.action)}:void 0,y=(0,t.notMissing)(g.support)?parseSupportGuides(g.support,r,[`authentication`,o,c,`support`]):void 0,b=(0,t.notMissing)(y)?buildSupport(a,g.label,y):void 0,x=resolveAuthorizationRedirectUri(g,a),S=(0,t.notMissing)(x)?{...g.authorization,redirectUri:x}:g.authorization;return n[u]={...g,authorization:S,...(0,t.notMissing)(b)?{support:b}:{},refreshAuthentication:v,requiredScopes:_,envKey:u,envName:d,testActions:m},n},{})}if(i.length>0)throw new MissingScopeDefinitionError(i);return n},buildActionKey=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,inferActionKey=e=>e.actionType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,getEntrypointHttpMethod=e=>{if(e.actionType!==`refresh_token`)return e.entrypointHttpMethod??`get`},inferEntrypointUrl=e=>{if(!(e.actionType===`refresh_token`||(0,t.isMissing)(e.schema)))return e.actionType===`list`?`/${e.schema}`:`/${e.schema}/:id`},buildActionResponses=e=>{let t={success:getDefaultSuccessActionResponse(e.actionType),errors:getDefaultErrorActionResponses()};return e.responses?.reduce((e,t)=>((0,a.isSuccessStatusCode)(t.statusCode)?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e),t)??t},buildActionsFromYaml=(e,t)=>e.actions?.reduce((n,r,i)=>{let a=buildActionKey(r),o=inferActionKey(r),s=a??o,c=buildActionId(e.info.key,r.actionId);return n[c]=parseAction(e,[`actions`,i],c,r,t,s),n},{}),buildSyncedActionsFromActions=e=>{if(!(0,t.notMissing)(e))return;let n=Object.values(e).reduce((e,t)=>{if(t.dataSync?.allowed!==!0)return e;let n=`${t.id}_s1query`;return e[n]={id:n,baseActionId:t.id,label:t.label,description:t.description,actionType:t.actionType,entrypointHttpMethod:t.entrypointHttpMethod,inputs:t.inputs,validationRules:t.validationRules,hasRequiredInput:t.inputs?.some(e=>e.required)??!1,dataSync:t.dataSync},e},{});return Object.keys(n).length>0?n:void 0},buildEventActionsFromYaml=(e,t)=>e.events?.actions?.reduce((n,r,i)=>{let a=buildActionId(e.info.key,r.actionId);return n[a]=parseAction(e,[`events`,`actions`,i],a,r,t,void 0),n},{}),validateEnumInputs=(e,t)=>{if(t){for(let n of t)if(n.type===`enum`&&n.oneOf&&`ref`in n.oneOf&&!(0,s.isValidEnumRef)(n.oneOf.ref))throw new InvalidEnumReferenceError(e,n.name,n.oneOf.ref)}},validateVariantProperties=(e,t,n)=>{for(let r of t){let t=[...e,r.name];!r.variants&&!r.type&&n.push({message:`'type' is required when 'variants' is absent`,path:t,keys:[`type`]}),r.type===`enum`&&!r.oneOf&&n.push({message:`oneOf is required when type is 'enum'`,path:t,keys:[]}),r.type===`enum`&&r.oneOf&&`ref`in r.oneOf&&((0,s.isValidEnumRef)(r.oneOf.ref)||n.push({message:`Invalid enum reference '${r.oneOf.ref}'`,path:t,keys:[]})),r.type!==`enum`&&r.oneOf&&n.push({message:`oneOf is only allowed when type is 'enum'`,path:t,keys:[]}),r.variants&&validateInputVariants(e,[r],n),r.type===`object`&&r.properties&&validateVariantProperties(t,r.properties,n)}},validateInputVariants=(e,t,n)=>{if(t)for(let r of t){let t=[...e,r.name];if(r.variants){r.type&&n.push({message:`when 'variants' is present, 'type' must be absent`,path:t,keys:[`type`]}),r.array&&n.push({message:`when 'variants' is present, 'array' must be absent`,path:t,keys:[`array`]}),r.properties&&n.push({message:`when 'variants' is present, 'properties' must be absent`,path:t,keys:[`properties`]}),r.oneOf&&n.push({message:`when 'variants' is present, 'oneOf' must be absent`,path:t,keys:[`oneOf`]}),r.rules&&n.push({message:`when 'variants' is present, 'rules' must be absent — define rules inside each variant instead`,path:t,keys:[`rules`]}),r.variants.length<2&&n.push({message:`'variants' must contain at least 2 entries`,path:t,keys:[`variants`]});for(let e of r.variants)e.type===`enum`&&!e.oneOf&&n.push({message:`oneOf is required when type is 'enum'`,path:t,keys:[]}),e.type===`enum`&&e.oneOf&&`ref`in e.oneOf&&((0,s.isValidEnumRef)(e.oneOf.ref)||n.push({message:`Invalid enum reference '${e.oneOf.ref}'`,path:t,keys:[]})),e.type===`object`&&e.properties&&validateVariantProperties(t,e.properties,n)}else r.type||n.push({message:`'type' is required when 'variants' is absent`,path:t,keys:[`type`]});r.type===`object`&&r.properties&&validateInputVariants(t,r.properties,n)}},validateExamplesMatchInputs=(e,n,r)=>{if(!n||n.length===0)return;let i={};for(let e of r){let t=buildZodSchemaFromInputType(e);e.required||(t=t.optional()),i[e.name]=t}let a=t.z.object(i).strict();for(let t=0;t<n.length;t++){let{exampleDescription:r,...i}=n[t],o=a.safeParse(i);if(!o.success){let n=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:[]}));throw new InvalidActionExampleError(e,t,n)}}},validateActionRuleFieldReferences=(e,t,n,r)=>{if(!n||n.length===0)return;let i=new Set(r.map(e=>e.name)),a=[];for(let r of n){let n=[];switch(r.rule){case`atLeastOneOf`:case`mutuallyExclusive`:n.push(...r.fields);break;case`requiredIf`:n.push(r.field,r.condition.field);break}for(let o of n)i.has(o)||a.push({message:`Validation rule '${r.rule}' in action '${e}' references unknown field '${o}'`,path:[...t,`validationRules`],keys:[o]})}if(a.length>0)throw new SchemaValidationError(a)},validateDataSyncPaginationKeys=(e,t,n,r)=>{let i=n?.pagination;if(!i)return;let a=(0,s.getIteratorLocation)(i),o=(0,s.getPaginationKeys)(i);if(!a||o.length===0)return;let c=new Set(r.filter(e=>e.in===a).map(e=>e.name)),l=[];for(let n of o)c.has(n)||l.push({message:`Pagination iterator references key '${n}' in '${a}', but no input with that name and location is declared on action '${e}'.`,path:[...t,`dataSync`,`pagination`,`iterator`],keys:[n]});if(l.length>0)throw new SchemaValidationError(l)},validateDataSyncIncrementalKeys=(e,t,n,r)=>{let i=n?.incremental;if(!i)return;let{key:a,in:o}=i.iterator;if(!r.some(e=>e.in===o&&e.name===a))throw new SchemaValidationError([{message:`Incremental iterator references key '${a}' in '${o}', but no input with that name and location is declared on action '${e}'.`,path:[...t,`dataSync`,`incremental`,`iterator`],keys:[a]}])},validateEventRouterRuleActions=(e,t,n,r)=>{let i=`${n}_`;for(let[a,o]of e.entries()){let e=o.then.action;if(!e.startsWith(i))throw new InvalidEventRouterActionPrefixError(e,a,n,t);if(!r.includes(e))throw new InvalidEventRouterReferenceError(e,a,t)}},validateAuthRequirementsMutualExclusivity=(e,n)=>{if((0,t.isMissing)(n))return;let r=e.info.key,i=Object.values(n).some(e=>(0,t.notMissing)(e.authRequirements)),a=Object.values(n).some(e=>(0,t.notMissing)(e.requiredScopes)&&e.requiredScopes.length>0);if(i&&a)throw new InvalidAuthRequirementsError([{message:`Connector '${r}' cannot have both 'authRequirements' and 'requiredScopes'. To migrate, replace 'requiredScopes' with 'authRequirements' on all actions including test actions.`,path:[`actions`],keys:[`authRequirements`,`requiredScopes`]}])},getConnectorAuthKeys=e=>{let t=new Set;for(let n of e.authentication??[])for(let e of Object.keys(n))t.add(e);return t},parseAuthRequirements=(e,n,r,i,a)=>{if((0,t.isMissing)(i))return;if(Object.keys(i).length===0)throw new InvalidAuthRequirementsError([{message:`Action '${r}' has an empty authRequirements map. Either omit authRequirements (to allow all auth types) or specify at least one auth config key.`,path:[...n,`authRequirements`],keys:[]}]);let o=getConnectorAuthKeys(e),s=[],c={};for(let[e,t]of Object.entries(i)){if(!o.has(e)){s.push({message:`Action '${r}' references auth config key '${e}' which is not defined on this connector. Valid keys: ${[...o].join(`, `)}.`,path:[...n,`authRequirements`],keys:[e]});continue}for(let i of t)a.has(i)||s.push({message:`Undefined scope '${i}' in action '${r}' (auth: '${e}'). Ensure the scope is declared in scopeDefinitions.`,path:[...n,`authRequirements`,e],keys:[i]});c[e]=t}if(s.length>0)throw new InvalidAuthRequirementsError(s);return c},parseAction=(e,t,n,r,i,a)=>{let o=inferEntrypointUrl(r),c=buildActionResponses(r),l=buildCursorConfig(r),u=r.inputs||[];l.enabled&&(u?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),u?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1})),validateEnumInputs(n,u);let d=[];if(validateInputVariants(t,u,d),d.length>0)throw new SchemaValidationError(d);validateExamplesMatchInputs(n,r.examples,u),validateActionRuleFieldReferences(n,t,r.validationRules,u),validateDataSyncPaginationKeys(n,t,r.dataSync,u),validateDataSyncIncrementalKeys(n,t,r.dataSync,u);let f=getEntrypointHttpMethod(r),p=new Set(Object.keys(e.scopeDefinitions||{})),m=[],h=parseScopesString(r.requiredScopes);if(Object.values(h??[]).forEach(e=>{p.has(e)||m.push({message:`Scope '${e}' included in action '${r.actionId}' is not defined.`,path:t,keys:[`requiredScopes`]})}),m.length>0)throw new MissingScopeDefinitionError(m);let g=parseAuthRequirements(e,t,r.actionId,r.authRequirements,p);return{id:n,categories:r.categories,label:r.label,description:r.description,details:r.details,examples:r.examples,actionType:r.actionType,effects:r.effects,annotations:r.annotations,executionMode:r.executionMode,schemaType:r.schemaType??`native`,entrypointUrl:r.entrypointUrl??o,entrypointHttpMethod:f,endpoint:a,tags:r.tags,releaseStage:r.releaseStage,resources:r.resources,responses:c,cursor:l,compositeIdentifiers:parseCompositeIdentifiersConfig(r),requiredScopes:h,authRequirements:g,inputs:u,validationRules:r.validationRules,steps:parseSteps({kind:`action`,actionId:r.actionId},r.steps,i,n=>n.functionName!==`map_fields`&&n.functionName!==`typecast`?{}:parseFieldConfigs(e,t,n.parameters?.fields??r.fieldConfigs)??{}),result:r.result,dataSync:r.dataSync,dataSyncConfigFingerprint:r.dataSync?.allowed===!0?(0,s.computeDataSyncFingerprint)(r.dataSync):void 0,providerEvents:r.providerEvents,prerequisiteActions:r.prerequisiteActions,requiresManualSetup:r.requiresManualSetup,userScoped:r.userScoped}},parseWebhookSetupPhase=(e,t,n)=>({steps:parseSteps({kind:`setupPhase`,phase:e},t.steps,n),result:t.result}),parseSteps=(e,t,n,r)=>t.reduce((t,i)=>{let parseStepFunctionMeta=e=>{let{customErrors:t,...i}=e.parameters??{},a=r?.(e)??{};return{functionName:e.functionName,version:e.version,params:{...getDefaultRequestStepFunctionsParams({stepFunctionName:e.functionName,baseRequestParams:n,customErrors:t}),...a,...i}}},a={id:i.stepId,description:i.description,condition:i.condition,onConditionError:i.onConditionError,ignoreError:i.ignoreError};if(`iterator`in i&&i.iterator){if(`stepFunction`in i&&i.stepFunction){let n={...a,iterator:i.iterator,stepFunction:parseStepFunctionMeta(i.stepFunction)};validateStep(e,n),t[i.stepId]=n}else if(`stepFunctions`in i&&i.stepFunctions){let n={...a,iterator:i.iterator,stepFunctions:i.stepFunctions.map(parseStepFunctionMeta)};validateStepFunctions(e,n),t[i.stepId]=n}}else if(`stepFunction`in i&&i.stepFunction){let n={...a,stepFunction:parseStepFunctionMeta(i.stepFunction)};validateStep(e,n),t[i.stepId]=n}return t},{}),parseFieldConfigs=(e,n,r)=>{if((0,t.isMissing)(r)||!Array.isArray(r))return;let i=new Set(Object.keys(e.scopeDefinitions||{})),a=[],o=r.map((e,t)=>{if(typeof e!=`object`||!e)return;let r=parseScopesString(e.requiredScopes);return Object.values(r??[]).forEach(r=>{i.has(r)||a.push({message:`Scope '${r}' included in field config '${e.targetFieldKey}' is not defined.`,path:[...n,`fieldConfigs`,t],keys:[`requiredScopes`]})}),{...e,requiredScopes:r}});if(a.length>0)throw new MissingScopeDefinitionError(a);return{fields:o}},validateStep=(e,t)=>{let n=t.stepFunction.version??`1`,r=s.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new InvalidStepFunctionError(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&parseStepFunctionParamsWithSchemaException(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},validateStepFunctions=(e,t)=>{for(let n of t.stepFunctions){let r=n.version??`1`,i=s.StepFunctionsRegistry[n.functionName]?.[`v${r}`];if(!i)throw new InvalidStepFunctionError(e,t.id,n.functionName,r);let a=i.inputSchema;a&&parseStepFunctionParamsWithSchemaException(a,n.params,e,t.id,n.functionName,r)}},buildPathString=e=>e.reduce((e,t)=>typeof t==`number`?`${e}[${t}]`:typeof t==`string`?e?`${e}.${t}`:t:e,``),enrichVariantErrors=e=>{let isVariantDump=e=>e.message?.includes(`expected one of the following shapes`),t=e.filter(isVariantDump);if(t.length===0)return e;let n=Math.min(...t.map(e=>e.path?.length??0));return e.filter(e=>!isVariantDump(e)||(e.path?.length??0)<=n).map(e=>isVariantDump(e)&&e.path?.length>0?{...e,message:`The field '${buildPathString(e.path)}' ${e.message}`}:e)},parseActionInputs=(e,n)=>{if(!e.inputs)return{};let r=createInputsSchema(e.inputs),i;try{i=t.z.object(r).parse(n)}catch(e){throw e instanceof t.z.ZodError?new t.z.ZodError(enrichVariantErrors(e.issues)):e}let a={...i.headers??{},...i.query??{},...i.path??{},...i.body??{}};return e.validationRules&&e.validationRules.length>0&&validateActionRules(e.validationRules,a,e.inputs),a},createInputsSchema=e=>{let n=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),r={};for(let[e,i]of Object.entries(n)){let n={};for(let e of i){let t=buildZodSchemaFromInputType(e);e.description&&(t=t.meta({description:e.description})),e.required||(t=t.optional()),n[e.name]=t}Object.keys(n).length>0&&(r[e]=t.z.object(n))}return r},buildEnumZodSchema=(e,n)=>{if(!n)throw Error(`Enum input "${e}" requires oneOf definition`);let r;if(`values`in n)r=n.values;else if(`ref`in n){let t=(0,s.getInputEnumValues)(n.ref);if(!t)throw Error(`Unknown enum reference "${n.ref}" in input "${e}"`);r=t}else throw Error(`Invalid oneOf definition in input "${e}"`);if(r.length===0)throw Error(`Enum input "${e}" must have at least one allowed value`);return t.z.enum(r)},applyInputRules=(e,t,n)=>{let r=t.errorMessage;if(n===`string`||n===`datetime_string`){let n=e;if(t.minLength!==void 0&&(n=n.min(t.minLength,r)),t.maxLength!==void 0&&(n=n.max(t.maxLength,r)),t.pattern!==void 0&&(n=n.regex(new RegExp(t.pattern),r)),t.format!==void 0){let e=s.FORMAT_PATTERNS[t.format];e&&(n=n.regex(e,r??`Must be a valid ${t.format}`))}return n}if(n===`number`){let n=e;return t.min!==void 0&&(n=n.min(t.min,r)),t.max!==void 0&&(n=n.max(t.max,r)),n}return e},validateActionRules=(e,n,r)=>{let i=[],a={};if(r)for(let e of r)a[e.name]=e.in;let fieldPath=e=>{let t=a[e];return t?[t,e]:[e]};for(let t of e)switch(t.rule){case`atLeastOneOf`:if(!t.fields.some(e=>n[e]!==void 0&&n[e]!==null))for(let e of t.fields)i.push({code:`custom`,message:t.errorMessage??`At least one of [${t.fields.join(`, `)}] is required`,path:fieldPath(e),input:n});break;case`requiredIf`:{let e=n[t.condition.field],r=!1;if(t.condition.equals!==void 0)r=String(e)===t.condition.equals;else if(t.condition.notEquals!==void 0)r=String(e)!==t.condition.notEquals;else if(t.condition.present!==void 0){let n=e!=null;r=t.condition.present?n:!n}r&&(n[t.field]===void 0||n[t.field]===null)&&i.push({code:`custom`,message:t.errorMessage??`Field "${t.field}" is required when condition is met`,path:fieldPath(t.field),input:n});break}case`mutuallyExclusive`:{let e=t.fields.filter(e=>n[e]!==void 0&&n[e]!==null);if(e.length>1)for(let r of e)i.push({code:`custom`,message:t.errorMessage??`Fields [${t.fields.join(`, `)}] are mutually exclusive`,path:fieldPath(r),input:n});break}}if(i.length>0)throw new t.z.ZodError(i)},describeVariantShape=e=>{let t;switch(e.type){case`string`:case`datetime_string`:case`number`:case`boolean`:t=e.type;break;case`enum`:t=e.oneOf&&`values`in e.oneOf?e.oneOf.values.map(e=>`'${e}'`).join(` | `):`enum`;break;case`object`:t=e.properties&&e.properties.length>0?`{ ${e.properties.map(e=>{let t=e.required?``:`?`,n;return n=e.variants&&e.variants.length>=2?e.variants.map(describeVariantShape).join(` | `):e.type===`enum`&&e.oneOf&&`values`in e.oneOf?e.oneOf.values.map(e=>`'${e}'`).join(` | `):e.type??`unknown`,e.array&&(n+=`[]`),`${e.name}${t}: ${n}`}).join(`, `)} }`:`object`;break;default:t=`unknown`}return e.array&&(t+=`[]`),t},buildVariantsSchema=e=>{let n=e.map(e=>buildZodSchemaFromInputType(e,{strict:!0})),r=e.map(describeVariantShape).join(` | `);return t.z.any().check(e=>{for(let t of n)if(t.safeParse(e.value).success)return;e.issues.push({code:`custom`,message:`expected one of the following shapes: ${r}`,input:e.value,path:[]})})},buildZodSchemaFromInputType=(e,n)=>{if(e.variants&&e.variants.length>=2)return buildVariantsSchema(e.variants);let r;switch(e.type){case`string`:case`datetime_string`:r=t.z.string();break;case`number`:r=t.z.number();break;case`boolean`:r=t.z.boolean();break;case`enum`:r=buildEnumZodSchema(e.name,e.oneOf);break;case`object`:if(e.properties&&e.properties.length>0){let i={};for(let t of e.properties){let e=buildZodSchemaFromInputType(t,n);t.description&&(e=e.meta({description:t.description})),t.required||(e=e.optional()),i[t.name]=e}r=n?.strict?(0,t.zStrictObject)(i):t.z.object(i)}else r=t.z.record(t.z.string(),t.z.unknown());break;default:r=t.z.unknown()}return e.rules&&e.type&&(r=applyInputRules(r,e.rules,e.type)),e.array&&(r=t.z.array(r)),r},buildCursorConfig=e=>{let t=e.actionType===`list`,n=e.cursor??{enabled:t,pageSize:25};return{enabled:n.enabled&&t,pageSize:n.pageSize}},parseCompositeIdentifiersConfig=e=>{if(e.actionType===`refresh_token`||(0,t.isMissing)(e.compositeIdentifiers))return{enabled:!1};let n=[];for(let t of e.compositeIdentifiers?.fields??[]){let r=t.components.map(t=>({name:t,alias:e.fieldConfigs?.find(e=>e.targetFieldKey===t)?.alias}));n.push({targetFieldKey:t.targetFieldKey,remote:t.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:n.length>0?n:void 0}},getDefaultRequestStepFunctionsParams=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`||e===`soap_request`||e===`soap_paginated_request`||e===`download_file`||e===`upload_file`||e===`upload_binary`){let e=[{receivedStatus:500,targetStatus:502}],r=[...n&&Array.isArray(n)?n:[],...e];return{...t,customErrors:r}}else if(e===`mcp_request`)return{...t};else return{}},parseWithSchemaException=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;throw new SchemaValidationError(n.error.issues.map(e=>{let t=e?.keys??[];if(t.length===0&&e.code===`invalid_union`){let n=e;for(let e of n.errors??[]){let n=e?.find(e=>e.code===`unrecognized_keys`);if(n?.keys?.length){t=n.keys;break}}}return{code:e.code,message:e.message,input:e.input,path:e.path,keys:t}}),`Invalid connector schema`)},parseStepFunctionParamsWithSchemaException=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;throw new InvalidStepFunctionParamsError(n,r,i,a,o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]})))},validateYamlConnector=e=>{try{return{success:!0,connector:parseYamlConnector(e)}}catch(n){if(n instanceof SchemaValidationError||n instanceof MissingScopeDefinitionError||n instanceof InvalidAuthRequirementsError){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=(0,t.isMissing)(r)?n.path:[...n.path,r],o=getErrorLineNumber(a,e);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof InvalidYamlFileError)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof InvalidStepFunctionError)return{success:!1,errors:[{line:getErrorLineNumberInSteps(n.location,n.stepId,n.functionName,!1,e),message:n.message,field:stepLocationField(n.location)}]};else if(n instanceof UnknownCallActionTargetError||n instanceof SelfReferencingActionError||n instanceof CircularActionReferenceError||n instanceof IncompatibleCallActionAuthError)return{success:!1,errors:[{line:getErrorLineNumberInSteps(n.location,n.stepId,`call_action`,!1,e),message:n.message,field:stepLocationField(n.location)}]};else if(n instanceof InvalidEventRouterActionPrefixError||n instanceof InvalidEventRouterReferenceError)return{success:!1,errors:[{line:1,message:n.message,field:`events.router`}]};else if(n instanceof InvalidStepFunctionParamsError){let r=n.issues,i=[],a=stepLocationFieldPrefix(n.location);return r.forEach(r=>{let o=r?.keys?.[0],s=(0,t.isMissing)(o)?r.path:[...r.path,o],c=getErrorLineNumberInSteps(n.location,n.stepId,n.functionName,!0,e);i.push({line:c,message:r.message,field:`${a}${s.join(`.`)}`})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},getErrorLineNumber=(e,n)=>{let r=n.split(`
|
|
5
5
|
`),i=0,a=-1,o=0;for(let n=0;n<r.length;n++){let s=r[n],c=s.match(/^(\s*)/)?.[1]?.length||0,l=s.replace(`- `,``).trim();if(l.startsWith(`#`)||l===``||c<=a)continue;let u=(0,t.notMissing)(e[i])?`${String(e[i])}`:``;if((0,t.isMissing)(u))return o+1;if(!isNaN(Number(u))){let e=parseInt(u,10),t=-1;for(let a=n;a<r.length;a++)if(r[a].trim().startsWith(`-`)&&t++,t===e){i++,o=n,n--;break}else n++}else if(l.startsWith(`${u}:`)){if(i===e.length-1)return n+1;a=c,o=n,i++}}return o+1},stepLocationField=e=>e.kind===`action`?void 0:`events.setup.${e.phase}`,stepLocationFieldPrefix=e=>e.kind===`action`?``:`events.setup.${e.phase}.`,ownerMarkersFor=e=>e.kind===`action`?[`- actionId: ${e.actionId}`]:[`setup:`,`${e.phase}:`],getErrorLineNumberInSteps=(e,t,n,r,i)=>{let a=i.split(`
|
|
6
|
-
`),o=ownerMarkersFor(e),s=0,c=!1,l=1;for(let e=0;e<a.length;e++){let i=a[e].trim();if(s<o.length){i===o[s]&&(s++,l=e+1);continue}if(!c){i===`- stepId: ${t}`&&(c=!0,l=e+1);continue}if(!r&&i.includes(`functionName: ${n}`)||r&&i===`parameters:`)return e+1}return l},X=[{key:`production`,name:`Production`}],finishDescription=e=>{let t=e.length>200?e.slice(0,199).trimEnd():e;return t.endsWith(`.`)?t:`${t}.`},buildDescription=(e,t)=>{let n=t.server?.description?.replace(/\s+/g,` `).trim();if(n)return finishDescription(n.toLowerCase().startsWith(e.toLowerCase())?n:`${e} is ${n.charAt(0).toLowerCase()}${n.slice(1)}`);let r=t.resource?.name??t.server?.title??t.server?.name;return r&&r!==e?`${e} is a remote MCP server integration exposing the tools of ${r} through the Model Context Protocol.`:`${e} is a remote MCP server integration exposing its tools through the Model Context Protocol.`},deriveConnectorKey=e=>{let t=e.toLowerCase().replace(/[^a-z0-9]/g,``);return t===``?void 0:`mcp_${t}`},buildAuthenticationEntry=(e,t,n)=>{if(!n.requiresAuthorization)return{mcp:{type:`mcp`,label:`MCP Server`,support:{description:`Open MCP server. No credentials required to connect.`},authorization:{type:`none`},environments:X}};if(n.oauth){let r=n.oauth.dynamicRegistration===!0?{}:{setupFields:[{key:`clientId`,label:`Client ID`,type:`text`,required:!0,secret:!1,description:`OAuth client ID of the app registered with the ${e} MCP server`},{key:`clientSecret`,label:`Client Secret`,type:`password`,required:!1,secret:!0,description:`OAuth client secret of the app registered with the ${e} MCP server. Leave empty for public clients (PKCE-only)`}]};return{mcp_oauth:{type:`mcp`,label:`OAuth`,support:{description:`Authorize through the MCP server. Endpoints and client registration are discovered at connect time.`},authorizationFlow:{serverUrl:t,...n.oauth.scopes?.length?{scopes:n.oauth.scopes}:{}},authorization:{type:`bearer`,token:`$.credentials.accessToken`},...r,environments:X}}}return{mcp:{type:`mcp`,label:`Access Token`,support:{description:`Uses a static access token issued by the MCP server.`},authorization:{type:`bearer`,token:`$.credentials.accessToken`},configFields:[{key:`accessToken`,label:`Access Token`,type:`password`,required:!0,secret:!0,description:`Access token for the ${e} MCP server`}],environments:X}}},generateMcpConnector=async({serverUrl:e,title:n},r=a.probeMcpServer)=>{let i=deriveConnectorKey(n);if((0,t.isMissing)(i))throw Error(`The connector title must contain at least one alphanumeric character`);let s=await r(e),c=s.server?.instructions,l=s.server?.iconUrl??`https://stackone-logos.com/api/stackone/filled/png`,u=s.resource?.documentationUrl,d=buildDescription(n,s),f=(0,o.stringify)({StackOne:`1.0.0`,info:{title:n,key:i,version:`1.0.0`,assets:{icon:l},description:d},baseUrl:e,releaseStage:`ga`,...u?{resources:u}:{},...c?{mcp:{instructions:c.slice(0,J)}}:{},authentication:[buildAuthenticationEntry(n,e,s)]}),p=validateYamlConnector(f);if(!p.success||(0,t.isMissing)(p.connector)){let e=p.errors?.map(e=>`${e.field??`unknown`}: ${e.message}`).join(`; `);throw Error(`The generated MCP connector failed validation: ${e}`)}return{yaml:f,connector:p.connector}},isMcpConnector=e=>{let t=Object.values(e.authentication??{}).flatMap(e=>Object.values(e??{}));return t.length>0&&t.every(e=>e?.type===`mcp`)},Te=[`title`,`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`],deriveActionId=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``),humanizeToolName=e=>{let t=e.replace(/[_-]+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)},mapScalarType=e=>e===`number`||e===`integer`?`number`:e===`boolean`?`boolean`:`string`,mapInputType=e=>{if(e.enum?.length)return{type:`enum`,oneOf:{values:e.enum.map(String)}};let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`array`?{array:!0,...mapInputType(e.items??{})}:t===`object`?{type:`object`,...e.properties?{properties:buildInputFields(e,{nested:!0})}:{}}:{type:mapScalarType(t)}},buildInputFields=(e,{nested:n})=>{let r=e.properties;if((0,t.isMissing)(r))return;let i=new Set(e.required??[]);return Object.entries(r).map(([e,t])=>({name:e,description:t.description??`The ${e} argument of the tool`,required:i.has(e),...n?{}:{in:`body`},...mapInputType(t)}))},buildToolAnnotations=e=>{let n=e.annotations;if((0,t.isMissing)(n))return{};let r=Te.reduce((e,t)=>(n[t]!==void 0&&(e[t]=n[t]),e),{});return{effects:n.readOnlyHint===!0?[`read`]:n.destructiveHint===!0?[`delete`]:[`execute`],...Object.keys(r).length?{annotations:r}:{}}},buildToolAction=e=>{let t=deriveActionId(e.name);if(t===``)throw Error(`Cannot derive an action id from the MCP tool name '${e.name}': it has no alphanumeric characters`);let n=buildInputFields(e.inputSchema??{},{nested:!1}),r=n?.map(e=>({name:e.name,value:`$.inputs.${e.name}`,...e.required?{}:{condition:`{{present(inputs.${e.name})}}`}}));return{actionId:t,categories:[`MCP`],actionType:`custom`,label:e.title??e.annotations?.title??humanizeToolName(e.name),description:e.description??`Call the ${e.name} tool on the MCP server.`,...buildToolAnnotations(e),...n?{inputs:n}:{},steps:[{stepId:`call_tool`,description:`Call the ${e.name} tool on the MCP server`,stepFunction:{functionName:`mcp_request`,parameters:{toolName:e.name,...r?.length?{args:r}:{}}}}],result:{data:`$.steps.call_tool.output.data`}}},addMcpToolActions=(e,n)=>{let r=(0,o.parse)(e);if((0,t.isMissing)(r)||typeof r!=`object`)throw Error(`The provided yaml is not a connector document`);let i=Array.isArray(r.actions)?r.actions:[],a=n.map(buildToolAction),s=[...i.map(e=>a.find(t=>t.actionId===e.actionId)??e),...a.filter(e=>!i.some(t=>t.actionId===e.actionId))],c=(0,o.stringify)({...r,actions:s}),l=validateYamlConnector(c);if(!l.success||(0,t.isMissing)(l.connector)){let e=l.errors?.map(e=>`${e.field??`unknown`}: ${e.message}`).join(`; `);throw Error(`The completed MCP connector failed validation: ${e}`)}return{yaml:c,connector:l.connector}},listAllTools=async(e,t)=>{let n=await e.listTools(t?{cursor:t}:void 0);return n.nextCursor?[...n.tools,...await listAllTools(e,n.nextCursor)]:n.tools},buildMcpClient=e=>new a.McpClient(e),extractHostname=e=>{try{return new URL(String(e)).hostname}catch{return}},applyServerInfo=(e,n)=>{let r=(0,o.parse)(e);if((0,t.isMissing)(n)||(0,t.isMissing)(r)||typeof r!=`object`)return e;let i=r.info??{},a=typeof i.title==`string`?i.title:void 0,s=n.title??n.name,c=extractHostname(r.baseUrl),l=!!(s&&a&&c&&a.toLowerCase()===c),u=l?s:a,d=(n.description||l)&&u?{description:buildDescription(u,{server:n})}:{},f=n.iconUrl&&i.assets?.icon===`https://stackone-logos.com/api/stackone/filled/png`?{assets:{...i.assets,icon:n.iconUrl}}:{},p=n.instructions?{mcp:{...r.mcp??{},instructions:n.instructions.slice(0,J)}}:{};return(0,o.stringify)({...r,info:{...i,...l?{title:u}:{},...d,...f},...p})},completeMcpConnector=async(e,{headers:t,timeout:n}={},r=buildMcpClient)=>{let i=(0,o.parse)(e)?.baseUrl;if(typeof i!=`string`||i===``)throw Error(`The connector yaml has no baseUrl pointing at the MCP server`);let a=r({serverUrl:i,headers:t,timeout:n});try{let t=await listAllTools(a);return addMcpToolActions(applyServerInfo(e,await a.getServerInfo().catch(()=>void 0)),t)}finally{await a.close().catch(()=>void 0)}},getActionForRefreshAuthentication=(e,n,r)=>{let i=e.authentication?.[n]?.[r]?.refreshAuthentication?.action;return(0,t.notMissing)(i)?{action:i,params:{}}:void 0},supportsRefreshAuthentication=(e,n,r)=>(0,t.notMissing)(getActionForRefreshAuthentication(e,n,r)),Ee=[`oauth2`,`mcp`],getTokenExpiresIn=(e,t,n)=>{let r=e.authentication?.[t]?.[n],i=r?.authorization,a=r?.type;if(!(!a||!Ee.includes(a)))return i?.tokenExpiresIn},getRefreshTokenExpiresIn=(e,t,n)=>{let r=e.authentication?.[t]?.[n],i=r?.authorization,a=r?.type;if(!(!a||!Ee.includes(a)))return i?.tokenRefreshExpiresIn};var Z=class ConnectSDKError extends Error{constructor(e,t,n){super(n),this.name=`ConnectSDKError`,this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,ConnectSDKError)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},ConnectorParseError=class extends Z{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},MissingActionError=class extends Z{constructor(e,t){super(`MISSING_ACTION_ERROR`,e,t),this.name=`MissingActionError`}},InvalidActionInputsError=class extends Z{constructor(e,t,n){super(`INVALID_ACTION_INPUTS_ERROR`,e,t),this.name=`InvalidActionInputsError`,this.validationErrors=n}},InvalidCursorError=class extends Z{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}},IncompatibleAuthTypeError=class extends Z{constructor(e,t){super(`INCOMPATIBLE_AUTH_TYPE_ERROR`,e,t),this.name=`IncompatibleAuthTypeError`}},ActingUserRequiredError=class extends Z{constructor(e,t){super(`ACTING_USER_REQUIRED_ERROR`,e,t),this.name=`ActingUserRequiredError`}},InvalidEventOutputError=class extends Z{constructor(e,t){super(`INVALID_EVENT_OUTPUT_ERROR`,e,t),this.name=`InvalidEventOutputError`}},PolicyDeniedError=class extends Z{constructor(e,t,n){super(`POLICY_DENIED_ERROR`,e,n),this.name=`PolicyDeniedError`,this.level=t.level,this.policyIds=t.policyIds}},PolicyEvaluationError=class extends Z{constructor(e,t,n){super(`POLICY_EVALUATION_ERROR`,e,n),this.name=`PolicyEvaluationError`,this.level=t.level}},PolicyPreparseError=class extends Z{constructor(e,t){super(`POLICY_PREPARSE_ERROR`,e,t),this.name=`PolicyPreparseError`}};const Q={POLICY_DENIED_ERROR:403,POLICY_EVALUATION_ERROR:503,POLICY_PREPARSE_ERROR:500},isPolicyErrorType=e=>e in Q,isRefusalType=e=>isPolicyErrorType(e)||e===`ACTING_USER_REQUIRED_ERROR`,De={org:`an organization administrator`,project:`a project administrator`},quoting=e=>e?`, quoting reference ${e}`:``,Oe={POLICY_DENIED_ERROR:({message:e,level:t,reference:n})=>`${e}. Ask ${De[t??``]??`an administrator`} for access${quoting(n)}.`,POLICY_EVALUATION_ERROR:({message:e,reference:t})=>`${e}. This is usually temporary, so retry the call${t?`, and quote reference ${t} if it keeps failing`:``}.`,POLICY_PREPARSE_ERROR:({reference:e})=>`The policies governing this call could not be read. Ask an administrator to check them${quoting(e)}.`,ACTING_USER_REQUIRED_ERROR:({message:e,reference:t})=>`${e}. Call it as a signed-in user, or ask an administrator for help${quoting(t)}.`},describeRefusal=e=>{if(!isRefusalType(e.errorType))return;let{level:n}=e,r=(0,t.isString)(n)?n:void 0;return{errorType:e.errorType,message:Oe[e.errorType]({message:e.message,level:r,reference:e.context?.actionRunId}),...r&&{level:r}}},refusalOf=e=>{let n=(0,t.isObject)(e)?e.refusal:void 0;if(!(!(0,t.isObject)(n)||!(0,t.isString)(n.errorType)||!(0,t.isString)(n.message)))return n};function buildInputs(e,t,n){let r=e[t],i=r&&typeof r==`object`&&!Array.isArray(r)?{...r,...n}:n;return{...e,[t]:i}}function extractData(e,n){let r=(0,t.getByDotPath)(n.outputs,e.response.dataKey);return Array.isArray(r)?r:r==null?[]:[r]}const buildResponseScope=e=>({...(0,t.isObject)(e.outputs)?e.outputs:{},headers:e.responseHeaders}),assertResponseHeadersAvailable=(e,n)=>{if(n.includes(`$.headers`)){if(e.responseHeaders===void 0)throw Error(`DataSync key reads $.headers but the response carried no responseHeaders: ${n}. Check that connect-handler forwards responseHeaders and that the action makes a request.`);if((0,t.isObject)(e.outputs)&&Object.prototype.hasOwnProperty.call(e.outputs,`headers`))throw Error(`DataSync key reads $.headers, which is ambiguous because the action result also has a headers field: ${n}. Rename the result field; \$.headers is reserved for response headers.`)}},resolveResponseKey=(e,n)=>{if(!(0,c.isExpression)(n))return(0,t.getByDotPath)(e.outputs,n);assertResponseHeadersAvailable(e,n);try{return(0,c.evaluate)(n,buildResponseScope(e),{throwOnEvalError:!0})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to evaluate DataSync response key ${n}. ${t}`)}};function isExhausted(e,t,n,r){if(e.stopCondition===void 0&&typeof n==`function`)return n(t);let i=e.stopCondition??n;assertResponseHeadersAvailable(t,i);try{return!!(0,c.evaluate)(`{{ ${i} }}`,buildResponseScope(t))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to evaluate pagination stop condition on page ${r}: ${i}. ${t}`)}}function createCursorPaginator(e,{baseInputs:n={}}={}){let resolveCursor=t=>resolveResponseKey(t,e.response.nextKey),defaultStop=e=>(0,t.isMissing)(resolveCursor(e));return{config:e,computeNextInputs({previousResponse:t}){return t?buildInputs(n,e.iterator.in,{[e.iterator.key]:resolveCursor(t)}):{...n}},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,defaultStop,n)}}function createOffsetPaginator(e,{baseInputs:t={}}={}){let n=e.iterator.defaultLimit??100,r=e.iterator.startOffset??0,{in:i,offsetKey:a,limitKey:o}=e.iterator,s=`${e.response.dataKey}[0] == null`;return{config:e,computeNextInputs({currentIteration:e,recordsRetrieved:s}){let c=s??e*n;return buildInputs(t,i,{[a]:r+c,[o]:n})},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,s,n)}}function createPagePaginator(e,{baseInputs:t={}}={}){let n=e.iterator.startPage??1,r=e.iterator.defaultPageSize??100,{in:i,pageKey:a,pageSizeKey:o}=e.iterator,s=`${e.response.dataKey}[0] == null`;return{config:e,computeNextInputs({currentIteration:e}){let s={[a]:n+e};return o&&(s[o]=r),buildInputs(t,i,s)},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,s,n)}}const ke={cursor:createCursorPaginator,offset:createOffsetPaginator,page:createPagePaginator};function createPaginator(e,t={}){let n=ke[e.type];return n(e,t)}function extractItems(e,n){let r=n.pagination?.response.dataKey??n.dataKey??`data`,i=(0,t.getByDotPath)(e.outputs,r);return Array.isArray(i)?i:i==null?[]:[i]}function assertSuccessful(e,t){if(e.response?.successful===!1)throw Error(`Action call failed on page ${t}: ${e.response.statusCode} ${e.response.message??``}`.trim())}function hasExceededMaxIterations(e,t=1e4){return e>=t}function hasExceededTimeout(e,t,n=3e5){return t-e>=n}function isDuplicatePage(e,t){return t===null?!1:e===t}async function paginate(e,n,r={}){let i=r.maxIterations??1e4,a=r.timeoutMs??3e5,o=r.onPageComplete,s=r.now??Date.now,c=s(),l=[],u=0,d=null,f;for(;;){if(hasExceededMaxIterations(u,i))return{data:l,pagesRetrieved:u,stoppedBy:`maxIterations`};if(hasExceededTimeout(c,s(),a))return{data:l,pagesRetrieved:u,stoppedBy:`timeout`};let r=await n(e.computeNextInputs({previousResponse:f,currentIteration:u,recordsRetrieved:l.length}));u++,assertSuccessful(r,u);let p=e.extractData(r),m=(0,t.getContentHash)(p);if(isDuplicatePage(m,d))return{data:l,pagesRetrieved:u,stoppedBy:`duplicatePage`};if(l.push(...p),d=m,f=r,o?.({pagesRetrieved:u,totalRecords:l.length}),e.isExhausted(r,u))return{data:l,pagesRetrieved:u,stoppedBy:`exhausted`}}}function createDeltaTokenStrategy(e){return{config:e,applyToInputs({baseInputs:t,checkpoint:n}){return n?.kind===`cursor`?buildInputs(t,e.iterator.in,{[e.iterator.key]:n.value}):t},extractFromPage({block:t,isFinalPage:n}){if(e.response.onlyOnFinalPage&&!n)return null;let r=resolveResponseKey(t,e.response.path);if(r==null)return null;let i=String(r);return i===``?null:{kind:`cursor`,value:i}},finalizeCheckpoint({extractedCheckpoints:e}){return e[e.length-1]??null}}}function formatIncrementalWatermark(e,n){switch(n){case`iso8601`:return e.toISOString();case`unix_seconds`:return String((0,t.dateToEpoch)(e,`seconds`));case`unix_millis`:return String((0,t.dateToEpoch)(e,`ms`))}}function createTimeFilterStrategy(e){let laterOf=(t,n)=>{if(e.format!==`iso8601`)return Number(t)>Number(n)?t:n;let r=Date.parse(t),i=Date.parse(n),a=!Number.isNaN(r),o=!Number.isNaN(i);return a&&o?r>i?t:n:a===o?t>n?t:n:a?t:n};return{config:e,applyToInputs({baseInputs:t,checkpoint:n}){return n?.kind===`timestamp`?buildInputs(t,e.iterator.in,{[e.iterator.key]:n.value}):t},extractFromPage({items:n}){let r=e.response?.updatedAtPath;if(!r)return null;let i=null;for(let e of n){let n=(0,t.getByDotPath)(e,r);if(n==null)continue;let a=String(n);a!==``&&(i=i===null?a:laterOf(i,a))}return i===null?null:{kind:`timestamp`,value:i}},finalizeCheckpoint({runStartTime:t,extractedCheckpoints:n}){let r=null;for(let e of n)e.kind===`timestamp`&&(r=r===null?e.value:laterOf(r,e.value));if(r!==null)return{kind:`timestamp`,value:r};let i=e.safetyBufferSeconds??60,a=t.getTime()-i*1e3;return{kind:`timestamp`,value:formatIncrementalWatermark(new Date(a),e.format)}}}}const Ae={time_filter:createTimeFilterStrategy,delta_token:createDeltaTokenStrategy};function createIncrementalStrategy(e){let t=Ae[e.type];return t(e)}const getConnectorAuthenticationMethods=(e,t)=>{let n=t?.includes(`authentication_guides`);return Object.keys(e.authentication??{}).map(t=>{let r=e.authentication?.[t]?.production,i={type:r?.type??`custom`,label:r?.label||`Custom`,key:t,required_scopes:r?.requiredScopes,...r?.support?.description?{description:r.support.description}:{}};return n&&(i.support=r?.support,i.configFields=r?.configFields,i.configNotices=r?.configNotices,i.setupFields=r?.setupFields,i.setupNotices=r?.setupNotices),i})},getActionAuthenticationMethods=e=>Object.keys(e.authentication??{}).map(t=>{let n=e.authentication?.[t]?.production;return{type:n?.type??`custom`,label:n?.label||`Custom`,key:t,required_scopes:n?.requiredScopes,...n?.support?.description?{description:n.support.description}:{}}}),buildActionAuthentication=(e,n)=>{if((0,t.isMissing)(e.authRequirements))return n;let r=e.authRequirements;return n.filter(e=>e.key in r).map(e=>({...e,required_scopes:r[e.key]}))},buildActionMeta=(e,n,r)=>{let i=buildActionAuthentication(e,n);return{id:e.id,description:e.description,label:e.label.replace(/(^|\s)\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,authentication:i,...e.tags?{tags:e.tags}:{},...(0,t.notMissing)(e.requiredScopes)&&(0,t.isMissing)(e.authRequirements)?{required_scopes:e.requiredScopes}:{},...e.releaseStage?{release_stage:e.releaseStage}:{},...e.effects?.length?{effects:e.effects}:{},...e.annotations&&Object.keys(e.annotations).length?{annotations:e.annotations}:{},...e.userScoped?{user_scoped:!0}:{},...r?.includes(`action_details`)?{action_details:e}:{}}},getScopeDefinitions=e=>Object.values(e.scopeDefinitions??{}),getActionsCount=e=>Object.keys(e.actions??{}).length,getEventActionsMeta=(e,t)=>Object.values(e.events?.actions??{}).map(e=>({id:e.id,label:e.label,description:e.description,tags:e.tags,release_stage:e.releaseStage,...e.requiresManualSetup?{requires_manual_setup:!0}:{},authentication:t})),getEventGuidesMeta=(e,t)=>{if(!t?.includes(`event_guides`))return;let n=e.events?.guides;if(n?.setup)return{setup:n.setup}},getActionsMeta=(e,t)=>{let n=getConnectorAuthenticationMethods(e,t),r=getActionAuthenticationMethods(e),i=Object.values(e.actions??{}).map(e=>buildActionMeta(e,r,t)),a=getScopeDefinitions(e),o=getEventActionsMeta(e,r),s=getEventGuidesMeta(e,t);return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,categories:e.categories,authentication:n,scope_definitions:a.length>0?a:void 0,release_stage:e.releaseStage,owner:e.owner,actions_count:i.length,actions:i,event_actions:o.length>0?o:void 0,documentation:e.documentation,event_guides:s}},getActionsMetaFromConnectors=(e,t)=>e.map(e=>getActionsMeta(e,t)),getActionMeta=(e,t,n)=>{let r=e.actions?.[t];if(r)return buildActionMeta(r,getActionAuthenticationMethods(e),n)},getActionsMetaSummary=(e,t)=>{let n=getConnectorAuthenticationMethods(e,t),r=getActionAuthenticationMethods(e),i=getScopeDefinitions(e),a=getEventActionsMeta(e,r),o=getEventGuidesMeta(e,t);return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,categories:e.categories,authentication:n,scope_definitions:i.length>0?i:void 0,release_stage:e.releaseStage,owner:e.owner,actions_count:getActionsCount(e),event_actions:a.length>0?a:void 0,event_guides:o}},getActionsMetaSummaryFromConnectors=(e,t)=>e.map(e=>getActionsMetaSummary(e,t)),applyReleaseStageResolutionToMeta=(e,n)=>{if((0,t.isMissing)(n))return;let keepReleasedAuthentication=e=>e.filter(e=>n.authenticationKeys.has(e.key)),r=e.actions.filter(e=>n.actionIds.has(e.id)).map(e=>({...e,authentication:keepReleasedAuthentication(e.authentication)})),i=(e.event_actions??[]).filter(e=>n.eventActionIds.has(e.id)).map(e=>(0,t.isMissing)(e.authentication)?e:{...e,authentication:keepReleasedAuthentication(e.authentication)});return{...e,authentication:keepReleasedAuthentication(e.authentication),actions_count:r.length,actions:r,event_actions:i.length>0?i:void 0}},hasOwnKey=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),je=__name(e=>typeof e==`object`&&!!e&&!Array.isArray(e),`isPlainObject`),Me=__name((e,t)=>/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?e?`${e}.${t}`:t:`${e}["${t.replace(/"/g,`\\"`)}"]`,`joinKey`),valueTypeOf=e=>e==null?`null`:typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`mixed`,combineValueTypes=(e,t)=>e===t||t===`null`?e:e===`null`?t:`mixed`,isRecordIdKey=e=>/^\d{4,}$/.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^[0-9a-f]{24,}$/i.test(e),Ne=t.z.uuid(),Pe=t.z.ulid(),isIdentifierValue=e=>typeof e==`string`&&(Ne.safeParse(e).success||Pe.safeParse(e).success&&/[a-z]/i.test(e)),Fe=new Set([`id`,`_id`]),Ie=/(?:^|_)(?:id|uuid|guid)s?$|(?:Id|ID|Uuid|UUID|Guid|GUID)s?$/,fieldPathsOf=(e,t={})=>{let n=t.maxPaths??250,r=new Set,i=new Map,a=new Map,o=new Map,s=new Set,c=new Set,l=!1,recordNeighbours=(e,t,n,r)=>{let i=a.get(e)??{parent:t,siblings:new Set,siblingCount:0};for(let e of n)i.siblings.size<12&&i.siblings.add(e);i.siblingCount=Math.max(i.siblingCount,r),a.set(e,i)},walk=(e,t,a,u)=>{if(r.size>=n){l=!0;return}if(a>12){l=!0;return}if(Array.isArray(e)){for(let n of e)walk(n,`${t}[]`,a+1,u);return}if(je(e)){let n=Object.keys(e).filter(e=>!isRecordIdKey(e)),r=n.slice(0,13),i=isRecordIdKey(u.key)?`*`:u.key;for(let[o,s]of Object.entries(e))walk(s,Me(t,o),a+1,{key:o,parent:i,siblings:r.filter(e=>e!==o).slice(0,12),siblingCount:n.length-+!isRecordIdKey(o)});return}if(t!==``){r.add(t);let n=i.get(t),a=valueTypeOf(e);if(i.set(t,n===void 0?a:combineValueTypes(n,a)),recordNeighbours(t,u.parent,u.siblings,u.siblingCount),Fe.has(u.key.toLowerCase())&&s.add(t),Ie.test(u.key)&&c.add(t),e!=null){let n=o.get(t)??{allIds:!0,seenValue:!1};o.set(t,{allIds:n.allIds&&isIdentifierValue(e),seenValue:!0})}}};return walk(e,``,0,{key:``,parent:``,siblings:[],siblingCount:0}),{paths:[...r],truncated:l,valueTypes:Object.fromEntries(i),neighbours:Object.fromEntries([...a].map(([e,{parent:t,siblings:n,siblingCount:r}])=>[e,{parent:t,siblings:[...n],siblingCount:r}])),identifierPaths:[...r].filter(e=>{if(s.has(e))return!0;let t=o.get(e);return!l&&c.has(e)&&t?.seenValue===!0&&t.allIds})}},Le=/\["((?:[^"\\]|\\.)*)"\]|\[\]|\.?([^.[\]]+)/g,labelKeyOf=e=>[...e.matchAll(Le)].map(([e,t,n])=>e===`[]`?`[]`:isRecordIdKey(t===void 0?n:t.replace(/\\"/g,`"`))?`.*`:t===void 0?`.${n}`:e).join(``).replace(/^\./,``),withActingUser=(e,t)=>!e?.principal||!t?.email||e.principal.userId!==t.id?e:{...e,principal:{...e.principal,email:t.email}},credentialOf=e=>e??`unknown`,identity=e=>({actionRunId:e.actionRunId,actionId:e.actionId,accountSecureId:e.accountSecureId,...e.principal&&{principal:{userId:e.principal.userId,groups:[...e.principal.groups]}},decidedAt:new Date().toISOString()}),policyResultOf=(e,t)=>{let{changed:n,degraded:r,watched:i}=t;return e.evaluated?e.decision===`deny`?e.faulted?`error`:`denied`:r?`error`:n?`partial`:i||e.observed.some(e=>e.decision===`deny`&&e.faulted!==!0)?`monitored`:`allowed`:`skipped`},effectOf=(e,t,n)=>{let{maskedFields:r,redactedClasses:i,observedFields:a}=n;return(t.deniedBy?.policyIds??[]).includes(e)?`refused`:r.some(t=>t.policyIds.includes(e))?`masked`:i.some(t=>t.policyIds.includes(e))?`redacted`:t.observed.some(t=>t.decision===`deny`&&t.faulted!==!0&&t.policyIds.includes(e))?`would-have-refused`:a.some(t=>t.policyIds.includes(e))?`would-have-masked`:t.resolved.some(t=>t.determining.includes(e))?`permitted`:void 0},isAuthored=e=>!(0,l.isBasePermitId)(e),policiesFor=(e,t,n)=>{let{redactedClasses:r}=n,describing=e=>{for(let n of t)if(Object.prototype.hasOwnProperty.call(n.descriptors??{},e))return n.descriptors?.[e]},i=new Map;for(let t of e.resolved)for(let r of t.checked.filter(isAuthored)){if(i.has(r))continue;let a=describing(r),o=effectOf(r,e,n);i.set(r,{id:r,...a&&{name:a.name,version:a.version},level:t.level,mode:t.mode,...o&&{effect:o}})}for(let e of r)if(e.level!==void 0)for(let t of e.policyIds.filter(isAuthored)){if(i.has(t))continue;let n=describing(t);i.set(t,{id:t,...n&&{name:n.name,version:n.version},level:e.level,mode:`enforce`,effect:`redacted`})}return[...i.values()]},toPolicyContext=(e,t,n={})=>{let{maskedFields:r=[],degraded:i=!1,redactedClasses:a=[],observedFields:o=[]}=n,s=e.deniedBy?.policyIds??[],c=policiesFor(e,t.levels??[],{maskedFields:r,redactedClasses:a,observedFields:o});return{result:policyResultOf(e,{changed:r.length>0||a.length>0,degraded:i,watched:o.length>0}),...identity(t),policyIds:s,...e.deniedBy&&{level:e.deniedBy.level},...c.length>0&&{policies:c},...r.length>0&&{maskedFields:r},...o.length>0&&{observedFields:o},...a.length>0&&{redactedClasses:a},...e.observed.length>0&&{observed:e.observed},...e.resolved.length>0&&{resolved:e.resolved}}},preparseFailureContext=e=>({result:`error`,...identity(e),policyIds:[]}),categoryOf=e=>e.categories?.[0]?.toLowerCase()??`unknown`;let $;const Re={warn:(e,t)=>$?.warning({message:e,context:t}),error:(e,t)=>$?.error({code:`PolicyEvaluationError`,message:e,context:t})};let ze;const sharedPolicyEvaluator=e=>($??=e,ze??=(0,l.createEvaluator)(Re)),ownLabelsOf=(e,t)=>e&&hasOwnKey(e,t)?e[t]:[],decideReadFields=async e=>{if(e.policy.levels.length===0||e.paths.length===0)return{evaluated:!1,fields:e.paths.map(e=>({path:e,decision:`allow`,faulted:!1,observed:[]}))};let t=e.evaluator??sharedPolicyEvaluator(e.logger),n=await(0,l.prepareLevels)(t,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(t,async()=>n).decideFields({principal:e.policy.principal,action:`readField`,account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},fields:e.paths.map(t=>({id:t,path:t,labels:ownLabelsOf(e.policy.fieldLabels,labelKeyOf(t))})),context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType),...e.policy.client?{client:e.policy.client}:{}}})},decideInvokeTool=async e=>{if(e.policy.levels.length===0)return{decision:`allow`,evaluated:!1,faulted:!1,observed:[],resolved:[]};let t=e.evaluator??sharedPolicyEvaluator(e.logger),n=await(0,l.prepareLevels)(t,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(t,async()=>n).decide({principal:e.policy.principal,tool:{id:e.action.id,name:e.policy.toolName??e.action.id,labels:[]},account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},args:e.args,context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType),...e.policy.client?{client:e.policy.client}:{}}})},Be=[{id:`email`,group:`PersonalInfo`},{id:`phone_number`,group:`PersonalInfo`},{id:`ssn`,group:`PersonalInfo`},{id:`credit_card`,group:`Financial`}],Ve={email:[`email`,`email_address`],credit_card:[`credit_card`,`credit_debit_card`]},modelLabelsForClasses=e=>{let t=new Set;for(let n of e)for(let e of Ve[n]??[n])t.add(e);return t},classWasApplied=(e,t)=>(Ve[e]??[e]).some(e=>t.has(e)),decideRedactionClasses=async e=>{let t=e.classes??Be;if(e.policy.levels.length===0||t.length===0)return{evaluated:!1,classes:t.map(e=>({class:e.id,decision:`allow`,faulted:!1,observed:[]}))};let n=e.evaluator??sharedPolicyEvaluator(e.logger),r=await(0,l.prepareLevels)(n,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(n,async()=>r).decideRedactionClasses({principal:e.policy.principal,account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},classes:t,context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType)}})},evaluateExternalAccountIdExtractorByConnector=(e,t)=>(0,s.evaluateExternalAccountIdExtractor)(e,t),executeStepFunction=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=s.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===s.StepFunctionName.MAP_FIELDS?{[s.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},definitionVersionOf=e=>[...e].reduce((e,t)=>Math.imul(e^t.charCodeAt(0),16777619)>>>0,2166136261).toString(16).padStart(8,`0`),He=/(?:[A-Za-z_][A-Za-z0-9_]*::)*Label::"((?:[^"\\]|\\.)*)"/g,Ue=/@unlabelled\(\s*"allow"\s*\)/,isRecord=e=>typeof e==`object`&&!!e&&!Array.isArray(e),labelsNamedBy=e=>typeof e==`string`?[...e.matchAll(He)].map(([,e])=>e.replace(/\\"/g,`"`)):Array.isArray(e)?e.flatMap(labelsNamedBy):isRecord(e)?[...typeof e.type==`string`&&/(^|::)Label$/.test(e.type)&&typeof e.id==`string`?[e.id]:[],...Object.values(e).flatMap(labelsNamedBy)]:[],policySetsOf=e=>e.flatMap(e=>[e.enforce,e.monitor].filter(e=>e!==void 0)),labelsReferencedBy=e=>[...new Set(policySetsOf(e).flatMap(e=>[...labelsNamedBy(e.staticPolicies),...labelsNamedBy(e.templates)]))],allowsUnlabelled=e=>typeof e==`string`?Ue.test(e):isRecord(e)&&isRecord(e.annotations)?e.annotations.unlabelled===`allow`:!1,unlabelledAllowPolicyIdsOf=e=>new Set(policySetsOf(e).flatMap(e=>{let t=isRecord(e.staticPolicies)?Object.entries(e.staticPolicies):[],n=new Set(Object.entries(e.templates??{}).filter(([,e])=>allowsUnlabelled(e)).map(([e])=>e));return[...t.filter(([,e])=>allowsUnlabelled(e)).map(([e])=>e),...(e.templateLinks??[]).filter(e=>n.has(e.templateId)).map(e=>e.newId)]})),We=new Map([[`request`,`GET`],[`paginated_request`,`GET`],[`soap_request`,`POST`],[`soap_paginated_request`,`POST`],[`download_file`,`GET`],[`upload_file`,`POST`],[`upload_binary`,`POST`]]),Ge=__name(e=>{if(!isRecord(e))return[];let t=Array.isArray(e.stepFunctions)?e.stepFunctions:[],n=isRecord(e.stepFunction)?[e.stepFunction]:[];return[...t,...n].filter(isRecord)},`stepFunctionsOf`),requestOf=e=>{let t=We.get(e.functionName),n=e.params??{};return!t||typeof n.url!=`string`||n.url===``?[]:[`${typeof n.method==`string`?n.method.toUpperCase():t} ${n.url}`]},providerRequestsOf=e=>[...new Set(Object.values(isRecord(e.steps)?e.steps:{}).flatMap(e=>Ge(e).flatMap(requestOf)))].slice(0,5),shapeOf=(e,t,n)=>{let r=e.flatMap(e=>t&&hasOwnKey(t,e)?[t[e]]:[]),i=e.flatMap(e=>n&&hasOwnKey(n,e)?[n[e]]:[]);return{valueType:r.length===0?`mixed`:r.reduce((e,t)=>combineValueTypes(e,t)),parent:i[0]?.parent??``,siblings:[...new Set(i.flatMap(e=>e.siblings))].slice(0,12),siblingCount:Math.max(0,...i.map(e=>e.siblingCount))}},Ke=/^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$/,declaredPaginationPathsOf=e=>{let t=isRecord(e.dataSync)?e.dataSync:void 0,n=t?.pagination,r=t?.incremental;return[n?.type===`cursor`?n.response?.nextKey:void 0,r?.type===`delta_token`?r.response?.path:void 0].filter(e=>typeof e==`string`&&Ke.test(e))},isWithin=(e,t)=>e===t||e.startsWith(`${t}.`)||e.startsWith(`${t}[`),unlabelledPathsOf=e=>{let t=declaredPaginationPathsOf(e.action);return new Set([...e.identifierPaths??[],...e.paths.filter(e=>t.some(t=>isWithin(e,t)))])},withoutStoredLabels=(e,t)=>{let n=e.policy.fieldLabels,r=new Set([...t].map(labelKeyOf));return!n||r.size===0?e:{...e,policy:{...e.policy,fieldLabels:Object.fromEntries(Object.entries(n).filter(([e])=>!r.has(e)))}}},answersWithin=async(e,t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await Promise.race([e(t,r.signal),new Promise((e,t)=>r.signal.addEventListener(`abort`,()=>t(Error(`Field labelling deadline passed`))))])}finally{clearTimeout(i)}},createLabellingDecideReadFields=e=>{let t=e.decide??decideReadFields;return async n=>{let r=unlabelledPathsOf(n),i=withoutStoredLabels(n,r),a=i.policy.labelDefinitions??{},isDefined=e=>hasOwnKey(a,e),o=labelsReferencedBy(i.policy.levels),s=o.filter(e=>!isDefined(e));s.length>0&&i.logger?.warning({message:`Rules name labels with no definition, so no field can be classified under them: ${s.join(`, `)}`,category:`runAction`});let c=o.filter(isDefined);if(c.length===0)return t(i);let l=i.policy.fieldLabels??{},u=new Map;for(let e of i.paths){let t=labelKeyOf(e);!hasOwnKey(l,t)&&!r.has(e)&&u.set(t,[...u.get(t)??[],e])}if(u.size===0)return t(i);let d=providerRequestsOf(i.action),f=[...u].flatMap(([e,t])=>{let n={fieldPath:e,connector:i.account.providerKey,action:i.action.id,...i.action.description&&{actionDescription:i.action.description},requests:d,...shapeOf(t,i.valueTypes,i.neighbours)};return c.map(t=>({labelKey:e,label:t,definition:a[t],evidence:n}))}),p=await answersWithin(e.labeller,f,e.deadlineMs).catch(e=>(i.logger?.warning({message:`Field labelling failed, unanswered fields fall back to every referenced label: ${e instanceof Error?e.message:String(e)}`,category:`runAction`}),{answers:[],modelVersion:``})),m=new Map(p.answers.map(e=>[`${e.labelKey}|${e.label}`,e])),h=[...u.keys()].filter(e=>c.some(t=>!m.has(`${e}|${t}`))),g=new Set(h),labelsOf=(t,n)=>c.filter(r=>{let i=m.get(`${t}|${r}`);return i===void 0?n:i.score>=e.thresholdFor(r)}),withLabels=e=>({...l,...Object.fromEntries([...u.keys()].map(t=>[t,labelsOf(t,e)]))});e.onLabelled?.({decisions:p.answers.map(e=>({labelKey:e.labelKey,label:e.label,score:e.score,modelVersion:p.modelVersion,definitionVersion:definitionVersionOf(isDefined(e.label)?a[e.label]:``),evidence:`shape`})),unanswered:h});let _=await t({...i,policy:{...i.policy,fieldLabels:withLabels(!0)}}),v=unlabelledAllowPolicyIdsOf(i.policy.levels);if(g.size===0||v.size===0)return _;let y=await t({...i,policy:{...i.policy,fieldLabels:withLabels(!1)}}),b=new Map(y.fields.map(e=>[e.path,e]));return{..._,fields:_.fields.map(e=>{let t=e.deniedBy?.policyIds??[];return e.decision===`deny`&&!e.faulted&&g.has(labelKeyOf(e.path))&&t.length>0&&t.every(e=>v.has(e))?b.get(e.path)??e:e})}}},qe=`[redacted by policy]`,isPlainObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),joinKey=(e,t)=>/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?e?`${e}.${t}`:t:`${e}["${t.replace(/"/g,`\\"`)}"]`,maskFields=(e,t,n)=>{let r=new Set(t);if(r.size===0&&n===void 0)return{payload:e,masked:[]};let i=new Set,walk=(e,t)=>{if(t!==``&&r.has(t))return i.add(t),qe;if(Array.isArray(e))return e.map(e=>walk(e,`${t}[]`));if(isPlainObject(e)){let n={};for(let[r,i]of Object.entries(e))n[r]=walk(i,joinKey(t,r));return n}return t!==``&&n&&!n.has(t)?(i.add(t),qe):e};return{payload:walk(e,``),masked:[...i]}},createBlockContext=({category:e,connectorKey:n,connectorVersion:r,connectorOwner:i,connectorProfileId:a,authConfigKey:o,environment:s=`production`,action:c,accountSecureId:l,projectSecureId:u,organizationId:d,originOwnerId:f,originOwnerName:p,sourceType:m,sourceId:h,authType:g,authId:_,sessionId:v,agentId:y,userAgent:b,ipAddress:x,transportType:S,streamType:C,flowType:w,sourceValue:T})=>({organizationId:d,projectSecureId:u,accountSecureId:l,connectorKey:n,connectorVersion:r,connectorOwner:i,connectorProfileId:a,category:e,service:``,resource:``,originOwnerId:f,originOwnerName:p,sourceType:m,sourceId:h,authType:g,authId:_,sessionId:v,agentId:y,userAgent:b,ipAddress:x,transportType:S,streamType:C,schema:c?.schema?.key,actionType:c?.actionType??`unknown`,authenticationType:o,environment:s,actionRunId:(0,t.generateActionRunId)(),flowType:w,sourceValue:T}),getTestActions=(e,t,n)=>e.authentication?.[t]?.[n]?.testActions,normalizeActingUser=e=>{if(!e)return;let t=e.email?.trim().toLowerCase();return{id:e.id,...t&&{email:t}}},actingUserRefusal=(e,t,n)=>e.userScoped===!0&&!t?.email?.trim()?new ActingUserRequiredError(n,`Action '${e.id}' answers for the acting user and the call carries no user email`):void 0,validateActingUser=(e,t,n)=>{let r=actingUserRefusal(e,t,n);if(r)throw r},validateAuthTypeCompatibility=(e,n,r)=>{if(!Object.prototype.hasOwnProperty.call(e,`authRequirements`)||(0,t.isMissing)(n))return;let i=e.authRequirements;if(!(0,t.isMissing)(i)&&!(n in i)){let t=Object.keys(i).join(`, `);throw new IncompatibleAuthTypeError(r,`Action '${e.id}' is not compatible with authentication type '${n}'. Compatible types: ${t}`)}};function extractStrings(e){let t=[];function traverse(e){typeof e==`string`?t.push(e):Array.isArray(e)?e.forEach(traverse):e&&typeof e==`object`&&Object.values(e).forEach(traverse)}return traverse(e),t}function estimateResponseSize(e){try{let t=JSON.stringify(e);return{bytes:Buffer.byteLength(t,`utf8`),words:extractStrings(e).join(` `).split(/\s+/).filter(Boolean).length}}catch{return{bytes:0,words:0}}}function shouldSkipDefender(e,t){if(!t?.enabled)return{skip:!0,reason:`disabled`};let n=t.maxResponseSize??1048576,r=t.maxResponseWords??1e4,i=estimateResponseSize(e);return i.bytes>n||i.words>r?(t.largeResponseBehavior??`skip`)===`skip`?{skip:!0,reason:`size_limit`,size:i}:{skip:!1,size:i}:{skip:!1}}const decodeInputCompositeIdentifiers=e=>{let n=e.action?.compositeIdentifiers,r={...e.inputs??{}};if(!n?.enabled||(0,t.isMissing)(r))return e;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{});return processLevel(r,{version:n.version??s.COMPOSITE_ID_LATEST_VERSION,aliases:i},e.logger),{...e,inputs:r}},processLevel=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))processCompositeId(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)processLevel(e,t,n);else typeof i==`object`&&i&&processLevel(i,t,n)}},processInputElements=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,s.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},setDecodedIds=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},shouldSimplifyComponent=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},setSimplifiedIds=(e,t,n,r,i)=>{n.every(shouldSimplifyComponent)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},handleCompositeIdError=(e,t,n)=>{e instanceof s.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},processCompositeId=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=processInputElements(o,t,r,i);setDecodedIds(n,t,s,a),setSimplifiedIds(n,t,s,c,a)}catch(e){handleCompositeIdError(e,t,i)}},Je=`remote_`,encodeResultCompositeIdentifiers=e=>{let n=e.action?.compositeIdentifiers;if(!n?.enabled)return e;let r=`data`,i=e.outputs?.[r];if((0,t.isMissing)(i))return e;let a=Array.isArray(i)?i.map(e=>mapCompositeIds(e,n)):mapCompositeIds(i,n);return{...e,outputs:{...e.outputs??{},[r]:a}}},mapCompositeIds=(e,n)=>{let r=mapCompositeIdsFromInference(mapConfiguredCompositeIds(e,n));return{...e,...(0,t.isObject)(r)?r:{}}},mapConfiguredCompositeIds=(e,t)=>{let n=t.version??s.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=(0,s.encodeCompositeId)(a.length===1?a[0]:{identifiers:a},{version:n,aliases:Object.keys(i).length>0?i:void 0});r[t.targetFieldKey]=o,t.remote&&(r[`${Je}${t.remote}`]=e[t.remote])}),{...e,...r}},isIdField=e=>e===`id`||/.+_id(s)?$/.test(e),isValidStringArray=e=>Array.isArray(e)&&e.every(e=>(0,t.isString)(e)&&e.length>0),shouldSkipEncoding=(e,t)=>(0,s.isCompositeId)(e)||t.startsWith(Je),encodeStringValue=(e,t)=>{try{return(0,s.encodeCompositeId)({key:e,value:t},{version:s.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},processStringArrayField=(e,n,r)=>{r[e]=n.map(n=>(0,t.isString)(n)&&n.length>0&&!(0,s.isCompositeId)(n)?encodeStringValue(e,n):n),r[`${Je}${e}`]=n},processStringField=(e,t,n)=>{shouldSkipEncoding(t,e)||(n[e]=(0,s.encodeCompositeId)({key:e,value:t},{version:s.COMPOSITE_ID_LATEST_VERSION}),n[`remote_${e}`]=t)},processIdField=(e,n,r)=>{isValidStringArray(n)?processStringArrayField(e,n,r):(0,t.isString)(n)&&n.length>0&&processStringField(e,n,r)},mapCompositeIdsFromInference=e=>{if(Array.isArray(e))return e.map(e=>mapCompositeIdsFromInference(e));if(!(0,t.isObject)(e))return e;let n={...e};for(let[r,i]of Object.entries(e))((0,t.isObject)(i)||Array.isArray(i)&&i.length>0&&(0,t.isObject)(i[0]))&&(n[r]=mapCompositeIdsFromInference(i)),isIdField(r)&&processIdField(r,i,n);return n},getPageSize=(e,n)=>{let r=Number(e.inputs?.page_size);return(0,t.notMissing)(e.inputs?.page_size)&&(0,t.isNumber)(r)&&!Number.isNaN(r)?r:e.action?.cursor?.pageSize??n},virtualPaginateResult=(e,n,r,i)=>{let a=(0,t.isMissing)(e)?void 0:e.data,o=Object.keys(r).length+1,c=(0,s.isCursorEmpty)({cursor:i,ignoreStepIndex:o});if(!(0,t.isObject)(e)||(0,t.isMissing)(a)||(a?.length??0)<=n)return{result:e,next:(0,t.notMissing)(i)&&!c?(0,s.minifyCursor)(i):null};let l=i?.remote?.[o]?.pageNumber??1,u=(l-1)*n,d=u+n,f=a.slice(u,d),p=a.length>d||!c,m=(0,s.updateCursor)({cursor:i,stepIndex:o,pageNumber:l+1});return{result:{...e,data:f},next:p?(0,s.minifyCursor)(m):null}},refuse=(e,t,n)=>({...e,outputs:void 0,streamOutput:void 0,response:{successful:!1,statusCode:t,message:n}}),messageOf=e=>e instanceof Error?e.message:String(e),parseCalleeInputs=(e,t)=>{try{return{inputs:parseActionInputs(e,{path:t?.path,query:t?.query,body:t?.body,headers:t?.headers})}}catch(e){return{error:describeInputIssues(e)}}},describeInputIssues=e=>e instanceof t.z.ZodError?e.issues.map(e=>{let t=e.path.map(String),n=t[0]??`body`,r=t.slice(1).join(`.`);return r?`${n}.${r}: ${e.message}`:`${n}: ${e.message}`}).join(`; `):messageOf(e),usesCallAction=e=>(0,s.stepsUseFunction)(e?.steps,s.StepFunctionName.CALL_ACTION),expandCalleeCursor=(e,n,r)=>{let i=r?.query?.next;if(!(0,t.notMissing)(i)||n.actionType!==`list`)return{};if(e.action?.cursor.enabled)return{error:`a paginated action cannot forward a cursor to a nested call, because nothing relates its pages to the callee's. Call '${n.id}' from an action that is not itself paginated`};if(typeof i!=`string`)return{error:`'next' must be a cursor token, not an expanded cursor`};let a=(0,s.expandCursor)(i);return a===null?{error:`'next' is not a valid cursor`}:{cursor:a}},buildCalleeBlock=(e,t,n,r)=>({connector:e.connector,context:{...e.context,actionType:t.actionType,schema:t.schema?.key},credentials:e.credentials,user:e.user,httpClient:e.httpClient,olapClient:e.olapClient,settings:e.settings,logger:e.logger,debug:e.debug,scopes:e.scopes,emitEvent:e.emitEvent,action:t,inputs:n,callAction:void 0,steps:{},intermediateSteps:{},iterator:void 0,result:void 0,outputs:void 0,streamOutput:void 0,response:void 0,statistics:void 0,defenderMetadata:void 0,policyMetadata:void 0,responseHeaders:void 0,nextCursor:r,fieldConfigs:[]}),createCallActionRunner=(e,n)=>async({actionId:r,inputs:i})=>{let a=e.connector;if(!(0,t.notMissing)(a))return refuse(e,500,`call_action cannot resolve a target: no connector on the block.`);let o=findActionByActionId(a,r);if(!(0,t.notMissing)(o))return refuse(e,500,`call_action target '${r}' is not an action of connector '${a.key}'.`);if(n.ancestors.has(o.id))return refuse(e,500,`call_action would re-enter action '${o.id}', which is already running. Chain: ${[...n.ancestors,o.id].join(` -> `)}.`);if(n.depth>=4)return refuse(e,500,`call_action exceeded the maximum nesting depth of 4 while calling '${o.id}'.`);if(n.budget.remaining<=0)return refuse(e,500,`call_action exceeded the maximum of 32 nested calls per request while calling '${o.id}'.`);try{validateAuthTypeCompatibility(o,e.context.authenticationType,e.context),validateActingUser(o,e.user,e.context)}catch(t){return refuse(e,403,messageOf(t))}let s=parseCalleeInputs(o,i);if(`error`in s)return refuse(e,400,`call_action inputs for '${o.id}' are invalid: ${s.error}`);let c=expandCalleeCursor(e,o,i);if(`error`in c)return refuse(e,400,`call_action cannot page '${o.id}': ${c.error}.`);--n.budget.remaining;let l=buildCalleeBlock(e,o,s.inputs,c.cursor);usesCallAction(o)&&(l.callAction=createCallActionRunner(l,{...n,depth:n.depth+1,ancestors:new Set([...n.ancestors,o.id])}));let u=await n.executeSteps(l);return(0,t.notMissing)(u.streamOutput)?(u.streamOutput.stream?.destroy(),refuse(e,500,`Action '${o.id}' returns a stream, which cannot be consumed by call_action. Call it directly instead.`)):u},createRootCallActionRunner=(e,t)=>createCallActionRunner(e,{...t,depth:0,ancestors:new Set(e.action?.id?[e.action.id]:[]),budget:{remaining:32}}),rawHeadersOf=e=>{if(!e.successful||e.skipped)return;let n=Array.isArray(e.output?.raw)?e.output.raw.at(-1):e.output?.raw,r=(0,t.isObject)(n)?n.headers:void 0;return(0,t.isObject)(r)?r:void 0},lowercaseKeys=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),extractDataSyncResponseHeaders=e=>{let n=e.action?.dataSync;if(!(e.context?.sourceType===s.SourceType.DataSyncV2&&((0,t.notMissing)(n?.pagination)||(0,t.notMissing)(n?.incremental))))return;let r=Object.values(e.steps??{}).reverse().map(rawHeadersOf).find(t.notMissing);return r?lowercaseKeys(r):void 0},runStepAction=async({block:e,buildStepFunction:t=s.StepFunctionsFactory.build,virtualPaginateResultFn:n=virtualPaginateResult,encodeResultCompositeIds:r=encodeResultCompositeIdentifiers,decodeInputCompositeIds:i=decodeInputCompositeIdentifiers})=>{let a=i(e);return r(await executeStepsWorkflow({block:usesCallAction(a.action)?{...a,callAction:createRootCallActionRunner(a,{executeSteps:e=>executeStepsWorkflow({block:e,buildStepFunction:t,virtualPaginateResultFn:n})})}:a,buildStepFunction:t,virtualPaginateResultFn:n}))},captureErrorDetails=(e,n)=>{e.errorStatusCode??=n?.statusCode??500,!(0,t.notMissing)(e.errorMessage)&&typeof n?.message==`string`&&(e.errorMessage=n.message),e.errorData??=n?.data,e.errorRaw??=n?.raw},buildConditionContext=e=>{let t=(0,s.buildExpressionContext)(e,{includeCredentials:!0});return`action`in e&&(t.action=e.action),`nextCursor`in e&&(t.nextCursor=e.nextCursor),`scopes`in e&&(t.scopes=e.scopes),t},resolveConditionOutcome=(e,t)=>{if(!e.condition)return{kind:`run`};let{errored:n,value:r,error:i}=(0,c.evaluateConditionExpression)(e.condition,buildConditionContext(t));if(!n)return r?{kind:`run`}:{kind:`skip`,message:`Step skipped due to condition not met.`};let a=e.onConditionError??!1;return a===`break`?{kind:`fail`,message:`Step condition failed to evaluate.`,error:i}:a===!0?{kind:`run`,message:`Step ran due to a condition evaluation error.`}:{kind:`skip`,message:`Step skipped due to a condition evaluation error.`}},stampConditionNote=(e,n,r)=>{let i=e.steps?.[n];return!i||i.successful===!1||(0,t.notMissing)(i.message)?e:{...e,steps:{...e.steps,[n]:{...i,message:r}}}},buildStepParamsForFunction=(e,n,r)=>{let i=s.StepFunctionsRegistry[e.functionName]?.[`v${e.version??1}`],a=(0,t.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return n.action?.cursor.enabled&&a?{...e.params??{},cursor:{token:n.nextCursor?.remote?.[r]?.providerPageCursor,position:n.nextCursor?.remote?.[r]?.position}}:e.params??{}},buildStepParams=(e,t,n)=>e.stepFunction?buildStepParamsForFunction(e.stepFunction,t,n):{},handleStepFailure=async(e,t,n,r,i,a,o,s)=>{let c=await addStepResultToBlock({block:e,stepId:t,stepIndex:n,successful:!1,functionOutput:r,startTime:o,endTime:s});return(i.ignoreError??!1)||(a.hasFatalError=!0,captureErrorDetails(a,r.output)),c},isCredentialRecoveryStep=(e,t)=>t.action?.actionType===`refresh_token`&&!(0,s.isForeachStep)(e)&&e.stepFunction?.functionName===s.StepFunctionName.MAP_FIELDS,executeStep=async(e,n,r,i,a,o,c)=>{let l=new Date,u=r[e];if(a.hasFatalError&&!isCredentialRecoveryStep(u,i))return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:`Step skipped due to previous error.`,startTime:l,endTime:l});let d=resolveConditionOutcome(u,i);if(d.kind===`skip`)return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!0,skipped:!0,message:d.message,startTime:l,endTime:l});if(d.kind===`fail`){let r=d.error??d.message;return a.errorStatusCode??=500,(0,t.notMissing)(a.errorMessage)||(a.errorMessage=d.message,a.errorData??={error:r}),a.hasFatalError=!0,await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:d.message,errors:[{message:r}],startTime:l,endTime:l})}let f=a.hasFatalError?await executeCredentialRecoveryStep(e,n,u,i,a,o,c):(0,s.isForeachStep)(u)?await executeForeachStep(e,n,u,i,a,o,c):await executeSimpleStep(e,n,u,i,a,o,c);return d.message?stampConditionNote(f,e,d.message):f},withoutFailedStepOutputs=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,t.successful?t:{...t,output:void 0}])),executeCredentialRecoveryStep=async(e,n,r,i,a,o,s)=>{let c=await executeSimpleStep(e,n,r,{...i,steps:withoutFailedStepOutputs(i.steps)},a,o,s),l=c.steps?.[e];return{...c,steps:(0,t.notMissing)(l)?{...i.steps,[e]:l}:i.steps}},executeSimpleStep=async(e,t,n,r,i,a,o)=>{let c=new Date,l=n.stepFunction;if(!l)return await addStepResultToBlock({block:r,stepId:e,stepIndex:t,successful:!1,message:`Step function is not defined.`,startTime:c,endTime:new Date});let u=a.buildStepFunction({functionName:l.functionName,version:l.version,validateSchemas:!0}).fn,d=await u({block:r,params:buildStepParams(n,r,t)});if(d.successful===!1)return await handleStepFailure(r,e,t,d,n,i,c,new Date);if(d.streamOutput)return o?await addStepResultToBlock({block:{...d.block,streamOutput:d.streamOutput},stepId:e,stepIndex:t,successful:!0,functionOutput:d,startTime:c,endTime:new Date}):(i.hasFatalError=!0,i.errorStatusCode=500,i.errorMessage=`Stream output can only be used in the final step of an action. Move the streaming step to the end or use responseMode: "buffer".`,await addStepResultToBlock({block:r,stepId:e,stepIndex:t,successful:!1,message:`Stream output can only be used in the final step of an action. Move the streaming step to the end or use responseMode: "buffer".`,startTime:c,endTime:new Date}));let f=r.action?.cursor.enabled?(0,s.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:d.output?.next,position:d.output?.position}):void 0;return await addStepResultToBlock({block:{...d.block,nextCursor:f},stepId:e,stepIndex:t,successful:!0,functionOutput:d,startTime:c,endTime:new Date})},executeForeachStep=async(e,n,r,i,a,o,l)=>{let u=new Date,d=(0,c.safeEvaluate)(r.iterator,i);if(!Array.isArray(d))return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:`Step skipped because iterator expression did not return an array.`,startTime:u,endTime:u});let f=(0,s.stepFunctionsOf)(r);if(f.length===0)return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,message:`No step functions defined for foreach step.`,startTime:u,endTime:new Date});let p=[],m=i,h,g={};for(let[i,s]of d.entries()){let c={...m,iterator:{item:s,index:i}};for(let l of f){let d=o.buildStepFunction({functionName:l.functionName,version:l.version,validateSchemas:!0}).fn,f=buildStepParamsForFunction(l,c,n),p=await d({block:c,params:f});if(h=p,p.successful===!1&&!(r.ignoreError??!1))return a.hasFatalError=!0,captureErrorDetails(a,p.output),g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:!1,output:p.output,errors:p.errors}},await addStepResultToBlock({block:{...m,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!1,functionOutput:p,startTime:u,endTime:new Date});if(c={...p.block,iterator:{item:s,index:i,current:p.output}},p.streamOutput)return a.hasFatalError=!0,a.errorStatusCode=500,a.errorMessage=`Stream output is not supported in foreach steps.`,g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:!1,message:`Stream output is not supported in foreach steps.`}},await addStepResultToBlock({block:{...m,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!1,message:`Stream output is not supported in foreach steps.`,startTime:u,endTime:new Date})}m=c,g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:h?.successful??!0,output:h?.output,errors:h?.errors}},h?.output&&p.push(h.output)}let _=i.action?.cursor.enabled?(0,s.updateCursor)({cursor:i.nextCursor,stepIndex:n,providerPageCursor:h?.output?.next,position:h?.output?.position}):void 0,v={block:m,successful:!0,output:{data:p}};return await addStepResultToBlock({block:{...m,nextCursor:_,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!0,functionOutput:v,startTime:u,endTime:new Date})},buildFinalResponse=(e,n,r,i,o)=>{let s=!r.hasFatalError,c=s?e.action?.responses.success.statusCode??200:r.errorStatusCode??500,l=s?void 0:r.errorMessage??e.action?.responses?.errors?.[c]?.description??a.HttpErrorMessages?.[c]??`Error while processing the request`,u=s?{}:{...r.errorData===void 0?{}:{data:r.errorData},...r.errorRaw===void 0?{}:{raw:r.errorRaw}};if(n.streamOutput)return{...n,response:{successful:s,statusCode:c,message:l,...u}};let d=(0,t.notMissing)(o)&&(0,t.isObject)(o.result)?{next:o.next,...o.result}:i;return{...n,outputs:d,response:{successful:s,statusCode:c,message:l,...u}}},executeStepsWorkflow=async({block:e,buildStepFunction:t=s.StepFunctionsFactory.build,virtualPaginateResultFn:n=virtualPaginateResult})=>{let r=e.action?.steps||{},i={...e},a=Object.keys(r),o=getPageSize(e,25),c={hasFatalError:!1,errorStatusCode:null},l={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries()){let n=e===a.length-1;i=await executeStep(t,e,r,i,c,l,n)}let u=e.action?.result?evaluateResult(e.action.result,i):void 0,d=e.action?.cursor.enabled?n(u,o,r,i.nextCursor):void 0,f=extractDataSyncResponseHeaders(i);return buildFinalResponse(e,f?{...i,responseHeaders:f}:i,c,u,d)},evaluateResult=(e,n)=>{let r=(0,s.buildExpressionContext)(n);return(0,t.isObject)(e)?(0,c.safeEvaluateRecord)(e,r):(0,c.safeEvaluate)(e,r)},addStepResultToBlock=async({block:e,stepId:t,stepIndex:n,successful:r,functionOutput:i,skipped:a,message:o,errors:s,startTime:c,endTime:l})=>({...e,steps:{...e.steps,[t]:{successful:r??i?.successful??!1,errors:s??i?.errors,output:i?.output,skipped:a,message:o,statistics:{startTime:c,endTime:l}}}}),Ye={drop:!0,truncate:!0,complete:!0},isTruncationMode=e=>typeof e==`string`&&Ye[e]===!0,getOlapOptions=e=>{let n=e?.olap;if((0,t.isMissing)(n))return{};let r=n.logs,i=r&&typeof r.enabled==`boolean`?{enabled:r.enabled}:void 0,a=n.advanced,o=a?{}:void 0;return a&&o&&(typeof a.enabled==`boolean`&&(o.enabled=a.enabled),typeof a.ttl==`number`&&(o.ttl=a.ttl),typeof a.errorsOnly==`boolean`&&(o.errorsOnly=a.errorsOnly),typeof a.includeBackground==`boolean`&&(o.includeBackground=a.includeBackground),isTruncationMode(a.truncation)&&(o.truncation=a.truncation),typeof a.piiRedactionEnabled==`boolean`&&(o.piiRedactionEnabled=a.piiRedactionEnabled)),{logs:i,advanced:o}},recordActionResult=async({action:e,resultBlock:n,mode:r,organizationId:i,pathParams:a,queryParams:o,body:s,headers:c,source:l,isBackground:u,settings:d,logger:p,policyContext:m,refusal:h})=>{if((0,t.isMissing)(e)){p?.warning({message:`action missing, skipping recording action result`});return}let g=n.olapClient;if((0,t.isMissing)(g)){p?.warning({message:`olap client is missing, skipping recording action result`});return}let _=getOlapOptions(d),v=n.context,y={actionId:e.id,actionRunId:v.actionRunId||`missing`,mode:r,connectorKey:v.connectorKey,connectorVersion:v.connectorVersion,connectorOwner:v.connectorOwner,connectorProfileId:v.connectorProfileId,actionType:v.actionType,category:v.category,organizationId:i,projectSecureId:v.projectSecureId,accountSecureId:v.accountSecureId,originOwnerId:v.originOwnerId,originOwnerName:v.originOwnerName,sourceType:l?.sourceType,sourceId:l?.sourceId,authType:l?.authType,authId:l?.authId,sessionId:l?.sessionId,agentId:l?.agentId,userAgent:l?.userAgent,ipAddress:l?.ipAddress,transportType:l?.transportType,streamType:l?.streamType,httpMethod:e?.entrypointHttpMethod,url:e?.entrypointUrl,pathParams:a,queryParams:o,body:s,headers:c,isBackground:u,startTime:n.statistics?.startTime},b=Object.values(n.steps??{}).some(e=>e?.successful===!1||(0,f.hasErrorEntries)(e?.errors)),x={success:n.response?.successful??!1,statusCode:n.response?.statusCode,body:n.outputs??void 0,message:n.response?.message,hasStepErrors:b,endTime:n.statistics?.endTime,defenderContext:n.defenderMetadata,...m&&{policyContext:m},...h&&{refusal:h}};try{await g.recordAction(y,x,_);let r=e.steps||{},a=Object.keys(r).map((e,a)=>{let o=n.steps?.[e];if((0,t.isMissing)(o))return null;let s=r[e],c=s?.stepFunction?.functionName,l=s?.stepFunction?.version,u=s&&`iterator`in s&&n.intermediateSteps?.[e]?Object.keys(n.intermediateSteps[e]).length:void 0,d=typeof o.output?.statusCode==`number`?o.output.statusCode:void 0;return{input:{actionRunId:y.actionRunId,actionMode:y.mode,actionSuccess:x.success,stepIndex:a,stepId:e,organizationId:i,projectSecureId:v.projectSecureId,accountSecureId:v.accountSecureId,inputs:n.inputs,...c&&{stepFunctionName:c},...l&&{stepFunctionVersion:l},...u!==void 0&&{stepIterations:u},startTime:o.statistics?.startTime},result:{success:o.successful,statusCode:d,message:o.message,outputs:o.output,errors:o.errors,skipped:o.skipped,endTime:o.statistics?.endTime}}}).filter(t.notMissing);a.length>0&&await g.recordSteps(a,_)}catch(e){p?.warning({message:`Failed to record action result: ${e.message}`,error:e})}},Xe={action_id:`action`,path:`action`,test_actions:`test_action`,refresh_authentication:`refresh_authentication`},buildTier2Config=e=>{let t={};return e?.highRiskThreshold!==void 0&&(t.highRiskThreshold=e.highRiskThreshold),e?.mediumRiskThreshold!==void 0&&(t.mediumRiskThreshold=e.mediumRiskThreshold),e?.multiheadEnabled&&(t.multihead={mainThreshold:.64,auxThreshold:.458}),Object.keys(t).length>0?{tier2Config:t}:{}},recordingFieldsFromParams=e=>({mode:e.mode,organizationId:e.account.organizationId,pathParams:e.pathParams,queryParams:e.queryParams,body:e.body,headers:e.headers,source:e.source,settings:e.settings,logger:e.logger}),applyDefenderToBlock=async(e,n,r,i)=>{if(!r?.defender?.enabled)return e;let{defenderMetadata:a,outputs:o,response:s}=await n({outputs:e.outputs,streamOutput:`streamOutput`in e?e.streamOutput:void 0,toolName:e.action?.id??e.context?.connectorKey??``,sourceType:e.context?.sourceType,settings:r,logger:i});return{...e,defenderMetadata:a,...(0,t.notMissing)(o)&&{outputs:o},...(0,t.notMissing)(s)&&{response:s}}};let Ze;const sharedRedactor=()=>Ze??=(0,d.createPiiRedaction)({enableTier2:!0}),applyRedactionToBlock=async(e,t,n)=>{if(!t||`streamOutput`in e&&e.streamOutput)return{block:e,redactedClasses:[]};let r=!1;try{if(!(typeof e.outputs==`string`&&e.outputs.length>0||fieldPathsOf(e.outputs).paths.length>0))return{block:e,redactedClasses:[]};let i=(await decideRedactionClasses({policy:t.policy,account:t.account,action:t.action,...t.authType&&{authType:t.authType},...t.sessionId&&{sessionId:t.sessionId},logger:n})).classes.filter(e=>e.decision===`deny`);if(i.length===0)return{block:e,redactedClasses:[]};r=!0;let a=i.filter(e=>e.faulted);a.length>0&&n?.error({code:`PolicyRedactionFaulted`,message:`PII redaction decision faulted; redacting ${a.length} class(es) to fail safe: ${a.map(e=>e.class).join(`, `)}`,category:`runAction`});let o=modelLabelsForClasses(i.map(e=>e.class)),{value:s,appliedLabels:c,modelAvailable:l,skipped:u}=await(0,d.scrubObjectDetailedAsync)(e.outputs,sharedRedactor(),o,n),f=i.filter(e=>classWasApplied(e.class,c)),p=u===`oversized`?i:l?[]:i.filter(e=>!f.includes(e)&&(0,d.labelledPatternsFor)(modelLabelsForClasses([e.class]),sharedRedactor().getConfig().entropy.piiPatterns).length===0);if(p.length>0){let e=p.map(e=>e.class).join(`, `);n?.error(u===`oversized`?{code:`PolicyRedactionOversized`,message:`PII redaction skipped: response exceeds the redaction size limit; ${p.length} forbidden class(es) not redacted: ${e}`,category:`runAction`}:{code:`PolicyRedactionUnavailable`,message:`PII redaction model unavailable; ${p.length} forbidden class(es) not redacted: ${e}`,category:`runAction`})}let m=p.length>0||a.length>0;return f.length===0?{block:e,redactedClasses:[],...m&&{degraded:!0}}:{block:{...e,outputs:s},redactedClasses:f.map(e=>({class:e.class,policyIds:e.deniedBy?.policyIds??[],...e.deniedBy?.level&&{level:e.deniedBy.level}})),...m&&{degraded:!0}}}catch(t){return n?.error({code:`PolicyRedactionFailed`,message:`PII redaction failed, response returned unredacted: ${t instanceof Error?t.message:String(t)}`,category:`runAction`}),{block:e,redactedClasses:[],...r&&{degraded:!0}}}},isEnabledTestAction=(e,n,r)=>(0,t.isMissing)(r)||e.isInline||r.has(n.id),runAction=async e=>{let{pathParams:n={},queryParams:r={},body:i={},headers:a={},decideInvokeToolFn:o=decideInvokeTool,decideReadFieldsFn:s=decideReadFields,parseConnector:l=parseYamlConnector,parseActionInputsFn:u=parseActionInputs,createBlockContextFn:d=createBlockContext,createBlockFn:f=createBlock,runStepActionFn:p=runStepAction,getActionFromUrlFn:m=getActionFromUrl,getActionForRefreshAuthenticationFn:h=getActionForRefreshAuthentication,getTestActionsFn:g=getTestActions,applyDefenderFn:_=applyDefender,applyRedactionFn:v=applyRedactionToBlock,mode:y,account:b,connector:x,getHttpClient:S,getOlapClient:C,settings:w,source:T,user:E,policy:D,logger:O,category:k,...A}=e,j=normalizeActingUser(E),M=withActingUser(D,j),N=b.authConfigKey,P=b.environment??`production`,F=b.secureId,ee=b.projectSecureId,I=b.organizationId,L=b.credentials,R=b.originOwnerId,z=b.originOwnerName,B=d({category:k??`action`,connectorKey:b.providerKey,connectorVersion:b.providerVersion,connectorOwner:b.connectorOwner,connectorProfileId:b.connectorProfileId,authConfigKey:N,environment:P,accountSecureId:F,projectSecureId:ee,organizationId:I,originOwnerId:R,originOwnerName:z,sourceType:T?.sourceType,authType:T?.authType,authId:T?.authId,sessionId:T?.sessionId,agentId:T?.agentId,userAgent:T?.userAgent,ipAddress:T?.ipAddress,transportType:T?.transportType,streamType:T?.streamType,flowType:Xe[y],sourceId:T?.sourceId,sourceValue:T?.sourceValue}),V=new Date,H;try{H=(0,t.isString)(x)?l(x):x}catch{throw new ConnectorParseError(B,`Error while parsing connector`)}let U={connector:H,context:B,user:j,credentials:L,settings:w,logger:O,getHttpClient:S,getOlapClient:C};if(y===`action_id`){let{actionId:c}=A,l=findActionByActionId(H,c);if((0,t.isMissing)(l))throw new MissingActionError(B,`No matching action found`);return validateAuthTypeCompatibility(l,N,B),await runAndRecord({action:l,execute:{action:l,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:n,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else if(y===`test_actions`){let{enabledActions:n}=A,r=g(H,N,P);if((0,t.isMissing)(r)||r.length===0)return await createSuccessBlock(f,U);B.actionType=`test`;let i=(0,t.notMissing)(n)&&!n.allEnabled?new Set(n.actionIds):void 0,a=0;for(let n of r){let{action:r}=n;if((0,t.isString)(r))throw new MissingActionError(B,`Test action "${r}" does not resolve to an action`);if(!isEnabledTestAction(n,r,i))continue;let o=new Date,s=await f({...U,inputs:void 0,action:r,nextCursor:void 0});if(!(!(0,t.notMissing)(n.condition)||(0,c.evaluate)(n.condition,s)))continue;validateActingUser(r,j,B),a++;let l=await p({block:s});if(l=await applyDefenderToBlock(l,_,w,O),(0,t.notMissing)(l?.response?.successful)&&l.response.successful){l.statistics={startTime:o,endTime:new Date},await recordActionResult({action:r,resultBlock:l,...recordingFieldsFromParams(e)});let t=await createSuccessBlock(f,U);return t.statistics={startTime:V,endTime:new Date},t}O?.error({code:`TestActionFailed`,message:`Test action "${r.id}" failed with error: ${l?.response?.message}`}),l.statistics={startTime:o,endTime:new Date},await recordActionResult({action:r,resultBlock:l,...recordingFieldsFromParams(e)})}if(a>0){let e=await createErrorBlock(f,U);return e.statistics={startTime:V,endTime:new Date},e}let o=await createSuccessBlock(f,U);return o.statistics={startTime:V,endTime:new Date},o}else if(y===`refresh_authentication`){let{redirectUri:n}=A;B.redirectUri=n;let c=h(H,N,P);if((0,t.isMissing)(c))throw new MissingActionError(B,`No matching action found`);return await runAndRecord({action:c.action,execute:{action:c.action,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:c.params,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else if(y===`path`){let{path:n,method:c}=A,l=m(H,n,c);if((0,t.isMissing)(l))throw new MissingActionError(B,`No matching action found`);return validateAuthTypeCompatibility(l.action,N,B),await runAndRecord({action:l.action,execute:{action:l.action,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:l.params,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else return await createErrorBlock(f,U)},refusalStatus=e=>isPolicyErrorType(e.errorType)?Q[e.errorType]:e instanceof ActingUserRequiredError?403:void 0,runAndRecord=async e=>{let t=await executeAction(e.execute);if(t.outcome===`refused`){let n=await createErrorBlock(e.execute.createBlockFn,e.execute.createBlockParams,refusalStatus(t.error));n.statistics={startTime:e.startTime,endTime:new Date};let r=describeRefusal(t.error);throw await recordActionResult({action:e.action,resultBlock:n,...t.policy&&{policyContext:t.policy},...r&&{refusal:r},...e.recording}),r?Object.assign(t.error,{refusal:r}):t.error}let{block:n,maskedFields:r,observedFields:i,degraded:a}=await applyPolicyMask(t,e.logger),o=await applyDefenderToBlock(n,e.applyDefenderFn,e.settings,e.logger),{block:s,redactedClasses:c,degraded:l=!1}=await e.applyRedactionFn(o,t.readFields,e.logger);s.statistics={startTime:e.startTime,endTime:new Date};let u=t.readFields&&(r.length>0||c.length>0||l||i.length>0)?toPolicyContext(t.readFields.decision,t.readFields.call,{maskedFields:r,degraded:a||l,redactedClasses:c,observedFields:i}):t.policy;return(u?.maskedFields?.length||c.length||l)&&(s.policyMetadata={result:u?.result===`error`?`error`:`partial`,maskedFields:(u?.maskedFields??[]).map(e=>({...e})),...c.length>0&&{redactedClasses:c.map(e=>({...e}))},policies:(u?.policies??[]).map(e=>({...e}))}),await recordActionResult({action:e.action,resultBlock:s,...u&&{policyContext:u},...e.recording}),s},observedFieldsOf=e=>e.filter(e=>e.decision!==`deny`).flatMap(e=>{let t=e.observed.filter(e=>e.decision===`deny`&&e.faulted!==!0),[n]=t;return n?[{path:e.path,policyIds:[...new Set(t.flatMap(e=>e.policyIds))],level:n.level}]:[]}),applyPolicyMask=async(e,t)=>{let n=e.readFields;if(!n)return{block:e.block,maskedFields:[],observedFields:[],degraded:!1};try{let{paths:r,truncated:i,valueTypes:a,neighbours:o,identifierPaths:s}=fieldPathsOf(e.block.outputs);if(r.length===0)return{block:e.block,maskedFields:[],observedFields:[],degraded:!1};let c=await(n.decideReadFieldsFn??decideReadFields)({policy:n.policy,account:n.account,action:n.action,paths:r,valueTypes:a,neighbours:o,identifierPaths:s,...n.authType&&{authType:n.authType},...n.sessionId&&{sessionId:n.sessionId},logger:t}),l=c.fields.filter(e=>e.decision===`deny`),u=observedFieldsOf(c.fields),d=i?new Set(c.fields.filter(e=>e.decision===`allow`&&!e.faulted).map(e=>e.path)):void 0;if(l.length===0&&!i)return{block:e.block,maskedFields:[],observedFields:u,degraded:!1};let{payload:f,masked:p}=maskFields(e.block.outputs,l.map(e=>e.path),d),m=new Map(l.map(e=>[e.path,e]));return{block:{...e.block,outputs:f},maskedFields:p.map(e=>({path:e,policyIds:m.get(e)?.deniedBy?.policyIds??[],...m.get(e)?.deniedBy?.level&&{level:m.get(e)?.deniedBy?.level}})),observedFields:u,degraded:i||l.some(e=>e.faulted)}}catch(n){t?.error({code:`PolicyMaskFailed`,message:`Field masking failed, response withheld: ${n instanceof Error?n.message:String(n)}`,category:`runAction`});let{payload:r,masked:i}=maskFields(e.block.outputs,[],new Set);return{block:{...e.block,outputs:r},maskedFields:i.map(e=>({path:e,policyIds:[]})),observedFields:[],degraded:!0}}},executeAction=async e=>{let{action:t,blockContext:n,account:r,policy:i,logger:a,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:c,pathParams:l,body:u,headers:d,parseActionInputsFn:f,createBlockFn:p,createBlockParams:m,runStepActionFn:h}=e;n.actionType=t.actionType,n.schema=t.schema?.key;let g=processCursor(c,n),_;try{_=f(t,{path:l,query:c,body:u,headers:d})}catch(e){throw typeof e==`object`&&e&&`issues`in e&&Array.isArray(e.issues)?new InvalidActionInputsError(n,`Invalid input values provided`,e.issues.map(e=>{let t=e.path.map(String),n=t[0]||`body`;return{field:t.slice(1).join(`.`)||t[0]||`unknown`,location:n,expected:`expected`in e?String(e.expected):e.code,received:`received`in e?String(e.received):`unknown`,message:e.message}})):new InvalidActionInputsError(n,`Error while parsing action inputs`)}let v=actingUserRefusal(t,m.user,n);if(v)return{outcome:`refused`,error:v};let y=await enforceInvokeTool({action:t,blockContext:n,account:r,policy:i,logger:a,decideInvokeToolFn:o});return y.permitted?{outcome:`ran`,block:await h({block:await p({...m,inputs:_,action:t,nextCursor:g})}),...y.policy&&{policy:y.policy},...y.readFields&&{readFields:{...y.readFields,decideReadFieldsFn:s}}}:{outcome:`refused`,policy:y.policy,error:y.error}},enforceInvokeTool=async e=>{let n=e.policy;if((0,t.isMissing)(n)||e.blockContext.flowType!==`action`)return{permitted:!0};let r={actionRunId:e.blockContext.actionRunId??`missing`,actionId:e.action.id,accountSecureId:e.account.secureId,...n.principal&&{principal:n.principal},levels:n.levels},i=await decideOrName(e,n);if(`preparse`in i)return{permitted:!1,policy:preparseFailureContext(r),error:i.preparse};let a=i.decision,o=toPolicyContext(a,r);if(a.decision===`allow`)return{permitted:!0,policy:o,readFields:{decision:a,call:r,policy:n,account:e.account,action:e.action,...e.blockContext.authType&&{authType:e.blockContext.authType},...e.blockContext.sessionId&&{sessionId:e.blockContext.sessionId}}};let s=n.toolName??e.action.id,c=a.deniedBy?.level??`org`;return{permitted:!1,policy:o,error:a.faulted?new PolicyEvaluationError(e.blockContext,{level:c},`Could not evaluate ${c} policy for action '${s}'`):new PolicyDeniedError(e.blockContext,{level:c,policyIds:a.deniedBy?.policyIds??[]},`Action '${s}' is not permitted by ${c} policy`)}},decideOrName=async(e,t)=>{try{return{decision:await e.decideInvokeToolFn({policy:t,account:e.account,action:e.action,authType:e.blockContext.authType,sessionId:e.blockContext.sessionId,logger:e.logger})}}catch(t){if(t instanceof l.PolicyPreparseError)return{preparse:new PolicyPreparseError(e.blockContext,t.message)};throw t}},createSuccessBlock=async(e,t)=>({...await e({...t,inputs:void 0,action:void 0,nextCursor:void 0}),response:{successful:!0,statusCode:200}}),createErrorBlock=async(e,t,n=500)=>({...await e({...t,inputs:void 0,action:void 0,nextCursor:void 0}),response:{successful:!1,statusCode:n}}),processCursor=(e,n)=>{let r=e?.next,i=(0,t.notMissing)(r)&&n.actionType===`list`?(0,s.expandCursor)(r):void 0;if(i===null)throw new InvalidCursorError(n,`Invalid cursor.`);return i},applyDefender=async({outputs:e,streamOutput:t,toolName:n,sourceType:r,settings:i,logger:a})=>{if(t)return{defenderMetadata:{applied:!1,skipped:{reason:`streaming`}}};let o=shouldSkipDefender(e,i?.defender);if(o.skip)return{defenderMetadata:{applied:!1,skipped:{reason:o.reason,estimatedSize:o.size?.bytes,threshold:i?.defender?.maxResponseSize}}};if(i?.defender?.largeResponseBehavior===`block`&&o.size&&(o.size.bytes>(i.defender.maxResponseSize??1048576)||o.size.words>(i.defender.maxResponseWords??1e4)))return{defenderMetadata:{applied:!1,skipped:{reason:`size_limit`,estimatedSize:o.size.bytes,threshold:i.defender.maxResponseSize}},response:{successful:!1,statusCode:413,message:`Response too large for security scanning`}};try{let t=await(0,u.createPromptDefense)({blockHighRisk:i?.defender?.blockHighRisk??!1,enableTier1:i?.defender?.useTier1Classification??!0,enableTier2:i?.defender?.useTier2Classification??!0,useSfe:i?.defender?.useSfe??!0,tier2Fields:i?.defender?.tier2Fields,annotateBoundary:i?.defender?.annotateBoundary??!1,sanitizeContent:i?.defender?.sanitizeContent??!0,enableTier3:i?.defender?.useTier3Classification??!1,defenderMode:i?.defender?.defenderMode??`cascade`,...buildTier2Config(i?.defender)}).defendToolResult(e,n),o=t.tier3,s=o===void 0?{}:o.decision===`block`||o.decision===`allow`?{tier3Decision:o.decision,tier3LatencyMs:o.latencyMs,...o.usage&&{tier3PromptTokens:o.usage.promptTokens,tier3CompletionTokens:o.usage.completionTokens}}:{tier3SkipReason:o.skipReason};return a?.info({message:`Defender applied`,context:{tool:n,sourceType:r,riskLevel:t.riskLevel,allowed:t.allowed,fieldsSanitized:t.fieldsSanitized.length,detectedFieldCount:t.detectedFieldCount,detections:t.detections,tier2Score:t.tier2Score,tier2SkipReason:t.tier2SkipReason,tier2Available:t.tier2Available,coverageDegraded:t.coverageDegraded,latencyMs:t.latencyMs,tier1Ms:t.tier1Ms,coldLoad:t.coldLoad,tier2Stats:t.tier2Stats,phaseTimings:t.phaseTimings,...s}}),{defenderMetadata:{applied:!0,result:{allowed:t.allowed,riskLevel:t.riskLevel,fieldsSanitized:t.fieldsSanitized,patternsByField:t.patternsByField,detections:t.detections,tier2Score:t.tier2Score,tier2RawScore:t.tier2RawScore,tier2AuxScore:t.tier2AuxScore,tier2MultiheadBlocked:t.tier2MultiheadBlocked,tier2SkipReason:t.tier2SkipReason,tier3:t.tier3,latencyMs:t.latencyMs,...s}},outputs:t.sanitized,...!t.allowed&&{response:{successful:!1,statusCode:403,message:`Tool result blocked by security policy`}}}}catch(e){return a?.error({code:`DefenderError`,message:`Defender failed: ${e.message}`,context:{tool:n}}),{defenderMetadata:{applied:!1,skipped:{reason:`error`,error:e.message}}}}},runConnectorActionById=async({actionId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},settings:s,source:c,logger:l,getHttpClient:u,getOlapClient:d,parseConnector:f=parseYamlConnector,parseActionInputsFn:p=parseActionInputs,createBlockContextFn:m=createBlockContext,createBlockFn:h=createBlock,runStepActionFn:g=runStepAction})=>runAction({mode:`action_id`,actionId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,settings:s,source:c,logger:l,getHttpClient:u,getOlapClient:d,parseConnector:f,parseActionInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepActionFn:g}),runConnectorActionByPath=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,settings:c,source:l,logger:u,getHttpClient:d,parseConnector:f=parseYamlConnector,getActionFromUrlFn:p=getActionFromUrl,getActionForRefreshAuthenticationFn:m=getActionForRefreshAuthentication,parseActionInputsFn:h=parseActionInputs,createBlockContextFn:g=createBlockContext,createBlockFn:_=createBlock,runStepActionFn:v=runStepAction})=>isRefreshTokenActionPath(r)?await runAction({mode:`refresh_authentication`,account:e,connector:t,settings:c,source:l,getActionForRefreshAuthenticationFn:m,parseConnector:f,logger:u,getHttpClient:d,parseActionInputsFn:h,createBlockContextFn:g,createBlockFn:_,runStepActionFn:v}):await runAction({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,settings:c,source:l,getActionFromUrlFn:p,parseConnector:f,logger:u,getHttpClient:d,parseActionInputsFn:h,createBlockContextFn:g,createBlockFn:_,runStepActionFn:v}),isRefreshTokenActionPath=e=>e===`stackone://internal//refresh_token`,runEventActionById=async({actionId:e,account:n,connector:r,body:i={},headers:a={},logger:o,getHttpClient:c,getOlapClient:l,emitEvent:u,getWebhookRemoteId:d,findActionFn:f=findEventActionByActionId,parseActionInputsFn:p=parseActionInputs,createBlockContextFn:m=createBlockContext,createBlockFn:h=createBlock,runStepActionFn:g=runStepAction})=>{let _=m({category:`action`,connectorKey:n.providerKey,connectorVersion:n.providerVersion,authConfigKey:n.authConfigKey,environment:n.environment??`production`,accountSecureId:n.secureId,projectSecureId:n.projectSecureId,organizationId:n.organizationId,originOwnerId:n.originOwnerId,originOwnerName:n.originOwnerName,connectorOwner:n.connectorOwner,flowType:`action`}),v=f(r,e);if((0,t.isMissing)(v))throw new MissingActionError(_,`No matching event action found`);_.actionType=`event`,_.schema=v.schema?.key,_.webhookRemoteId=await d?.();let y=p(v,{body:i,headers:a}),b=new Date,x=await h({connector:r,context:_,credentials:n.credentials,logger:o,getHttpClient:c,getOlapClient:l,emitEvent:u,inputs:y,action:v,nextCursor:void 0}),S={mode:`event`,organizationId:n.organizationId,body:i,headers:a,source:{sourceType:s.SourceType.Webhook},isBackground:!1,logger:o},C;try{C=await g({block:x})}catch(t){throw o?.error({code:`EventActionError`,message:`Event action "${e}" failed: ${t.message}`}),await recordActionResult({action:v,resultBlock:{...x,response:{successful:!1,statusCode:500,message:t.message},statistics:{startTime:b,endTime:new Date}},...S}),t}if(C.statistics={startTime:b,endTime:new Date},typeof C.outputs?.statusCode!=`number`)throw await recordActionResult({action:v,resultBlock:{...C,response:{successful:!1,statusCode:500,message:`Event action output must include a numeric statusCode`}},...S}),new InvalidEventOutputError(_,`Event action output must include a numeric statusCode`);return await recordActionResult({action:v,resultBlock:C,...S}),C},runTestActions=async({account:e,connector:t,settings:n,source:r,logger:i,getHttpClient:a,getOlapClient:o,enabledActions:s,parseConnector:c=parseYamlConnector,getTestActionsFn:l=getTestActions,createBlockContextFn:u=createBlockContext,createBlockFn:d=createBlock,runStepActionFn:f=runStepAction})=>(await runAction({mode:`test_actions`,account:e,connector:t,settings:n,source:r,logger:i,getHttpClient:a,getOlapClient:o,enabledActions:s,parseConnector:c,getTestActionsFn:l,createBlockContextFn:u,createBlockFn:d,runStepActionFn:f}))?.response?.successful??!1,phaseKindToActionType=e=>e===`deletion`?`delete`:`create`,phaseAsAction=(e,t)=>({id:`webhook-setup-${t}`,categories:[],label:`Webhook Setup ${t}`,description:`Webhook setup ${t} phase execution`,schemaType:`native`,actionType:phaseKindToActionType(t),steps:e.steps,result:e.result,responses:{success:{statusCode:200},errors:{}},cursor:{enabled:!1,pageSize:0},compositeIdentifiers:{enabled:!1}}),runWebhookSetupPhase=async({connector:e,phase:n,phaseKind:r,inputs:i,credentials:a,accountSecureId:o,projectSecureId:c,organizationId:l,originOwnerId:u,originOwnerName:d,connectorKey:f,connectorVersion:p,authConfigKey:m,environment:h,logger:g,getHttpClient:_,getOlapClient:v,createBlockFn:y=createBlock,createBlockContextFn:b=createBlockContext,runStepActionFn:x=runStepAction})=>{let S=e.categories?.[0];if((0,t.isMissing)(S))throw Error(`Connector category is required for webhook setup phase execution (connector '${f}')`);let C=phaseAsAction(n,r),w=b({category:S,connectorKey:f,connectorVersion:p,authConfigKey:m,environment:h,action:C,accountSecureId:o,projectSecureId:c,organizationId:l,originOwnerId:u,originOwnerName:d,flowType:`action`}),T=new Date,E=await y({connector:e,inputs:i,credentials:a,context:w,action:C,logger:g,getHttpClient:_,getOlapClient:v}),D={mode:`webhook_setup`,organizationId:l,body:i,source:{sourceType:s.SourceType.Internal},isBackground:!0,logger:g},O;try{O=await x({block:E})}catch(e){throw await recordActionResult({action:C,resultBlock:{...E,response:{successful:!1,statusCode:500,message:e.message},statistics:{startTime:T,endTime:new Date}},...D}),e}if(O.statistics={startTime:T,endTime:new Date},(0,t.isMissing)(O.response))throw await recordActionResult({action:C,resultBlock:{...O,response:{successful:!1,statusCode:500,message:`Webhook setup ${r} phase produced no response`}},...D}),Error(`Webhook setup ${r} phase produced no response (connector '${f}')`);return await recordActionResult({action:C,resultBlock:O,...D}),{successful:O.response.successful,statusCode:O.response.statusCode,outputs:O.outputs}};exports.ACTION_SCHEMA=W,exports.ActingUserRequiredError=ActingUserRequiredError,exports.CATEGORY_ACRONYMS=p,exports.CONNECTOR_YAML_SCHEMA=xe,exports.ConnectSDKError=Z,exports.DEFAULT_TIME_FILTER_SAFETY_BUFFER_SECONDS=60,exports.DELTA_TOKEN_INCREMENTAL_SCHEMA=b,exports.INCREMENTAL_SCHEMA=S,exports.IncompatibleAuthTypeError=IncompatibleAuthTypeError,exports.InvalidActionInputsError=InvalidActionInputsError,exports.InvalidEventOutputError=InvalidEventOutputError,exports.MAX_FIELD_PATHS=250,exports.POLICY_ERROR_STATUS=Q,exports.PolicyDeniedError=PolicyDeniedError,exports.PolicyEvaluationError=PolicyEvaluationError,exports.PolicyPreparseError=PolicyPreparseError,exports.TIME_FILTER_INCREMENTAL_SCHEMA=x,exports.addMcpToolActions=addMcpToolActions,exports.applyDefender=applyDefender,exports.applyReleaseStageResolutionToMeta=applyReleaseStageResolutionToMeta,exports.applyReleaseStageToConnector=applyReleaseStageToConnector,exports.buildReleaseStageProfile=buildReleaseStageProfile,exports.completeMcpConnector=completeMcpConnector,exports.computeCredentialsVerifiedByAuth=computeCredentialsVerifiedByAuth,exports.countReleaseStageProfile=countReleaseStageProfile,exports.createBlock=createBlock,exports.createCursorPaginator=createCursorPaginator,exports.createDeltaTokenStrategy=createDeltaTokenStrategy,exports.createIncrementalStrategy=createIncrementalStrategy,exports.createLabellingDecideReadFields=createLabellingDecideReadFields,exports.createOffsetPaginator=createOffsetPaginator,exports.createPagePaginator=createPagePaginator,exports.createPaginator=createPaginator,exports.createTimeFilterStrategy=createTimeFilterStrategy,exports.decideInvokeTool=decideInvokeTool,exports.decideReadFields=decideReadFields,exports.definitionVersionOf=definitionVersionOf,exports.evaluateExternalAccountIdExtractorByConnector=evaluateExternalAccountIdExtractorByConnector,exports.executeStepFunction=executeStepFunction,exports.extractItems=extractItems,exports.fieldPathsOf=fieldPathsOf,exports.filterActionsByAuthType=filterActionsByAuthType,exports.formatValidationErrorResponse=formatValidationErrorResponse,exports.generateMcpConnector=generateMcpConnector,exports.getActionAuthenticationMethods=getActionAuthenticationMethods,exports.getActionFromUrl=getActionFromUrl,exports.getActionMeta=getActionMeta,exports.getActionsMeta=getActionsMeta,exports.getActionsMetaFromConnectors=getActionsMetaFromConnectors,exports.getActionsMetaSummary=getActionsMetaSummary,exports.getActionsMetaSummaryFromConnectors=getActionsMetaSummaryFromConnectors,exports.getRefreshTokenExpiresIn=getRefreshTokenExpiresIn,exports.getTokenExpiresIn=getTokenExpiresIn,exports.hasCatastrophicBacktrackingRisk=hasCatastrophicBacktrackingRisk,exports.isConnectorReleased=isConnectorReleased,exports.isMcpConnector=isMcpConnector,exports.isPolicyErrorType=isPolicyErrorType,exports.labelKeyOf=labelKeyOf,exports.labelsReferencedBy=labelsReferencedBy,exports.loadConnector=loadConnector,exports.maskFields=maskFields,exports.paginate=paginate,exports.parseActionInputs=parseActionInputs,exports.parseYamlConnector=parseYamlConnector,exports.providerRequestsOf=providerRequestsOf,exports.refusalOf=refusalOf,exports.resolveReleaseStageCounts=resolveReleaseStageCounts,exports.resolveReleaseStageProfile=resolveReleaseStageProfile,exports.runAction=runAction,exports.runConnectorActionById=runConnectorActionById,exports.runConnectorActionByPath=runConnectorActionByPath,exports.runEventActionById=runEventActionById,exports.runStepAction=runStepAction,exports.runTestActions=runTestActions,exports.runWebhookSetupPhase=runWebhookSetupPhase,exports.supportsRefreshAuthentication=supportsRefreshAuthentication,exports.unlabelledAllowPolicyIdsOf=unlabelledAllowPolicyIdsOf,exports.validateYamlConnector=validateYamlConnector;
|
|
6
|
+
`),o=ownerMarkersFor(e),s=0,c=!1,l=1;for(let e=0;e<a.length;e++){let i=a[e].trim();if(s<o.length){i===o[s]&&(s++,l=e+1);continue}if(!c){i===`- stepId: ${t}`&&(c=!0,l=e+1);continue}if(!r&&i.includes(`functionName: ${n}`)||r&&i===`parameters:`)return e+1}return l},X=[{key:`production`,name:`Production`}],finishDescription=e=>{let t=e.length>200?e.slice(0,199).trimEnd():e;return t.endsWith(`.`)?t:`${t}.`},buildDescription=(e,t)=>{let n=t.server?.description?.replace(/\s+/g,` `).trim();if(n)return finishDescription(n.toLowerCase().startsWith(e.toLowerCase())?n:`${e} is ${n.charAt(0).toLowerCase()}${n.slice(1)}`);let r=t.resource?.name??t.server?.title??t.server?.name;return r&&r!==e?`${e} is a remote MCP server integration exposing the tools of ${r} through the Model Context Protocol.`:`${e} is a remote MCP server integration exposing its tools through the Model Context Protocol.`},deriveConnectorKey=e=>{let t=e.toLowerCase().replace(/[^a-z0-9]/g,``);return t===``?void 0:`mcp_${t}`},buildAuthenticationEntry=(e,t,n)=>{if(!n.requiresAuthorization)return{mcp:{type:`mcp`,label:`MCP Server`,support:{description:`Open MCP server. No credentials required to connect.`},authorization:{type:`none`},environments:X}};if(n.oauth){let r=n.oauth.dynamicRegistration===!0?{}:{setupFields:[{key:`clientId`,label:`Client ID`,type:`text`,required:!0,secret:!1,description:`OAuth client ID of the app registered with the ${e} MCP server`},{key:`clientSecret`,label:`Client Secret`,type:`password`,required:!1,secret:!0,description:`OAuth client secret of the app registered with the ${e} MCP server. Leave empty for public clients (PKCE-only)`}]};return{mcp_oauth:{type:`mcp`,label:`OAuth`,support:{description:`Authorize through the MCP server. Endpoints and client registration are discovered at connect time.`},authorizationFlow:{serverUrl:t,...n.oauth.scopes?.length?{scopes:n.oauth.scopes}:{}},authorization:{type:`bearer`,token:`$.credentials.accessToken`},...r,environments:X}}}return{mcp:{type:`mcp`,label:`Access Token`,support:{description:`Uses a static access token issued by the MCP server.`},authorization:{type:`bearer`,token:`$.credentials.accessToken`},configFields:[{key:`accessToken`,label:`Access Token`,type:`password`,required:!0,secret:!0,description:`Access token for the ${e} MCP server`}],environments:X}}},generateMcpConnector=async({serverUrl:e,title:n},r=a.probeMcpServer)=>{let i=deriveConnectorKey(n);if((0,t.isMissing)(i))throw Error(`The connector title must contain at least one alphanumeric character`);let s=await r(e),c=s.server?.instructions,l=s.server?.iconUrl??`https://stackone-logos.com/api/stackone/filled/png`,u=s.resource?.documentationUrl,d=buildDescription(n,s),f=(0,o.stringify)({StackOne:`1.0.0`,info:{title:n,key:i,version:`1.0.0`,assets:{icon:l},description:d},baseUrl:e,releaseStage:`ga`,...u?{resources:u}:{},...c?{mcp:{instructions:c.slice(0,J)}}:{},authentication:[buildAuthenticationEntry(n,e,s)]}),p=validateYamlConnector(f);if(!p.success||(0,t.isMissing)(p.connector)){let e=p.errors?.map(e=>`${e.field??`unknown`}: ${e.message}`).join(`; `);throw Error(`The generated MCP connector failed validation: ${e}`)}return{yaml:f,connector:p.connector}},isMcpConnector=e=>{let t=Object.values(e.authentication??{}).flatMap(e=>Object.values(e??{}));return t.length>0&&t.every(e=>e?.type===`mcp`)},Te=[`title`,`readOnlyHint`,`destructiveHint`,`idempotentHint`,`openWorldHint`],deriveActionId=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``),humanizeToolName=e=>{let t=e.replace(/[_-]+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)},mapScalarType=e=>e===`number`||e===`integer`?`number`:e===`boolean`?`boolean`:`string`,mapInputType=e=>{if(e.enum?.length)return{type:`enum`,oneOf:{values:e.enum.map(String)}};let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`array`?{array:!0,...mapInputType(e.items??{})}:t===`object`?{type:`object`,...e.properties?{properties:buildInputFields(e,{nested:!0})}:{}}:{type:mapScalarType(t)}},buildInputFields=(e,{nested:n})=>{let r=e.properties;if((0,t.isMissing)(r))return;let i=new Set(e.required??[]);return Object.entries(r).map(([e,t])=>({name:e,description:t.description??`The ${e} argument of the tool`,required:i.has(e),...n?{}:{in:`body`},...mapInputType(t)}))},buildToolAnnotations=e=>{let n=e.annotations;if((0,t.isMissing)(n))return{};let r=Te.reduce((e,t)=>(n[t]!==void 0&&(e[t]=n[t]),e),{});return{effects:n.readOnlyHint===!0?[`read`]:n.destructiveHint===!0?[`delete`]:[`execute`],...Object.keys(r).length?{annotations:r}:{}}},buildToolAction=e=>{let t=deriveActionId(e.name);if(t===``)throw Error(`Cannot derive an action id from the MCP tool name '${e.name}': it has no alphanumeric characters`);let n=buildInputFields(e.inputSchema??{},{nested:!1}),r=n?.map(e=>({name:e.name,value:`$.inputs.${e.name}`,...e.required?{}:{condition:`{{present(inputs.${e.name})}}`}}));return{actionId:t,categories:[`MCP`],actionType:`custom`,label:e.title??e.annotations?.title??humanizeToolName(e.name),description:e.description??`Call the ${e.name} tool on the MCP server.`,...buildToolAnnotations(e),...n?{inputs:n}:{},steps:[{stepId:`call_tool`,description:`Call the ${e.name} tool on the MCP server`,stepFunction:{functionName:`mcp_request`,parameters:{toolName:e.name,...r?.length?{args:r}:{}}}}],result:{data:`$.steps.call_tool.output.data`}}},addMcpToolActions=(e,n)=>{let r=(0,o.parse)(e);if((0,t.isMissing)(r)||typeof r!=`object`)throw Error(`The provided yaml is not a connector document`);let i=Array.isArray(r.actions)?r.actions:[],a=n.map(buildToolAction),s=[...i.map(e=>a.find(t=>t.actionId===e.actionId)??e),...a.filter(e=>!i.some(t=>t.actionId===e.actionId))],c=(0,o.stringify)({...r,actions:s}),l=validateYamlConnector(c);if(!l.success||(0,t.isMissing)(l.connector)){let e=l.errors?.map(e=>`${e.field??`unknown`}: ${e.message}`).join(`; `);throw Error(`The completed MCP connector failed validation: ${e}`)}return{yaml:c,connector:l.connector}},listAllTools=async(e,t)=>{let n=await e.listTools(t?{cursor:t}:void 0);return n.nextCursor?[...n.tools,...await listAllTools(e,n.nextCursor)]:n.tools},buildMcpClient=e=>new a.McpClient(e),extractHostname=e=>{try{return new URL(String(e)).hostname}catch{return}},applyServerInfo=(e,n)=>{let r=(0,o.parse)(e);if((0,t.isMissing)(n)||(0,t.isMissing)(r)||typeof r!=`object`)return e;let i=r.info??{},a=typeof i.title==`string`?i.title:void 0,s=n.title??n.name,c=extractHostname(r.baseUrl),l=!!(s&&a&&c&&a.toLowerCase()===c),u=l?s:a,d=(n.description||l)&&u?{description:buildDescription(u,{server:n})}:{},f=n.iconUrl&&i.assets?.icon===`https://stackone-logos.com/api/stackone/filled/png`?{assets:{...i.assets,icon:n.iconUrl}}:{},p=n.instructions?{mcp:{...r.mcp??{},instructions:n.instructions.slice(0,J)}}:{};return(0,o.stringify)({...r,info:{...i,...l?{title:u}:{},...d,...f},...p})},completeMcpConnector=async(e,{headers:t,timeout:n}={},r=buildMcpClient)=>{let i=(0,o.parse)(e)?.baseUrl;if(typeof i!=`string`||i===``)throw Error(`The connector yaml has no baseUrl pointing at the MCP server`);let a=r({serverUrl:i,headers:t,timeout:n});try{let t=await listAllTools(a);return addMcpToolActions(applyServerInfo(e,await a.getServerInfo().catch(()=>void 0)),t)}finally{await a.close().catch(()=>void 0)}},getActionForRefreshAuthentication=(e,n,r)=>{let i=e.authentication?.[n]?.[r]?.refreshAuthentication?.action;return(0,t.notMissing)(i)?{action:i,params:{}}:void 0},supportsRefreshAuthentication=(e,n,r)=>(0,t.notMissing)(getActionForRefreshAuthentication(e,n,r)),Ee=[`oauth2`,`mcp`],getTokenExpiresIn=(e,t,n)=>{let r=e.authentication?.[t]?.[n],i=r?.authorization,a=r?.type;if(!(!a||!Ee.includes(a)))return i?.tokenExpiresIn},getRefreshTokenExpiresIn=(e,t,n)=>{let r=e.authentication?.[t]?.[n],i=r?.authorization,a=r?.type;if(!(!a||!Ee.includes(a)))return i?.tokenRefreshExpiresIn};var Z=class ConnectSDKError extends Error{constructor(e,t,n){super(n),this.name=`ConnectSDKError`,this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,ConnectSDKError)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},ConnectorParseError=class extends Z{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},MissingActionError=class extends Z{constructor(e,t){super(`MISSING_ACTION_ERROR`,e,t),this.name=`MissingActionError`}},InvalidActionInputsError=class extends Z{constructor(e,t,n){super(`INVALID_ACTION_INPUTS_ERROR`,e,t),this.name=`InvalidActionInputsError`,this.validationErrors=n}},InvalidCursorError=class extends Z{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}},IncompatibleAuthTypeError=class extends Z{constructor(e,t){super(`INCOMPATIBLE_AUTH_TYPE_ERROR`,e,t),this.name=`IncompatibleAuthTypeError`}},ActingUserRequiredError=class extends Z{constructor(e,t){super(`ACTING_USER_REQUIRED_ERROR`,e,t),this.name=`ActingUserRequiredError`}},UserScopeViolationError=class extends Z{constructor(e,t){super(`USER_SCOPE_VIOLATION_ERROR`,e,t),this.name=`UserScopeViolationError`}},InvalidEventOutputError=class extends Z{constructor(e,t){super(`INVALID_EVENT_OUTPUT_ERROR`,e,t),this.name=`InvalidEventOutputError`}},PolicyDeniedError=class extends Z{constructor(e,t,n){super(`POLICY_DENIED_ERROR`,e,n),this.name=`PolicyDeniedError`,this.level=t.level,this.policyIds=t.policyIds}},PolicyEvaluationError=class extends Z{constructor(e,t,n){super(`POLICY_EVALUATION_ERROR`,e,n),this.name=`PolicyEvaluationError`,this.level=t.level}},PolicyPreparseError=class extends Z{constructor(e,t){super(`POLICY_PREPARSE_ERROR`,e,t),this.name=`PolicyPreparseError`}};const Q={POLICY_DENIED_ERROR:403,POLICY_EVALUATION_ERROR:503,POLICY_PREPARSE_ERROR:500},isPolicyErrorType=e=>e in Q,isRefusalType=e=>isPolicyErrorType(e)||e===`ACTING_USER_REQUIRED_ERROR`||e===`USER_SCOPE_VIOLATION_ERROR`,De={org:`an organization administrator`,project:`a project administrator`},quoting=e=>e?`, quoting reference ${e}`:``,Oe={POLICY_DENIED_ERROR:({message:e,level:t,reference:n})=>`${e}. Ask ${De[t??``]??`an administrator`} for access${quoting(n)}.`,POLICY_EVALUATION_ERROR:({message:e,reference:t})=>`${e}. This is usually temporary, so retry the call${t?`, and quote reference ${t} if it keeps failing`:``}.`,POLICY_PREPARSE_ERROR:({reference:e})=>`The policies governing this call could not be read. Ask an administrator to check them${quoting(e)}.`,ACTING_USER_REQUIRED_ERROR:({message:e,reference:t})=>`${e}. Call it as a signed-in user, or ask an administrator for help${quoting(t)}.`,USER_SCOPE_VIOLATION_ERROR:({message:e,reference:t})=>`${e}. Ask an administrator to check how this action is scoped to you${quoting(t)}.`},describeRefusal=e=>{if(!isRefusalType(e.errorType))return;let{level:n}=e,r=(0,t.isString)(n)?n:void 0;return{errorType:e.errorType,message:Oe[e.errorType]({message:e.message,level:r,reference:e.context?.actionRunId}),...r&&{level:r}}},refusalOf=e=>{let n=(0,t.isObject)(e)?e.refusal:void 0;if(!(!(0,t.isObject)(n)||!(0,t.isString)(n.errorType)||!(0,t.isString)(n.message)))return n};function buildInputs(e,t,n){let r=e[t],i=r&&typeof r==`object`&&!Array.isArray(r)?{...r,...n}:n;return{...e,[t]:i}}function extractData(e,n){let r=(0,t.getByDotPath)(n.outputs,e.response.dataKey);return Array.isArray(r)?r:r==null?[]:[r]}const buildResponseScope=e=>({...(0,t.isObject)(e.outputs)?e.outputs:{},headers:e.responseHeaders}),assertResponseHeadersAvailable=(e,n)=>{if(n.includes(`$.headers`)){if(e.responseHeaders===void 0)throw Error(`DataSync key reads $.headers but the response carried no responseHeaders: ${n}. Check that connect-handler forwards responseHeaders and that the action makes a request.`);if((0,t.isObject)(e.outputs)&&Object.prototype.hasOwnProperty.call(e.outputs,`headers`))throw Error(`DataSync key reads $.headers, which is ambiguous because the action result also has a headers field: ${n}. Rename the result field; \$.headers is reserved for response headers.`)}},resolveResponseKey=(e,n)=>{if(!(0,c.isExpression)(n))return(0,t.getByDotPath)(e.outputs,n);assertResponseHeadersAvailable(e,n);try{return(0,c.evaluate)(n,buildResponseScope(e),{throwOnEvalError:!0})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to evaluate DataSync response key ${n}. ${t}`)}};function isExhausted(e,t,n,r){if(e.stopCondition===void 0&&typeof n==`function`)return n(t);let i=e.stopCondition??n;assertResponseHeadersAvailable(t,i);try{return!!(0,c.evaluate)(`{{ ${i} }}`,buildResponseScope(t))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to evaluate pagination stop condition on page ${r}: ${i}. ${t}`)}}function createCursorPaginator(e,{baseInputs:n={}}={}){let resolveCursor=t=>resolveResponseKey(t,e.response.nextKey),defaultStop=e=>(0,t.isMissing)(resolveCursor(e));return{config:e,computeNextInputs({previousResponse:t}){return t?buildInputs(n,e.iterator.in,{[e.iterator.key]:resolveCursor(t)}):{...n}},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,defaultStop,n)}}function createOffsetPaginator(e,{baseInputs:t={}}={}){let n=e.iterator.defaultLimit??100,r=e.iterator.startOffset??0,{in:i,offsetKey:a,limitKey:o}=e.iterator,s=`${e.response.dataKey}[0] == null`;return{config:e,computeNextInputs({currentIteration:e,recordsRetrieved:s}){let c=s??e*n;return buildInputs(t,i,{[a]:r+c,[o]:n})},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,s,n)}}function createPagePaginator(e,{baseInputs:t={}}={}){let n=e.iterator.startPage??1,r=e.iterator.defaultPageSize??100,{in:i,pageKey:a,pageSizeKey:o}=e.iterator,s=`${e.response.dataKey}[0] == null`;return{config:e,computeNextInputs({currentIteration:e}){let s={[a]:n+e};return o&&(s[o]=r),buildInputs(t,i,s)},extractData:t=>extractData(e,t),isExhausted:(t,n)=>isExhausted(e,t,s,n)}}const ke={cursor:createCursorPaginator,offset:createOffsetPaginator,page:createPagePaginator};function createPaginator(e,t={}){let n=ke[e.type];return n(e,t)}function extractItems(e,n){let r=n.pagination?.response.dataKey??n.dataKey??`data`,i=(0,t.getByDotPath)(e.outputs,r);return Array.isArray(i)?i:i==null?[]:[i]}function assertSuccessful(e,t){if(e.response?.successful===!1)throw Error(`Action call failed on page ${t}: ${e.response.statusCode} ${e.response.message??``}`.trim())}function hasExceededMaxIterations(e,t=1e4){return e>=t}function hasExceededTimeout(e,t,n=3e5){return t-e>=n}function isDuplicatePage(e,t){return t===null?!1:e===t}async function paginate(e,n,r={}){let i=r.maxIterations??1e4,a=r.timeoutMs??3e5,o=r.onPageComplete,s=r.now??Date.now,c=s(),l=[],u=0,d=null,f;for(;;){if(hasExceededMaxIterations(u,i))return{data:l,pagesRetrieved:u,stoppedBy:`maxIterations`};if(hasExceededTimeout(c,s(),a))return{data:l,pagesRetrieved:u,stoppedBy:`timeout`};let r=await n(e.computeNextInputs({previousResponse:f,currentIteration:u,recordsRetrieved:l.length}));u++,assertSuccessful(r,u);let p=e.extractData(r),m=(0,t.getContentHash)(p);if(isDuplicatePage(m,d))return{data:l,pagesRetrieved:u,stoppedBy:`duplicatePage`};if(l.push(...p),d=m,f=r,o?.({pagesRetrieved:u,totalRecords:l.length}),e.isExhausted(r,u))return{data:l,pagesRetrieved:u,stoppedBy:`exhausted`}}}function createDeltaTokenStrategy(e){return{config:e,applyToInputs({baseInputs:t,checkpoint:n}){return n?.kind===`cursor`?buildInputs(t,e.iterator.in,{[e.iterator.key]:n.value}):t},extractFromPage({block:t,isFinalPage:n}){if(e.response.onlyOnFinalPage&&!n)return null;let r=resolveResponseKey(t,e.response.path);if(r==null)return null;let i=String(r);return i===``?null:{kind:`cursor`,value:i}},finalizeCheckpoint({extractedCheckpoints:e}){return e[e.length-1]??null}}}function formatIncrementalWatermark(e,n){switch(n){case`iso8601`:return e.toISOString();case`unix_seconds`:return String((0,t.dateToEpoch)(e,`seconds`));case`unix_millis`:return String((0,t.dateToEpoch)(e,`ms`))}}function createTimeFilterStrategy(e){let laterOf=(t,n)=>{if(e.format!==`iso8601`)return Number(t)>Number(n)?t:n;let r=Date.parse(t),i=Date.parse(n),a=!Number.isNaN(r),o=!Number.isNaN(i);return a&&o?r>i?t:n:a===o?t>n?t:n:a?t:n};return{config:e,applyToInputs({baseInputs:t,checkpoint:n}){return n?.kind===`timestamp`?buildInputs(t,e.iterator.in,{[e.iterator.key]:n.value}):t},extractFromPage({items:n}){let r=e.response?.updatedAtPath;if(!r)return null;let i=null;for(let e of n){let n=(0,t.getByDotPath)(e,r);if(n==null)continue;let a=String(n);a!==``&&(i=i===null?a:laterOf(i,a))}return i===null?null:{kind:`timestamp`,value:i}},finalizeCheckpoint({runStartTime:t,extractedCheckpoints:n}){let r=null;for(let e of n)e.kind===`timestamp`&&(r=r===null?e.value:laterOf(r,e.value));if(r!==null)return{kind:`timestamp`,value:r};let i=e.safetyBufferSeconds??60,a=t.getTime()-i*1e3;return{kind:`timestamp`,value:formatIncrementalWatermark(new Date(a),e.format)}}}}const Ae={time_filter:createTimeFilterStrategy,delta_token:createDeltaTokenStrategy};function createIncrementalStrategy(e){let t=Ae[e.type];return t(e)}const getConnectorAuthenticationMethods=(e,t)=>{let n=t?.includes(`authentication_guides`);return Object.keys(e.authentication??{}).map(t=>{let r=e.authentication?.[t]?.production,i={type:r?.type??`custom`,label:r?.label||`Custom`,key:t,required_scopes:r?.requiredScopes,...r?.support?.description?{description:r.support.description}:{}};return n&&(i.support=r?.support,i.configFields=r?.configFields,i.configNotices=r?.configNotices,i.setupFields=r?.setupFields,i.setupNotices=r?.setupNotices),i})},getActionAuthenticationMethods=e=>Object.keys(e.authentication??{}).map(t=>{let n=e.authentication?.[t]?.production;return{type:n?.type??`custom`,label:n?.label||`Custom`,key:t,required_scopes:n?.requiredScopes,...n?.support?.description?{description:n.support.description}:{}}}),buildActionAuthentication=(e,n)=>{if((0,t.isMissing)(e.authRequirements))return n;let r=e.authRequirements;return n.filter(e=>e.key in r).map(e=>({...e,required_scopes:r[e.key]}))},buildActionMeta=(e,n,r)=>{let i=buildActionAuthentication(e,n);return{id:e.id,description:e.description,label:e.label.replace(/(^|\s)\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,authentication:i,...e.tags?{tags:e.tags}:{},...(0,t.notMissing)(e.requiredScopes)&&(0,t.isMissing)(e.authRequirements)?{required_scopes:e.requiredScopes}:{},...e.releaseStage?{release_stage:e.releaseStage}:{},...e.effects?.length?{effects:e.effects}:{},...e.annotations&&Object.keys(e.annotations).length?{annotations:e.annotations}:{},...e.userScoped?{user_scoped:!0}:{},...r?.includes(`action_details`)?{action_details:e}:{}}},getScopeDefinitions=e=>Object.values(e.scopeDefinitions??{}),getActionsCount=e=>Object.keys(e.actions??{}).length,getEventActionsMeta=(e,t)=>Object.values(e.events?.actions??{}).map(e=>({id:e.id,label:e.label,description:e.description,tags:e.tags,release_stage:e.releaseStage,...e.requiresManualSetup?{requires_manual_setup:!0}:{},authentication:t})),getEventGuidesMeta=(e,t)=>{if(!t?.includes(`event_guides`))return;let n=e.events?.guides;if(n?.setup)return{setup:n.setup}},getActionsMeta=(e,t)=>{let n=getConnectorAuthenticationMethods(e,t),r=getActionAuthenticationMethods(e),i=Object.values(e.actions??{}).map(e=>buildActionMeta(e,r,t)),a=getScopeDefinitions(e),o=getEventActionsMeta(e,r),s=getEventGuidesMeta(e,t);return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,categories:e.categories,authentication:n,scope_definitions:a.length>0?a:void 0,release_stage:e.releaseStage,owner:e.owner,actions_count:i.length,actions:i,event_actions:o.length>0?o:void 0,documentation:e.documentation,event_guides:s}},getActionsMetaFromConnectors=(e,t)=>e.map(e=>getActionsMeta(e,t)),getActionMeta=(e,t,n)=>{let r=e.actions?.[t];if(r)return buildActionMeta(r,getActionAuthenticationMethods(e),n)},getActionsMetaSummary=(e,t)=>{let n=getConnectorAuthenticationMethods(e,t),r=getActionAuthenticationMethods(e),i=getScopeDefinitions(e),a=getEventActionsMeta(e,r),o=getEventGuidesMeta(e,t);return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,categories:e.categories,authentication:n,scope_definitions:i.length>0?i:void 0,release_stage:e.releaseStage,owner:e.owner,actions_count:getActionsCount(e),event_actions:a.length>0?a:void 0,event_guides:o}},getActionsMetaSummaryFromConnectors=(e,t)=>e.map(e=>getActionsMetaSummary(e,t)),applyReleaseStageResolutionToMeta=(e,n)=>{if((0,t.isMissing)(n))return;let keepReleasedAuthentication=e=>e.filter(e=>n.authenticationKeys.has(e.key)),r=e.actions.filter(e=>n.actionIds.has(e.id)).map(e=>({...e,authentication:keepReleasedAuthentication(e.authentication)})),i=(e.event_actions??[]).filter(e=>n.eventActionIds.has(e.id)).map(e=>(0,t.isMissing)(e.authentication)?e:{...e,authentication:keepReleasedAuthentication(e.authentication)});return{...e,authentication:keepReleasedAuthentication(e.authentication),actions_count:r.length,actions:r,event_actions:i.length>0?i:void 0}},hasOwnKey=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),je=__name(e=>typeof e==`object`&&!!e&&!Array.isArray(e),`isPlainObject`),Me=__name((e,t)=>/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?e?`${e}.${t}`:t:`${e}["${t.replace(/"/g,`\\"`)}"]`,`joinKey`),valueTypeOf=e=>e==null?`null`:typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`mixed`,combineValueTypes=(e,t)=>e===t||t===`null`?e:e===`null`?t:`mixed`,isRecordIdKey=e=>/^\d{4,}$/.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^[0-9a-f]{24,}$/i.test(e),Ne=t.z.uuid(),Pe=t.z.ulid(),isIdentifierValue=e=>typeof e==`string`&&(Ne.safeParse(e).success||Pe.safeParse(e).success&&/[a-z]/i.test(e)),Fe=new Set([`id`,`_id`]),Ie=/(?:^|_)(?:id|uuid|guid)s?$|(?:Id|ID|Uuid|UUID|Guid|GUID)s?$/,fieldPathsOf=(e,t={})=>{let n=t.maxPaths??250,r=new Set,i=new Map,a=new Map,o=new Map,s=new Set,c=new Set,l=!1,recordNeighbours=(e,t,n,r)=>{let i=a.get(e)??{parent:t,siblings:new Set,siblingCount:0};for(let e of n)i.siblings.size<12&&i.siblings.add(e);i.siblingCount=Math.max(i.siblingCount,r),a.set(e,i)},walk=(e,t,a,u)=>{if(r.size>=n){l=!0;return}if(a>12){l=!0;return}if(Array.isArray(e)){for(let n of e)walk(n,`${t}[]`,a+1,u);return}if(je(e)){let n=Object.keys(e).filter(e=>!isRecordIdKey(e)),r=n.slice(0,13),i=isRecordIdKey(u.key)?`*`:u.key;for(let[o,s]of Object.entries(e))walk(s,Me(t,o),a+1,{key:o,parent:i,siblings:r.filter(e=>e!==o).slice(0,12),siblingCount:n.length-+!isRecordIdKey(o)});return}if(t!==``){r.add(t);let n=i.get(t),a=valueTypeOf(e);if(i.set(t,n===void 0?a:combineValueTypes(n,a)),recordNeighbours(t,u.parent,u.siblings,u.siblingCount),Fe.has(u.key.toLowerCase())&&s.add(t),Ie.test(u.key)&&c.add(t),e!=null){let n=o.get(t)??{allIds:!0,seenValue:!1};o.set(t,{allIds:n.allIds&&isIdentifierValue(e),seenValue:!0})}}};return walk(e,``,0,{key:``,parent:``,siblings:[],siblingCount:0}),{paths:[...r],truncated:l,valueTypes:Object.fromEntries(i),neighbours:Object.fromEntries([...a].map(([e,{parent:t,siblings:n,siblingCount:r}])=>[e,{parent:t,siblings:[...n],siblingCount:r}])),identifierPaths:[...r].filter(e=>{if(s.has(e))return!0;let t=o.get(e);return!l&&c.has(e)&&t?.seenValue===!0&&t.allIds})}},Le=/\["((?:[^"\\]|\\.)*)"\]|\[\]|\.?([^.[\]]+)/g,labelKeyOf=e=>[...e.matchAll(Le)].map(([e,t,n])=>e===`[]`?`[]`:isRecordIdKey(t===void 0?n:t.replace(/\\"/g,`"`))?`.*`:t===void 0?`.${n}`:e).join(``).replace(/^\./,``),withActingUser=(e,t)=>!e?.principal||!t?.email||e.principal.userId!==t.id?e:{...e,principal:{...e.principal,email:t.email}},credentialOf=e=>e??`unknown`,identity=e=>({actionRunId:e.actionRunId,actionId:e.actionId,accountSecureId:e.accountSecureId,...e.principal&&{principal:{userId:e.principal.userId,groups:[...e.principal.groups]}},decidedAt:new Date().toISOString()}),policyResultOf=(e,t)=>{let{changed:n,degraded:r,watched:i}=t;return e.evaluated?e.decision===`deny`?e.faulted?`error`:`denied`:r?`error`:n?`partial`:i||e.observed.some(e=>e.decision===`deny`&&e.faulted!==!0)?`monitored`:`allowed`:`skipped`},effectOf=(e,t,n)=>{let{maskedFields:r,redactedClasses:i,observedFields:a}=n;return(t.deniedBy?.policyIds??[]).includes(e)?`refused`:r.some(t=>t.policyIds.includes(e))?`masked`:i.some(t=>t.policyIds.includes(e))?`redacted`:t.observed.some(t=>t.decision===`deny`&&t.faulted!==!0&&t.policyIds.includes(e))?`would-have-refused`:a.some(t=>t.policyIds.includes(e))?`would-have-masked`:t.resolved.some(t=>t.determining.includes(e))?`permitted`:void 0},isAuthored=e=>!(0,l.isBasePermitId)(e),policiesFor=(e,t,n)=>{let{redactedClasses:r}=n,describing=e=>{for(let n of t)if(Object.prototype.hasOwnProperty.call(n.descriptors??{},e))return n.descriptors?.[e]},i=new Map;for(let t of e.resolved)for(let r of t.checked.filter(isAuthored)){if(i.has(r))continue;let a=describing(r),o=effectOf(r,e,n);i.set(r,{id:r,...a&&{name:a.name,version:a.version},level:t.level,mode:t.mode,...o&&{effect:o}})}for(let e of r)if(e.level!==void 0)for(let t of e.policyIds.filter(isAuthored)){if(i.has(t))continue;let n=describing(t);i.set(t,{id:t,...n&&{name:n.name,version:n.version},level:e.level,mode:`enforce`,effect:`redacted`})}return[...i.values()]},toPolicyContext=(e,t,n={})=>{let{maskedFields:r=[],degraded:i=!1,redactedClasses:a=[],observedFields:o=[]}=n,s=e.deniedBy?.policyIds??[],c=policiesFor(e,t.levels??[],{maskedFields:r,redactedClasses:a,observedFields:o});return{result:policyResultOf(e,{changed:r.length>0||a.length>0,degraded:i,watched:o.length>0}),...identity(t),policyIds:s,...e.deniedBy&&{level:e.deniedBy.level},...c.length>0&&{policies:c},...r.length>0&&{maskedFields:r},...o.length>0&&{observedFields:o},...a.length>0&&{redactedClasses:a},...e.observed.length>0&&{observed:e.observed},...e.resolved.length>0&&{resolved:e.resolved}}},preparseFailureContext=e=>({result:`error`,...identity(e),policyIds:[]}),categoryOf=e=>e.categories?.[0]?.toLowerCase()??`unknown`;let $;const Re={warn:(e,t)=>$?.warning({message:e,context:t}),error:(e,t)=>$?.error({code:`PolicyEvaluationError`,message:e,context:t})};let ze;const sharedPolicyEvaluator=e=>($??=e,ze??=(0,l.createEvaluator)(Re)),ownLabelsOf=(e,t)=>e&&hasOwnKey(e,t)?e[t]:[],decideReadFields=async e=>{if(e.policy.levels.length===0||e.paths.length===0)return{evaluated:!1,fields:e.paths.map(e=>({path:e,decision:`allow`,faulted:!1,observed:[]}))};let t=e.evaluator??sharedPolicyEvaluator(e.logger),n=await(0,l.prepareLevels)(t,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(t,async()=>n).decideFields({principal:e.policy.principal,action:`readField`,account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},fields:e.paths.map(t=>({id:t,path:t,labels:ownLabelsOf(e.policy.fieldLabels,labelKeyOf(t))})),context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType),...e.policy.client?{client:e.policy.client}:{}}})},decideInvokeTool=async e=>{if(e.policy.levels.length===0)return{decision:`allow`,evaluated:!1,faulted:!1,observed:[],resolved:[]};let t=e.evaluator??sharedPolicyEvaluator(e.logger),n=await(0,l.prepareLevels)(t,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(t,async()=>n).decide({principal:e.policy.principal,tool:{id:e.action.id,name:e.policy.toolName??e.action.id,labels:[]},account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},args:e.args,context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType),...e.policy.client?{client:e.policy.client}:{}}})},Be=[{id:`email`,group:`PersonalInfo`},{id:`phone_number`,group:`PersonalInfo`},{id:`ssn`,group:`PersonalInfo`},{id:`credit_card`,group:`Financial`}],Ve={email:[`email`,`email_address`],credit_card:[`credit_card`,`credit_debit_card`]},modelLabelsForClasses=e=>{let t=new Set;for(let n of e)for(let e of Ve[n]??[n])t.add(e);return t},classWasApplied=(e,t)=>(Ve[e]??[e]).some(e=>t.has(e)),decideRedactionClasses=async e=>{let t=e.classes??Be;if(e.policy.levels.length===0||t.length===0)return{evaluated:!1,classes:t.map(e=>({class:e.id,decision:`allow`,faulted:!1,observed:[]}))};let n=e.evaluator??sharedPolicyEvaluator(e.logger),r=await(0,l.prepareLevels)(n,{organizationId:e.account.organizationId,levels:e.policy.levels});return(0,l.createDecider)(n,async()=>r).decideRedactionClasses({principal:e.policy.principal,account:{id:e.account.secureId,connector:e.account.providerKey,category:categoryOf(e.action)},classes:t,context:{orgId:e.account.organizationId,projectId:null,sessionId:e.sessionId??``,credential:credentialOf(e.authType)}})},evaluateExternalAccountIdExtractorByConnector=(e,t)=>(0,s.evaluateExternalAccountIdExtractor)(e,t),executeStepFunction=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=s.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===s.StepFunctionName.MAP_FIELDS?{[s.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},definitionVersionOf=e=>[...e].reduce((e,t)=>Math.imul(e^t.charCodeAt(0),16777619)>>>0,2166136261).toString(16).padStart(8,`0`),He=/(?:[A-Za-z_][A-Za-z0-9_]*::)*Label::"((?:[^"\\]|\\.)*)"/g,Ue=/@unlabelled\(\s*"allow"\s*\)/,isRecord=e=>typeof e==`object`&&!!e&&!Array.isArray(e),labelsNamedBy=e=>typeof e==`string`?[...e.matchAll(He)].map(([,e])=>e.replace(/\\"/g,`"`)):Array.isArray(e)?e.flatMap(labelsNamedBy):isRecord(e)?[...typeof e.type==`string`&&/(^|::)Label$/.test(e.type)&&typeof e.id==`string`?[e.id]:[],...Object.values(e).flatMap(labelsNamedBy)]:[],policySetsOf=e=>e.flatMap(e=>[e.enforce,e.monitor].filter(e=>e!==void 0)),labelsReferencedBy=e=>[...new Set(policySetsOf(e).flatMap(e=>[...labelsNamedBy(e.staticPolicies),...labelsNamedBy(e.templates)]))],allowsUnlabelled=e=>typeof e==`string`?Ue.test(e):isRecord(e)&&isRecord(e.annotations)?e.annotations.unlabelled===`allow`:!1,unlabelledAllowPolicyIdsOf=e=>new Set(policySetsOf(e).flatMap(e=>{let t=isRecord(e.staticPolicies)?Object.entries(e.staticPolicies):[],n=new Set(Object.entries(e.templates??{}).filter(([,e])=>allowsUnlabelled(e)).map(([e])=>e));return[...t.filter(([,e])=>allowsUnlabelled(e)).map(([e])=>e),...(e.templateLinks??[]).filter(e=>n.has(e.templateId)).map(e=>e.newId)]})),We=new Map([[`request`,`GET`],[`paginated_request`,`GET`],[`soap_request`,`POST`],[`soap_paginated_request`,`POST`],[`download_file`,`GET`],[`upload_file`,`POST`],[`upload_binary`,`POST`]]),Ge=__name(e=>{if(!isRecord(e))return[];let t=Array.isArray(e.stepFunctions)?e.stepFunctions:[],n=isRecord(e.stepFunction)?[e.stepFunction]:[];return[...t,...n].filter(isRecord)},`stepFunctionsOf`),requestOf=e=>{let t=We.get(e.functionName),n=e.params??{};return!t||typeof n.url!=`string`||n.url===``?[]:[`${typeof n.method==`string`?n.method.toUpperCase():t} ${n.url}`]},providerRequestsOf=e=>[...new Set(Object.values(isRecord(e.steps)?e.steps:{}).flatMap(e=>Ge(e).flatMap(requestOf)))].slice(0,5),shapeOf=(e,t,n)=>{let r=e.flatMap(e=>t&&hasOwnKey(t,e)?[t[e]]:[]),i=e.flatMap(e=>n&&hasOwnKey(n,e)?[n[e]]:[]);return{valueType:r.length===0?`mixed`:r.reduce((e,t)=>combineValueTypes(e,t)),parent:i[0]?.parent??``,siblings:[...new Set(i.flatMap(e=>e.siblings))].slice(0,12),siblingCount:Math.max(0,...i.map(e=>e.siblingCount))}},Ke=/^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$/,declaredPaginationPathsOf=e=>{let t=isRecord(e.dataSync)?e.dataSync:void 0,n=t?.pagination,r=t?.incremental;return[n?.type===`cursor`?n.response?.nextKey:void 0,r?.type===`delta_token`?r.response?.path:void 0].filter(e=>typeof e==`string`&&Ke.test(e))},isWithin=(e,t)=>e===t||e.startsWith(`${t}.`)||e.startsWith(`${t}[`),unlabelledPathsOf=e=>{let t=declaredPaginationPathsOf(e.action);return new Set([...e.identifierPaths??[],...e.paths.filter(e=>t.some(t=>isWithin(e,t)))])},withoutStoredLabels=(e,t)=>{let n=e.policy.fieldLabels,r=new Set([...t].map(labelKeyOf));return!n||r.size===0?e:{...e,policy:{...e.policy,fieldLabels:Object.fromEntries(Object.entries(n).filter(([e])=>!r.has(e)))}}},answersWithin=async(e,t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await Promise.race([e(t,r.signal),new Promise((e,t)=>r.signal.addEventListener(`abort`,()=>t(Error(`Field labelling deadline passed`))))])}finally{clearTimeout(i)}},createLabellingDecideReadFields=e=>{let t=e.decide??decideReadFields;return async n=>{let r=unlabelledPathsOf(n),i=withoutStoredLabels(n,r),a=i.policy.labelDefinitions??{},isDefined=e=>hasOwnKey(a,e),o=labelsReferencedBy(i.policy.levels),s=o.filter(e=>!isDefined(e));s.length>0&&i.logger?.warning({message:`Rules name labels with no definition, so no field can be classified under them: ${s.join(`, `)}`,category:`runAction`});let c=o.filter(isDefined);if(c.length===0)return t(i);let l=i.policy.fieldLabels??{},u=new Map;for(let e of i.paths){let t=labelKeyOf(e);!hasOwnKey(l,t)&&!r.has(e)&&u.set(t,[...u.get(t)??[],e])}if(u.size===0)return t(i);let d=providerRequestsOf(i.action),f=[...u].flatMap(([e,t])=>{let n={fieldPath:e,connector:i.account.providerKey,action:i.action.id,...i.action.description&&{actionDescription:i.action.description},requests:d,...shapeOf(t,i.valueTypes,i.neighbours)};return c.map(t=>({labelKey:e,label:t,definition:a[t],evidence:n}))}),p=await answersWithin(e.labeller,f,e.deadlineMs).catch(e=>(i.logger?.warning({message:`Field labelling failed, unanswered fields fall back to every referenced label: ${e instanceof Error?e.message:String(e)}`,category:`runAction`}),{answers:[],modelVersion:``})),m=new Map(p.answers.map(e=>[`${e.labelKey}|${e.label}`,e])),h=[...u.keys()].filter(e=>c.some(t=>!m.has(`${e}|${t}`))),g=new Set(h),labelsOf=(t,n)=>c.filter(r=>{let i=m.get(`${t}|${r}`);return i===void 0?n:i.score>=e.thresholdFor(r)}),withLabels=e=>({...l,...Object.fromEntries([...u.keys()].map(t=>[t,labelsOf(t,e)]))});e.onLabelled?.({decisions:p.answers.map(e=>({labelKey:e.labelKey,label:e.label,score:e.score,modelVersion:p.modelVersion,definitionVersion:definitionVersionOf(isDefined(e.label)?a[e.label]:``),evidence:`shape`})),unanswered:h});let _=await t({...i,policy:{...i.policy,fieldLabels:withLabels(!0)}}),v=unlabelledAllowPolicyIdsOf(i.policy.levels);if(g.size===0||v.size===0)return _;let y=await t({...i,policy:{...i.policy,fieldLabels:withLabels(!1)}}),b=new Map(y.fields.map(e=>[e.path,e]));return{..._,fields:_.fields.map(e=>{let t=e.deniedBy?.policyIds??[];return e.decision===`deny`&&!e.faulted&&g.has(labelKeyOf(e.path))&&t.length>0&&t.every(e=>v.has(e))?b.get(e.path)??e:e})}}},qe=`[redacted by policy]`,isPlainObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),joinKey=(e,t)=>/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?e?`${e}.${t}`:t:`${e}["${t.replace(/"/g,`\\"`)}"]`,maskFields=(e,t,n)=>{let r=new Set(t);if(r.size===0&&n===void 0)return{payload:e,masked:[]};let i=new Set,walk=(e,t)=>{if(t!==``&&r.has(t))return i.add(t),qe;if(Array.isArray(e))return e.map(e=>walk(e,`${t}[]`));if(isPlainObject(e)){let n={};for(let[r,i]of Object.entries(e))n[r]=walk(i,joinKey(t,r));return n}return t!==``&&n&&!n.has(t)?(i.add(t),qe):e};return{payload:walk(e,``),masked:[...i]}},createBlockContext=({category:e,connectorKey:n,connectorVersion:r,connectorOwner:i,connectorProfileId:a,authConfigKey:o,environment:s=`production`,action:c,accountSecureId:l,projectSecureId:u,organizationId:d,originOwnerId:f,originOwnerName:p,sourceType:m,sourceId:h,authType:g,authId:_,sessionId:v,agentId:y,userAgent:b,ipAddress:x,transportType:S,streamType:C,flowType:w,sourceValue:T})=>({organizationId:d,projectSecureId:u,accountSecureId:l,connectorKey:n,connectorVersion:r,connectorOwner:i,connectorProfileId:a,category:e,service:``,resource:``,originOwnerId:f,originOwnerName:p,sourceType:m,sourceId:h,authType:g,authId:_,sessionId:v,agentId:y,userAgent:b,ipAddress:x,transportType:S,streamType:C,schema:c?.schema?.key,actionType:c?.actionType??`unknown`,authenticationType:o,environment:s,actionRunId:(0,t.generateActionRunId)(),flowType:w,sourceValue:T}),getTestActions=(e,t,n)=>e.authentication?.[t]?.[n]?.testActions,normalizeActingUser=e=>{if(!e)return;let t=e.email?.trim().toLowerCase();return{id:e.id,...t&&{email:t}}},isUserScoped=e=>e.userScoped===!0||(0,t.isObject)(e.userScoped),actingUserRefusal=(e,t,n)=>isUserScoped(e)&&!t?.email?.trim()?new ActingUserRequiredError(n,`Action '${e.id}' answers for the acting user and the call carries no user email`):void 0,validateActingUser=(e,t,n)=>{let r=actingUserRefusal(e,t,n);if(r)throw r},validateAuthTypeCompatibility=(e,n,r)=>{if(!Object.prototype.hasOwnProperty.call(e,`authRequirements`)||(0,t.isMissing)(n))return;let i=e.authRequirements;if(!(0,t.isMissing)(i)&&!(n in i)){let t=Object.keys(i).join(`, `);throw new IncompatibleAuthTypeError(r,`Action '${e.id}' is not compatible with authentication type '${n}'. Compatible types: ${t}`)}};function extractStrings(e){let t=[];function traverse(e){typeof e==`string`?t.push(e):Array.isArray(e)?e.forEach(traverse):e&&typeof e==`object`&&Object.values(e).forEach(traverse)}return traverse(e),t}function estimateResponseSize(e){try{let t=JSON.stringify(e);return{bytes:Buffer.byteLength(t,`utf8`),words:extractStrings(e).join(` `).split(/\s+/).filter(Boolean).length}}catch{return{bytes:0,words:0}}}function shouldSkipDefender(e,t){if(!t?.enabled)return{skip:!0,reason:`disabled`};let n=t.maxResponseSize??1048576,r=t.maxResponseWords??1e4,i=estimateResponseSize(e);return i.bytes>n||i.words>r?(t.largeResponseBehavior??`skip`)===`skip`?{skip:!0,reason:`size_limit`,size:i}:{skip:!1,size:i}:{skip:!1}}const decodeInputCompositeIdentifiers=e=>{let n=e.action?.compositeIdentifiers,r={...e.inputs??{}};if(!n?.enabled||(0,t.isMissing)(r))return e;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{});return processLevel(r,{version:n.version??s.COMPOSITE_ID_LATEST_VERSION,aliases:i},e.logger),{...e,inputs:r}},processLevel=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))processCompositeId(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)processLevel(e,t,n);else typeof i==`object`&&i&&processLevel(i,t,n)}},processInputElements=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,s.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},setDecodedIds=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},shouldSimplifyComponent=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},setSimplifiedIds=(e,t,n,r,i)=>{n.every(shouldSimplifyComponent)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},handleCompositeIdError=(e,t,n)=>{e instanceof s.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},processCompositeId=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=processInputElements(o,t,r,i);setDecodedIds(n,t,s,a),setSimplifiedIds(n,t,s,c,a)}catch(e){handleCompositeIdError(e,t,i)}},Je=`remote_`,encodeResultCompositeIdentifiers=e=>{let n=e.action?.compositeIdentifiers;if(!n?.enabled)return e;let r=`data`,i=e.outputs?.[r];if((0,t.isMissing)(i))return e;let a=Array.isArray(i)?i.map(e=>mapCompositeIds(e,n)):mapCompositeIds(i,n);return{...e,outputs:{...e.outputs??{},[r]:a}}},mapCompositeIds=(e,n)=>{let r=mapCompositeIdsFromInference(mapConfiguredCompositeIds(e,n));return{...e,...(0,t.isObject)(r)?r:{}}},mapConfiguredCompositeIds=(e,t)=>{let n=t.version??s.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=(0,s.encodeCompositeId)(a.length===1?a[0]:{identifiers:a},{version:n,aliases:Object.keys(i).length>0?i:void 0});r[t.targetFieldKey]=o,t.remote&&(r[`${Je}${t.remote}`]=e[t.remote])}),{...e,...r}},isIdField=e=>e===`id`||/.+_id(s)?$/.test(e),isValidStringArray=e=>Array.isArray(e)&&e.every(e=>(0,t.isString)(e)&&e.length>0),shouldSkipEncoding=(e,t)=>(0,s.isCompositeId)(e)||t.startsWith(Je),encodeStringValue=(e,t)=>{try{return(0,s.encodeCompositeId)({key:e,value:t},{version:s.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},processStringArrayField=(e,n,r)=>{r[e]=n.map(n=>(0,t.isString)(n)&&n.length>0&&!(0,s.isCompositeId)(n)?encodeStringValue(e,n):n),r[`${Je}${e}`]=n},processStringField=(e,t,n)=>{shouldSkipEncoding(t,e)||(n[e]=(0,s.encodeCompositeId)({key:e,value:t},{version:s.COMPOSITE_ID_LATEST_VERSION}),n[`remote_${e}`]=t)},processIdField=(e,n,r)=>{isValidStringArray(n)?processStringArrayField(e,n,r):(0,t.isString)(n)&&n.length>0&&processStringField(e,n,r)},mapCompositeIdsFromInference=e=>{if(Array.isArray(e))return e.map(e=>mapCompositeIdsFromInference(e));if(!(0,t.isObject)(e))return e;let n={...e};for(let[r,i]of Object.entries(e))((0,t.isObject)(i)||Array.isArray(i)&&i.length>0&&(0,t.isObject)(i[0]))&&(n[r]=mapCompositeIdsFromInference(i)),isIdField(r)&&processIdField(r,i,n);return n},getPageSize=(e,n)=>{let r=Number(e.inputs?.page_size);return(0,t.notMissing)(e.inputs?.page_size)&&(0,t.isNumber)(r)&&!Number.isNaN(r)?r:e.action?.cursor?.pageSize??n},virtualPaginateResult=(e,n,r,i)=>{let a=(0,t.isMissing)(e)?void 0:e.data,o=Object.keys(r).length+1,c=(0,s.isCursorEmpty)({cursor:i,ignoreStepIndex:o});if(!(0,t.isObject)(e)||(0,t.isMissing)(a)||(a?.length??0)<=n)return{result:e,next:(0,t.notMissing)(i)&&!c?(0,s.minifyCursor)(i):null};let l=i?.remote?.[o]?.pageNumber??1,u=(l-1)*n,d=u+n,f=a.slice(u,d),p=a.length>d||!c,m=(0,s.updateCursor)({cursor:i,stepIndex:o,pageNumber:l+1});return{result:{...e,data:f},next:p?(0,s.minifyCursor)(m):null}},normalizeEmail=e=>e.trim().toLowerCase(),emailsAt=(e,t)=>{try{let n=(0,c.evaluate)(t,e);return(Array.isArray(n)?n:[n]).filter(e=>typeof e==`string`)}catch{return[]}},belongsTo=(e,n,r)=>(0,t.isObject)(e)&&n.some(t=>emailsAt(e,t).some(e=>normalizeEmail(e)===r)),scoped=(e,t,n=0)=>({outcome:`scoped`,block:{...e,outputs:t},omitted:n}),applyUserScope=(e,n,r)=>{let i=(0,t.isObject)(n.userScoped)?n.userScoped.identity:void 0;if(!i?.length||e.response?.successful!==!0)return{outcome:`scoped`,block:e,omitted:0};if((0,t.notMissing)(e.streamOutput))return{outcome:`violated`,message:`returns a stream, which cannot be checked`};let a=r?.email?.trim()?normalizeEmail(r.email):void 0;if(!a)return{outcome:`violated`,message:`has no acting user email to check against`};let o=e.outputs;if(!(0,t.isObject)(o)||!(`data`in o))return{outcome:`violated`,message:`returned no data to check against the caller`};let{data:s}=o,c=`next`in o?{next:o.next}:{};if(s==null)return scoped(e,{data:s,...c});if(Array.isArray(s)){let t=s.filter(e=>belongsTo(e,i,a));return scoped(e,{data:t,...c},s.length-t.length)}return belongsTo(s,i,a)?scoped(e,{data:s,...c}):{outcome:`violated`,message:`returned a record that does not belong to the caller`}},withoutStepOutputs=(e,t)=>isUserScoped(t)?{...e,steps:{},intermediateSteps:{}}:e,refuse=(e,t,n)=>({...e,outputs:void 0,streamOutput:void 0,response:{successful:!1,statusCode:t,message:n}}),messageOf=e=>e instanceof Error?e.message:String(e),parseCalleeInputs=(e,t)=>{try{return{inputs:parseActionInputs(e,{path:t?.path,query:t?.query,body:t?.body,headers:t?.headers})}}catch(e){return{error:describeInputIssues(e)}}},describeInputIssues=e=>e instanceof t.z.ZodError?e.issues.map(e=>{let t=e.path.map(String),n=t[0]??`body`,r=t.slice(1).join(`.`);return r?`${n}.${r}: ${e.message}`:`${n}: ${e.message}`}).join(`; `):messageOf(e),usesCallAction=e=>(0,s.stepsUseFunction)(e?.steps,s.StepFunctionName.CALL_ACTION),expandCalleeCursor=(e,n,r)=>{let i=r?.query?.next;if(!(0,t.notMissing)(i)||n.actionType!==`list`)return{};if(e.action?.cursor.enabled)return{error:`a paginated action cannot forward a cursor to a nested call, because nothing relates its pages to the callee's. Call '${n.id}' from an action that is not itself paginated`};if(typeof i!=`string`)return{error:`'next' must be a cursor token, not an expanded cursor`};let a=(0,s.expandCursor)(i);return a===null?{error:`'next' is not a valid cursor`}:{cursor:a}},buildCalleeBlock=(e,t,n,r)=>({connector:e.connector,context:{...e.context,actionType:t.actionType,schema:t.schema?.key},credentials:e.credentials,user:e.user,httpClient:e.httpClient,olapClient:e.olapClient,settings:e.settings,logger:e.logger,debug:e.debug,scopes:e.scopes,emitEvent:e.emitEvent,action:t,inputs:n,callAction:void 0,steps:{},intermediateSteps:{},iterator:void 0,result:void 0,outputs:void 0,streamOutput:void 0,response:void 0,statistics:void 0,defenderMetadata:void 0,policyMetadata:void 0,responseHeaders:void 0,nextCursor:r,fieldConfigs:[]}),createCallActionRunner=(e,n)=>async({actionId:r,inputs:i})=>{let a=e.connector;if(!(0,t.notMissing)(a))return refuse(e,500,`call_action cannot resolve a target: no connector on the block.`);let o=findActionByActionId(a,r);if(!(0,t.notMissing)(o))return refuse(e,500,`call_action target '${r}' is not an action of connector '${a.key}'.`);if(n.ancestors.has(o.id))return refuse(e,500,`call_action would re-enter action '${o.id}', which is already running. Chain: ${[...n.ancestors,o.id].join(` -> `)}.`);if(n.depth>=4)return refuse(e,500,`call_action exceeded the maximum nesting depth of 4 while calling '${o.id}'.`);if(n.budget.remaining<=0)return refuse(e,500,`call_action exceeded the maximum of 32 nested calls per request while calling '${o.id}'.`);try{validateAuthTypeCompatibility(o,e.context.authenticationType,e.context),validateActingUser(o,e.user,e.context)}catch(t){return refuse(e,403,messageOf(t))}let s=parseCalleeInputs(o,i);if(`error`in s)return refuse(e,400,`call_action inputs for '${o.id}' are invalid: ${s.error}`);let c=expandCalleeCursor(e,o,i);if(`error`in c)return refuse(e,400,`call_action cannot page '${o.id}': ${c.error}.`);--n.budget.remaining;let l=buildCalleeBlock(e,o,s.inputs,c.cursor);usesCallAction(o)&&(l.callAction=createCallActionRunner(l,{...n,depth:n.depth+1,ancestors:new Set([...n.ancestors,o.id])}));let u=await n.executeSteps(l);if((0,t.notMissing)(u.streamOutput))return u.streamOutput.stream?.destroy(),refuse(e,500,`Action '${o.id}' returns a stream, which cannot be consumed by call_action. Call it directly instead.`);let d=applyUserScope(u,o,e.user);return d.outcome===`violated`?refuse(e,403,`Action '${o.id}' ${d.message}`):d.block},createRootCallActionRunner=(e,t)=>createCallActionRunner(e,{...t,depth:0,ancestors:new Set(e.action?.id?[e.action.id]:[]),budget:{remaining:32}}),rawHeadersOf=e=>{if(!e.successful||e.skipped)return;let n=Array.isArray(e.output?.raw)?e.output.raw.at(-1):e.output?.raw,r=(0,t.isObject)(n)?n.headers:void 0;return(0,t.isObject)(r)?r:void 0},lowercaseKeys=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),extractDataSyncResponseHeaders=e=>{let n=e.action?.dataSync;if(!(e.context?.sourceType===s.SourceType.DataSyncV2&&((0,t.notMissing)(n?.pagination)||(0,t.notMissing)(n?.incremental))))return;let r=Object.values(e.steps??{}).reverse().map(rawHeadersOf).find(t.notMissing);return r?lowercaseKeys(r):void 0},runStepAction=async({block:e,buildStepFunction:t=s.StepFunctionsFactory.build,virtualPaginateResultFn:n=virtualPaginateResult,encodeResultCompositeIds:r=encodeResultCompositeIdentifiers,decodeInputCompositeIds:i=decodeInputCompositeIdentifiers})=>{let a=i(e);return r(await executeStepsWorkflow({block:usesCallAction(a.action)?{...a,callAction:createRootCallActionRunner(a,{executeSteps:e=>executeStepsWorkflow({block:e,buildStepFunction:t,virtualPaginateResultFn:n})})}:a,buildStepFunction:t,virtualPaginateResultFn:n}))},captureErrorDetails=(e,n)=>{e.errorStatusCode??=n?.statusCode??500,!(0,t.notMissing)(e.errorMessage)&&typeof n?.message==`string`&&(e.errorMessage=n.message),e.errorData??=n?.data,e.errorRaw??=n?.raw},buildConditionContext=e=>{let t=(0,s.buildExpressionContext)(e,{includeCredentials:!0});return`action`in e&&(t.action=e.action),`nextCursor`in e&&(t.nextCursor=e.nextCursor),`scopes`in e&&(t.scopes=e.scopes),t},resolveConditionOutcome=(e,t)=>{if(!e.condition)return{kind:`run`};let{errored:n,value:r,error:i}=(0,c.evaluateConditionExpression)(e.condition,buildConditionContext(t));if(!n)return r?{kind:`run`}:{kind:`skip`,message:`Step skipped due to condition not met.`};let a=e.onConditionError??!1;return a===`break`?{kind:`fail`,message:`Step condition failed to evaluate.`,error:i}:a===!0?{kind:`run`,message:`Step ran due to a condition evaluation error.`}:{kind:`skip`,message:`Step skipped due to a condition evaluation error.`}},stampConditionNote=(e,n,r)=>{let i=e.steps?.[n];return!i||i.successful===!1||(0,t.notMissing)(i.message)?e:{...e,steps:{...e.steps,[n]:{...i,message:r}}}},buildStepParamsForFunction=(e,n,r)=>{let i=s.StepFunctionsRegistry[e.functionName]?.[`v${e.version??1}`],a=(0,t.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return n.action?.cursor.enabled&&a?{...e.params??{},cursor:{token:n.nextCursor?.remote?.[r]?.providerPageCursor,position:n.nextCursor?.remote?.[r]?.position}}:e.params??{}},buildStepParams=(e,t,n)=>e.stepFunction?buildStepParamsForFunction(e.stepFunction,t,n):{},handleStepFailure=async(e,t,n,r,i,a,o,s)=>{let c=await addStepResultToBlock({block:e,stepId:t,stepIndex:n,successful:!1,functionOutput:r,startTime:o,endTime:s});return(i.ignoreError??!1)||(a.hasFatalError=!0,captureErrorDetails(a,r.output)),c},isCredentialRecoveryStep=(e,t)=>t.action?.actionType===`refresh_token`&&!(0,s.isForeachStep)(e)&&e.stepFunction?.functionName===s.StepFunctionName.MAP_FIELDS,executeStep=async(e,n,r,i,a,o,c)=>{let l=new Date,u=r[e];if(a.hasFatalError&&!isCredentialRecoveryStep(u,i))return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:`Step skipped due to previous error.`,startTime:l,endTime:l});let d=resolveConditionOutcome(u,i);if(d.kind===`skip`)return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!0,skipped:!0,message:d.message,startTime:l,endTime:l});if(d.kind===`fail`){let r=d.error??d.message;return a.errorStatusCode??=500,(0,t.notMissing)(a.errorMessage)||(a.errorMessage=d.message,a.errorData??={error:r}),a.hasFatalError=!0,await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:d.message,errors:[{message:r}],startTime:l,endTime:l})}let f=a.hasFatalError?await executeCredentialRecoveryStep(e,n,u,i,a,o,c):(0,s.isForeachStep)(u)?await executeForeachStep(e,n,u,i,a,o,c):await executeSimpleStep(e,n,u,i,a,o,c);return d.message?stampConditionNote(f,e,d.message):f},withoutFailedStepOutputs=e=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,t.successful?t:{...t,output:void 0}])),executeCredentialRecoveryStep=async(e,n,r,i,a,o,s)=>{let c=await executeSimpleStep(e,n,r,{...i,steps:withoutFailedStepOutputs(i.steps)},a,o,s),l=c.steps?.[e];return{...c,steps:(0,t.notMissing)(l)?{...i.steps,[e]:l}:i.steps}},executeSimpleStep=async(e,t,n,r,i,a,o)=>{let c=new Date,l=n.stepFunction;if(!l)return await addStepResultToBlock({block:r,stepId:e,stepIndex:t,successful:!1,message:`Step function is not defined.`,startTime:c,endTime:new Date});let u=a.buildStepFunction({functionName:l.functionName,version:l.version,validateSchemas:!0}).fn,d=await u({block:r,params:buildStepParams(n,r,t)});if(d.successful===!1)return await handleStepFailure(r,e,t,d,n,i,c,new Date);if(d.streamOutput)return o?await addStepResultToBlock({block:{...d.block,streamOutput:d.streamOutput},stepId:e,stepIndex:t,successful:!0,functionOutput:d,startTime:c,endTime:new Date}):(i.hasFatalError=!0,i.errorStatusCode=500,i.errorMessage=`Stream output can only be used in the final step of an action. Move the streaming step to the end or use responseMode: "buffer".`,await addStepResultToBlock({block:r,stepId:e,stepIndex:t,successful:!1,message:`Stream output can only be used in the final step of an action. Move the streaming step to the end or use responseMode: "buffer".`,startTime:c,endTime:new Date}));let f=r.action?.cursor.enabled?(0,s.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:d.output?.next,position:d.output?.position}):void 0;return await addStepResultToBlock({block:{...d.block,nextCursor:f},stepId:e,stepIndex:t,successful:!0,functionOutput:d,startTime:c,endTime:new Date})},executeForeachStep=async(e,n,r,i,a,o,l)=>{let u=new Date,d=(0,c.safeEvaluate)(r.iterator,i);if(!Array.isArray(d))return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,skipped:!0,message:`Step skipped because iterator expression did not return an array.`,startTime:u,endTime:u});let f=(0,s.stepFunctionsOf)(r);if(f.length===0)return await addStepResultToBlock({block:i,stepId:e,stepIndex:n,successful:!1,message:`No step functions defined for foreach step.`,startTime:u,endTime:new Date});let p=[],m=i,h,g={};for(let[i,s]of d.entries()){let c={...m,iterator:{item:s,index:i}};for(let l of f){let d=o.buildStepFunction({functionName:l.functionName,version:l.version,validateSchemas:!0}).fn,f=buildStepParamsForFunction(l,c,n),p=await d({block:c,params:f});if(h=p,p.successful===!1&&!(r.ignoreError??!1))return a.hasFatalError=!0,captureErrorDetails(a,p.output),g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:!1,output:p.output,errors:p.errors}},await addStepResultToBlock({block:{...m,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!1,functionOutput:p,startTime:u,endTime:new Date});if(c={...p.block,iterator:{item:s,index:i,current:p.output}},p.streamOutput)return a.hasFatalError=!0,a.errorStatusCode=500,a.errorMessage=`Stream output is not supported in foreach steps.`,g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:!1,message:`Stream output is not supported in foreach steps.`}},await addStepResultToBlock({block:{...m,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!1,message:`Stream output is not supported in foreach steps.`,startTime:u,endTime:new Date})}m=c,g[i]={iterator:(0,t.isObject)(s)?void 0:String(s),snapshot:{successful:h?.successful??!0,output:h?.output,errors:h?.errors}},h?.output&&p.push(h.output)}let _=i.action?.cursor.enabled?(0,s.updateCursor)({cursor:i.nextCursor,stepIndex:n,providerPageCursor:h?.output?.next,position:h?.output?.position}):void 0,v={block:m,successful:!0,output:{data:p}};return await addStepResultToBlock({block:{...m,nextCursor:_,intermediateSteps:{...m.intermediateSteps,[e]:g}},stepId:e,stepIndex:n,successful:!0,functionOutput:v,startTime:u,endTime:new Date})},buildFinalResponse=(e,n,r,i,o)=>{let s=!r.hasFatalError,c=s?e.action?.responses.success.statusCode??200:r.errorStatusCode??500,l=s?void 0:r.errorMessage??e.action?.responses?.errors?.[c]?.description??a.HttpErrorMessages?.[c]??`Error while processing the request`,u=s?{}:{...r.errorData===void 0?{}:{data:r.errorData},...r.errorRaw===void 0?{}:{raw:r.errorRaw}};if(n.streamOutput)return{...n,response:{successful:s,statusCode:c,message:l,...u}};let d=(0,t.notMissing)(o)&&(0,t.isObject)(o.result)?{next:o.next,...o.result}:i;return{...n,outputs:d,response:{successful:s,statusCode:c,message:l,...u}}},executeStepsWorkflow=async({block:e,buildStepFunction:t=s.StepFunctionsFactory.build,virtualPaginateResultFn:n=virtualPaginateResult})=>{let r=e.action?.steps||{},i={...e},a=Object.keys(r),o=getPageSize(e,25),c={hasFatalError:!1,errorStatusCode:null},l={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries()){let n=e===a.length-1;i=await executeStep(t,e,r,i,c,l,n)}let u=e.action?.result?evaluateResult(e.action.result,i):void 0,d=e.action?.cursor.enabled?n(u,o,r,i.nextCursor):void 0,f=extractDataSyncResponseHeaders(i);return buildFinalResponse(e,f?{...i,responseHeaders:f}:i,c,u,d)},evaluateResult=(e,n)=>{let r=(0,s.buildExpressionContext)(n);return(0,t.isObject)(e)?(0,c.safeEvaluateRecord)(e,r):(0,c.safeEvaluate)(e,r)},addStepResultToBlock=async({block:e,stepId:t,stepIndex:n,successful:r,functionOutput:i,skipped:a,message:o,errors:s,startTime:c,endTime:l})=>({...e,steps:{...e.steps,[t]:{successful:r??i?.successful??!1,errors:s??i?.errors,output:i?.output,skipped:a,message:o,statistics:{startTime:c,endTime:l}}}}),Ye={drop:!0,truncate:!0,complete:!0},isTruncationMode=e=>typeof e==`string`&&Ye[e]===!0,getOlapOptions=e=>{let n=e?.olap;if((0,t.isMissing)(n))return{};let r=n.logs,i=r&&typeof r.enabled==`boolean`?{enabled:r.enabled}:void 0,a=n.advanced,o=a?{}:void 0;return a&&o&&(typeof a.enabled==`boolean`&&(o.enabled=a.enabled),typeof a.ttl==`number`&&(o.ttl=a.ttl),typeof a.errorsOnly==`boolean`&&(o.errorsOnly=a.errorsOnly),typeof a.includeBackground==`boolean`&&(o.includeBackground=a.includeBackground),isTruncationMode(a.truncation)&&(o.truncation=a.truncation),typeof a.piiRedactionEnabled==`boolean`&&(o.piiRedactionEnabled=a.piiRedactionEnabled)),{logs:i,advanced:o}},recordActionResult=async({action:e,resultBlock:n,mode:r,organizationId:i,pathParams:a,queryParams:o,body:s,headers:c,source:l,isBackground:u,settings:d,logger:p,policyContext:m,refusal:h})=>{if((0,t.isMissing)(e)){p?.warning({message:`action missing, skipping recording action result`});return}let g=n.olapClient;if((0,t.isMissing)(g)){p?.warning({message:`olap client is missing, skipping recording action result`});return}let _=getOlapOptions(d),v=n.context,y={actionId:e.id,actionRunId:v.actionRunId||`missing`,mode:r,connectorKey:v.connectorKey,connectorVersion:v.connectorVersion,connectorOwner:v.connectorOwner,connectorProfileId:v.connectorProfileId,actionType:v.actionType,category:v.category,organizationId:i,projectSecureId:v.projectSecureId,accountSecureId:v.accountSecureId,originOwnerId:v.originOwnerId,originOwnerName:v.originOwnerName,sourceType:l?.sourceType,sourceId:l?.sourceId,authType:l?.authType,authId:l?.authId,sessionId:l?.sessionId,agentId:l?.agentId,userAgent:l?.userAgent,ipAddress:l?.ipAddress,transportType:l?.transportType,streamType:l?.streamType,httpMethod:e?.entrypointHttpMethod,url:e?.entrypointUrl,pathParams:a,queryParams:o,body:s,headers:c,isBackground:u,startTime:n.statistics?.startTime},b=Object.values(n.steps??{}).some(e=>e?.successful===!1||(0,f.hasErrorEntries)(e?.errors)),x={success:n.response?.successful??!1,statusCode:n.response?.statusCode,body:n.outputs??void 0,message:n.response?.message,hasStepErrors:b,endTime:n.statistics?.endTime,defenderContext:n.defenderMetadata,...m&&{policyContext:m},...h&&{refusal:h}};try{await g.recordAction(y,x,_);let r=e.steps||{},a=Object.keys(r).map((e,a)=>{let o=n.steps?.[e];if((0,t.isMissing)(o))return null;let s=r[e],c=s?.stepFunction?.functionName,l=s?.stepFunction?.version,u=s&&`iterator`in s&&n.intermediateSteps?.[e]?Object.keys(n.intermediateSteps[e]).length:void 0,d=typeof o.output?.statusCode==`number`?o.output.statusCode:void 0;return{input:{actionRunId:y.actionRunId,actionMode:y.mode,actionSuccess:x.success,stepIndex:a,stepId:e,organizationId:i,projectSecureId:v.projectSecureId,accountSecureId:v.accountSecureId,inputs:n.inputs,...c&&{stepFunctionName:c},...l&&{stepFunctionVersion:l},...u!==void 0&&{stepIterations:u},startTime:o.statistics?.startTime},result:{success:o.successful,statusCode:d,message:o.message,outputs:o.output,errors:o.errors,skipped:o.skipped,endTime:o.statistics?.endTime}}}).filter(t.notMissing);a.length>0&&await g.recordSteps(a,_)}catch(e){p?.warning({message:`Failed to record action result: ${e.message}`,error:e})}},Xe={action_id:`action`,path:`action`,test_actions:`test_action`,refresh_authentication:`refresh_authentication`},buildTier2Config=e=>{let t={};return e?.highRiskThreshold!==void 0&&(t.highRiskThreshold=e.highRiskThreshold),e?.mediumRiskThreshold!==void 0&&(t.mediumRiskThreshold=e.mediumRiskThreshold),e?.multiheadEnabled&&(t.multihead={mainThreshold:.64,auxThreshold:.458}),Object.keys(t).length>0?{tier2Config:t}:{}},recordingFieldsFromParams=e=>({mode:e.mode,organizationId:e.account.organizationId,pathParams:e.pathParams,queryParams:e.queryParams,body:e.body,headers:e.headers,source:e.source,settings:e.settings,logger:e.logger}),applyDefenderToBlock=async(e,n,r,i)=>{if(!r?.defender?.enabled)return e;let{defenderMetadata:a,outputs:o,response:s}=await n({outputs:e.outputs,streamOutput:`streamOutput`in e?e.streamOutput:void 0,toolName:e.action?.id??e.context?.connectorKey??``,sourceType:e.context?.sourceType,settings:r,logger:i});return{...e,defenderMetadata:a,...(0,t.notMissing)(o)&&{outputs:o},...(0,t.notMissing)(s)&&{response:s}}};let Ze;const sharedRedactor=()=>Ze??=(0,d.createPiiRedaction)({enableTier2:!0}),applyRedactionToBlock=async(e,t,n)=>{if(!t||`streamOutput`in e&&e.streamOutput)return{block:e,redactedClasses:[]};let r=!1;try{if(!(typeof e.outputs==`string`&&e.outputs.length>0||fieldPathsOf(e.outputs).paths.length>0))return{block:e,redactedClasses:[]};let i=(await decideRedactionClasses({policy:t.policy,account:t.account,action:t.action,...t.authType&&{authType:t.authType},...t.sessionId&&{sessionId:t.sessionId},logger:n})).classes.filter(e=>e.decision===`deny`);if(i.length===0)return{block:e,redactedClasses:[]};r=!0;let a=i.filter(e=>e.faulted);a.length>0&&n?.error({code:`PolicyRedactionFaulted`,message:`PII redaction decision faulted; redacting ${a.length} class(es) to fail safe: ${a.map(e=>e.class).join(`, `)}`,category:`runAction`});let o=modelLabelsForClasses(i.map(e=>e.class)),{value:s,appliedLabels:c,modelAvailable:l,skipped:u}=await(0,d.scrubObjectDetailedAsync)(e.outputs,sharedRedactor(),o,n),f=i.filter(e=>classWasApplied(e.class,c)),p=u===`oversized`?i:l?[]:i.filter(e=>!f.includes(e)&&(0,d.labelledPatternsFor)(modelLabelsForClasses([e.class]),sharedRedactor().getConfig().entropy.piiPatterns).length===0);if(p.length>0){let e=p.map(e=>e.class).join(`, `);n?.error(u===`oversized`?{code:`PolicyRedactionOversized`,message:`PII redaction skipped: response exceeds the redaction size limit; ${p.length} forbidden class(es) not redacted: ${e}`,category:`runAction`}:{code:`PolicyRedactionUnavailable`,message:`PII redaction model unavailable; ${p.length} forbidden class(es) not redacted: ${e}`,category:`runAction`})}let m=p.length>0||a.length>0;return f.length===0?{block:e,redactedClasses:[],...m&&{degraded:!0}}:{block:{...e,outputs:s},redactedClasses:f.map(e=>({class:e.class,policyIds:e.deniedBy?.policyIds??[],...e.deniedBy?.level&&{level:e.deniedBy.level}})),...m&&{degraded:!0}}}catch(t){return n?.error({code:`PolicyRedactionFailed`,message:`PII redaction failed, response returned unredacted: ${t instanceof Error?t.message:String(t)}`,category:`runAction`}),{block:e,redactedClasses:[],...r&&{degraded:!0}}}},isEnabledTestAction=(e,n,r)=>(0,t.isMissing)(r)||e.isInline||r.has(n.id),runAction=async e=>{let{pathParams:n={},queryParams:r={},body:i={},headers:a={},decideInvokeToolFn:o=decideInvokeTool,decideReadFieldsFn:s=decideReadFields,parseConnector:l=parseYamlConnector,parseActionInputsFn:u=parseActionInputs,createBlockContextFn:d=createBlockContext,createBlockFn:f=createBlock,runStepActionFn:p=runStepAction,getActionFromUrlFn:m=getActionFromUrl,getActionForRefreshAuthenticationFn:h=getActionForRefreshAuthentication,getTestActionsFn:g=getTestActions,applyDefenderFn:_=applyDefender,applyRedactionFn:v=applyRedactionToBlock,mode:y,account:b,connector:x,getHttpClient:S,getOlapClient:C,settings:w,source:T,user:E,policy:D,logger:O,category:k,...A}=e,j=normalizeActingUser(E),M=withActingUser(D,j),N=b.authConfigKey,P=b.environment??`production`,F=b.secureId,ee=b.projectSecureId,I=b.organizationId,L=b.credentials,R=b.originOwnerId,z=b.originOwnerName,B=d({category:k??`action`,connectorKey:b.providerKey,connectorVersion:b.providerVersion,connectorOwner:b.connectorOwner,connectorProfileId:b.connectorProfileId,authConfigKey:N,environment:P,accountSecureId:F,projectSecureId:ee,organizationId:I,originOwnerId:R,originOwnerName:z,sourceType:T?.sourceType,authType:T?.authType,authId:T?.authId,sessionId:T?.sessionId,agentId:T?.agentId,userAgent:T?.userAgent,ipAddress:T?.ipAddress,transportType:T?.transportType,streamType:T?.streamType,flowType:Xe[y],sourceId:T?.sourceId,sourceValue:T?.sourceValue}),V=new Date,H;try{H=(0,t.isString)(x)?l(x):x}catch{throw new ConnectorParseError(B,`Error while parsing connector`)}let U={connector:H,context:B,user:j,credentials:L,settings:w,logger:O,getHttpClient:S,getOlapClient:C};if(y===`action_id`){let{actionId:c}=A,l=findActionByActionId(H,c);if((0,t.isMissing)(l))throw new MissingActionError(B,`No matching action found`);return validateAuthTypeCompatibility(l,N,B),await runAndRecord({action:l,execute:{action:l,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:n,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else if(y===`test_actions`){let{enabledActions:n}=A,r=g(H,N,P);if((0,t.isMissing)(r)||r.length===0)return await createSuccessBlock(f,U);B.actionType=`test`;let i=(0,t.notMissing)(n)&&!n.allEnabled?new Set(n.actionIds):void 0,a=0;for(let n of r){let{action:r}=n;if((0,t.isString)(r))throw new MissingActionError(B,`Test action "${r}" does not resolve to an action`);if(!isEnabledTestAction(n,r,i))continue;let o=new Date,s=await f({...U,inputs:void 0,action:r,nextCursor:void 0});if(!(!(0,t.notMissing)(n.condition)||(0,c.evaluate)(n.condition,s)))continue;validateActingUser(r,j,B),a++;let l=await p({block:s});if(l=await applyDefenderToBlock(l,_,w,O),(0,t.notMissing)(l?.response?.successful)&&l.response.successful){l.statistics={startTime:o,endTime:new Date},await recordActionResult({action:r,resultBlock:l,...recordingFieldsFromParams(e)});let t=await createSuccessBlock(f,U);return t.statistics={startTime:V,endTime:new Date},t}O?.error({code:`TestActionFailed`,message:`Test action "${r.id}" failed with error: ${l?.response?.message}`}),l.statistics={startTime:o,endTime:new Date},await recordActionResult({action:r,resultBlock:l,...recordingFieldsFromParams(e)})}if(a>0){let e=await createErrorBlock(f,U);return e.statistics={startTime:V,endTime:new Date},e}let o=await createSuccessBlock(f,U);return o.statistics={startTime:V,endTime:new Date},o}else if(y===`refresh_authentication`){let{redirectUri:n}=A;B.redirectUri=n;let c=h(H,N,P);if((0,t.isMissing)(c))throw new MissingActionError(B,`No matching action found`);return await runAndRecord({action:c.action,execute:{action:c.action,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:c.params,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else if(y===`path`){let{path:n,method:c}=A,l=m(H,n,c);if((0,t.isMissing)(l))throw new MissingActionError(B,`No matching action found`);return validateAuthTypeCompatibility(l.action,N,B),await runAndRecord({action:l.action,execute:{action:l.action,blockContext:B,account:b,policy:M,logger:O,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:r,pathParams:l.params,body:i,headers:a,parseActionInputsFn:u,createBlockFn:f,createBlockParams:U,runStepActionFn:p},startTime:V,applyDefenderFn:_,applyRedactionFn:v,settings:w,logger:O,recording:recordingFieldsFromParams(e)})}else return await createErrorBlock(f,U)},refusalStatus=e=>isPolicyErrorType(e.errorType)?Q[e.errorType]:e instanceof ActingUserRequiredError||e instanceof UserScopeViolationError?403:void 0,runAndRecord=async e=>{let t=await executeAction(e.execute);if(t.outcome===`refused`)return recordRefusal(e,t.error,t.policy);let n=applyUserScope(t.block,e.action,e.execute.createBlockParams.user);if(n.outcome===`violated`)return recordRefusal(e,new UserScopeViolationError(e.execute.blockContext,`Action '${e.action.id}' ${n.message}`),t.policy);n.omitted>0&&e.logger?.warning({code:`UserScopeOmittedRecords`,message:`Action '${e.action.id}' omitted ${n.omitted} record(s) that do not belong to the acting user; the provider filter did not scope the response`,category:`runAction`});let{block:r,maskedFields:i,observedFields:a,degraded:o}=await applyPolicyMask({...t,block:n.block},e.logger),s=await applyDefenderToBlock(r,e.applyDefenderFn,e.settings,e.logger),{block:c,redactedClasses:l,degraded:u=!1}=await e.applyRedactionFn(s,t.readFields,e.logger);c.statistics={startTime:e.startTime,endTime:new Date};let d=t.readFields&&(i.length>0||l.length>0||u||a.length>0)?toPolicyContext(t.readFields.decision,t.readFields.call,{maskedFields:i,degraded:o||u,redactedClasses:l,observedFields:a}):t.policy;return(d?.maskedFields?.length||l.length||u)&&(c.policyMetadata={result:d?.result===`error`?`error`:`partial`,maskedFields:(d?.maskedFields??[]).map(e=>({...e})),...l.length>0&&{redactedClasses:l.map(e=>({...e}))},policies:(d?.policies??[]).map(e=>({...e}))}),await recordActionResult({action:e.action,resultBlock:c,...d&&{policyContext:d},...e.recording}),withoutStepOutputs(c,e.action)},recordRefusal=async(e,t,n)=>{let r=await createErrorBlock(e.execute.createBlockFn,e.execute.createBlockParams,refusalStatus(t));r.statistics={startTime:e.startTime,endTime:new Date};let i=describeRefusal(t);throw await recordActionResult({action:e.action,resultBlock:r,...n&&{policyContext:n},...i&&{refusal:i},...e.recording}),i?Object.assign(t,{refusal:i}):t},observedFieldsOf=e=>e.filter(e=>e.decision!==`deny`).flatMap(e=>{let t=e.observed.filter(e=>e.decision===`deny`&&e.faulted!==!0),[n]=t;return n?[{path:e.path,policyIds:[...new Set(t.flatMap(e=>e.policyIds))],level:n.level}]:[]}),applyPolicyMask=async(e,t)=>{let n=e.readFields;if(!n)return{block:e.block,maskedFields:[],observedFields:[],degraded:!1};try{let{paths:r,truncated:i,valueTypes:a,neighbours:o,identifierPaths:s}=fieldPathsOf(e.block.outputs);if(r.length===0)return{block:e.block,maskedFields:[],observedFields:[],degraded:!1};let c=await(n.decideReadFieldsFn??decideReadFields)({policy:n.policy,account:n.account,action:n.action,paths:r,valueTypes:a,neighbours:o,identifierPaths:s,...n.authType&&{authType:n.authType},...n.sessionId&&{sessionId:n.sessionId},logger:t}),l=c.fields.filter(e=>e.decision===`deny`),u=observedFieldsOf(c.fields),d=i?new Set(c.fields.filter(e=>e.decision===`allow`&&!e.faulted).map(e=>e.path)):void 0;if(l.length===0&&!i)return{block:e.block,maskedFields:[],observedFields:u,degraded:!1};let{payload:f,masked:p}=maskFields(e.block.outputs,l.map(e=>e.path),d),m=new Map(l.map(e=>[e.path,e]));return{block:{...e.block,outputs:f},maskedFields:p.map(e=>({path:e,policyIds:m.get(e)?.deniedBy?.policyIds??[],...m.get(e)?.deniedBy?.level&&{level:m.get(e)?.deniedBy?.level}})),observedFields:u,degraded:i||l.some(e=>e.faulted)}}catch(n){t?.error({code:`PolicyMaskFailed`,message:`Field masking failed, response withheld: ${n instanceof Error?n.message:String(n)}`,category:`runAction`});let{payload:r,masked:i}=maskFields(e.block.outputs,[],new Set);return{block:{...e.block,outputs:r},maskedFields:i.map(e=>({path:e,policyIds:[]})),observedFields:[],degraded:!0}}},executeAction=async e=>{let{action:t,blockContext:n,account:r,policy:i,logger:a,decideInvokeToolFn:o,decideReadFieldsFn:s,queryParams:c,pathParams:l,body:u,headers:d,parseActionInputsFn:f,createBlockFn:p,createBlockParams:m,runStepActionFn:h}=e;n.actionType=t.actionType,n.schema=t.schema?.key;let g=processCursor(c,n),_;try{_=f(t,{path:l,query:c,body:u,headers:d})}catch(e){throw typeof e==`object`&&e&&`issues`in e&&Array.isArray(e.issues)?new InvalidActionInputsError(n,`Invalid input values provided`,e.issues.map(e=>{let t=e.path.map(String),n=t[0]||`body`;return{field:t.slice(1).join(`.`)||t[0]||`unknown`,location:n,expected:`expected`in e?String(e.expected):e.code,received:`received`in e?String(e.received):`unknown`,message:e.message}})):new InvalidActionInputsError(n,`Error while parsing action inputs`)}let v=actingUserRefusal(t,m.user,n);if(v)return{outcome:`refused`,error:v};let y=await enforceInvokeTool({action:t,blockContext:n,account:r,policy:i,logger:a,decideInvokeToolFn:o});return y.permitted?{outcome:`ran`,block:await h({block:await p({...m,inputs:_,action:t,nextCursor:g})}),...y.policy&&{policy:y.policy},...y.readFields&&{readFields:{...y.readFields,decideReadFieldsFn:s}}}:{outcome:`refused`,policy:y.policy,error:y.error}},enforceInvokeTool=async e=>{let n=e.policy;if((0,t.isMissing)(n)||e.blockContext.flowType!==`action`)return{permitted:!0};let r={actionRunId:e.blockContext.actionRunId??`missing`,actionId:e.action.id,accountSecureId:e.account.secureId,...n.principal&&{principal:n.principal},levels:n.levels},i=await decideOrName(e,n);if(`preparse`in i)return{permitted:!1,policy:preparseFailureContext(r),error:i.preparse};let a=i.decision,o=toPolicyContext(a,r);if(a.decision===`allow`)return{permitted:!0,policy:o,readFields:{decision:a,call:r,policy:n,account:e.account,action:e.action,...e.blockContext.authType&&{authType:e.blockContext.authType},...e.blockContext.sessionId&&{sessionId:e.blockContext.sessionId}}};let s=n.toolName??e.action.id,c=a.deniedBy?.level??`org`;return{permitted:!1,policy:o,error:a.faulted?new PolicyEvaluationError(e.blockContext,{level:c},`Could not evaluate ${c} policy for action '${s}'`):new PolicyDeniedError(e.blockContext,{level:c,policyIds:a.deniedBy?.policyIds??[]},`Action '${s}' is not permitted by ${c} policy`)}},decideOrName=async(e,t)=>{try{return{decision:await e.decideInvokeToolFn({policy:t,account:e.account,action:e.action,authType:e.blockContext.authType,sessionId:e.blockContext.sessionId,logger:e.logger})}}catch(t){if(t instanceof l.PolicyPreparseError)return{preparse:new PolicyPreparseError(e.blockContext,t.message)};throw t}},createSuccessBlock=async(e,t)=>({...await e({...t,inputs:void 0,action:void 0,nextCursor:void 0}),response:{successful:!0,statusCode:200}}),createErrorBlock=async(e,t,n=500)=>({...await e({...t,inputs:void 0,action:void 0,nextCursor:void 0}),response:{successful:!1,statusCode:n}}),processCursor=(e,n)=>{let r=e?.next,i=(0,t.notMissing)(r)&&n.actionType===`list`?(0,s.expandCursor)(r):void 0;if(i===null)throw new InvalidCursorError(n,`Invalid cursor.`);return i},applyDefender=async({outputs:e,streamOutput:t,toolName:n,sourceType:r,settings:i,logger:a})=>{if(t)return{defenderMetadata:{applied:!1,skipped:{reason:`streaming`}}};let o=shouldSkipDefender(e,i?.defender);if(o.skip)return{defenderMetadata:{applied:!1,skipped:{reason:o.reason,estimatedSize:o.size?.bytes,threshold:i?.defender?.maxResponseSize}}};if(i?.defender?.largeResponseBehavior===`block`&&o.size&&(o.size.bytes>(i.defender.maxResponseSize??1048576)||o.size.words>(i.defender.maxResponseWords??1e4)))return{defenderMetadata:{applied:!1,skipped:{reason:`size_limit`,estimatedSize:o.size.bytes,threshold:i.defender.maxResponseSize}},response:{successful:!1,statusCode:413,message:`Response too large for security scanning`}};try{let t=await(0,u.createPromptDefense)({blockHighRisk:i?.defender?.blockHighRisk??!1,enableTier1:i?.defender?.useTier1Classification??!0,enableTier2:i?.defender?.useTier2Classification??!0,useSfe:i?.defender?.useSfe??!0,tier2Fields:i?.defender?.tier2Fields,annotateBoundary:i?.defender?.annotateBoundary??!1,sanitizeContent:i?.defender?.sanitizeContent??!0,enableTier3:i?.defender?.useTier3Classification??!1,defenderMode:i?.defender?.defenderMode??`cascade`,...buildTier2Config(i?.defender)}).defendToolResult(e,n),o=t.tier3,s=o===void 0?{}:o.decision===`block`||o.decision===`allow`?{tier3Decision:o.decision,tier3LatencyMs:o.latencyMs,...o.usage&&{tier3PromptTokens:o.usage.promptTokens,tier3CompletionTokens:o.usage.completionTokens}}:{tier3SkipReason:o.skipReason};return a?.info({message:`Defender applied`,context:{tool:n,sourceType:r,riskLevel:t.riskLevel,allowed:t.allowed,fieldsSanitized:t.fieldsSanitized.length,detectedFieldCount:t.detectedFieldCount,detections:t.detections,tier2Score:t.tier2Score,tier2SkipReason:t.tier2SkipReason,tier2Available:t.tier2Available,coverageDegraded:t.coverageDegraded,latencyMs:t.latencyMs,tier1Ms:t.tier1Ms,coldLoad:t.coldLoad,tier2Stats:t.tier2Stats,phaseTimings:t.phaseTimings,...s}}),{defenderMetadata:{applied:!0,result:{allowed:t.allowed,riskLevel:t.riskLevel,fieldsSanitized:t.fieldsSanitized,patternsByField:t.patternsByField,detections:t.detections,tier2Score:t.tier2Score,tier2RawScore:t.tier2RawScore,tier2AuxScore:t.tier2AuxScore,tier2MultiheadBlocked:t.tier2MultiheadBlocked,tier2SkipReason:t.tier2SkipReason,tier3:t.tier3,latencyMs:t.latencyMs,...s}},outputs:t.sanitized,...!t.allowed&&{response:{successful:!1,statusCode:403,message:`Tool result blocked by security policy`}}}}catch(e){return a?.error({code:`DefenderError`,message:`Defender failed: ${e.message}`,context:{tool:n}}),{defenderMetadata:{applied:!1,skipped:{reason:`error`,error:e.message}}}}},runConnectorActionById=async({actionId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},settings:s,source:c,logger:l,getHttpClient:u,getOlapClient:d,parseConnector:f=parseYamlConnector,parseActionInputsFn:p=parseActionInputs,createBlockContextFn:m=createBlockContext,createBlockFn:h=createBlock,runStepActionFn:g=runStepAction})=>runAction({mode:`action_id`,actionId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,settings:s,source:c,logger:l,getHttpClient:u,getOlapClient:d,parseConnector:f,parseActionInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepActionFn:g}),runConnectorActionByPath=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,settings:c,source:l,logger:u,getHttpClient:d,parseConnector:f=parseYamlConnector,getActionFromUrlFn:p=getActionFromUrl,getActionForRefreshAuthenticationFn:m=getActionForRefreshAuthentication,parseActionInputsFn:h=parseActionInputs,createBlockContextFn:g=createBlockContext,createBlockFn:_=createBlock,runStepActionFn:v=runStepAction})=>isRefreshTokenActionPath(r)?await runAction({mode:`refresh_authentication`,account:e,connector:t,settings:c,source:l,getActionForRefreshAuthenticationFn:m,parseConnector:f,logger:u,getHttpClient:d,parseActionInputsFn:h,createBlockContextFn:g,createBlockFn:_,runStepActionFn:v}):await runAction({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,settings:c,source:l,getActionFromUrlFn:p,parseConnector:f,logger:u,getHttpClient:d,parseActionInputsFn:h,createBlockContextFn:g,createBlockFn:_,runStepActionFn:v}),isRefreshTokenActionPath=e=>e===`stackone://internal//refresh_token`,runEventActionById=async({actionId:e,account:n,connector:r,body:i={},headers:a={},logger:o,getHttpClient:c,getOlapClient:l,emitEvent:u,getWebhookRemoteId:d,findActionFn:f=findEventActionByActionId,parseActionInputsFn:p=parseActionInputs,createBlockContextFn:m=createBlockContext,createBlockFn:h=createBlock,runStepActionFn:g=runStepAction})=>{let _=m({category:`action`,connectorKey:n.providerKey,connectorVersion:n.providerVersion,authConfigKey:n.authConfigKey,environment:n.environment??`production`,accountSecureId:n.secureId,projectSecureId:n.projectSecureId,organizationId:n.organizationId,originOwnerId:n.originOwnerId,originOwnerName:n.originOwnerName,connectorOwner:n.connectorOwner,flowType:`action`}),v=f(r,e);if((0,t.isMissing)(v))throw new MissingActionError(_,`No matching event action found`);_.actionType=`event`,_.schema=v.schema?.key,_.webhookRemoteId=await d?.();let y=p(v,{body:i,headers:a}),b=new Date,x=await h({connector:r,context:_,credentials:n.credentials,logger:o,getHttpClient:c,getOlapClient:l,emitEvent:u,inputs:y,action:v,nextCursor:void 0}),S={mode:`event`,organizationId:n.organizationId,body:i,headers:a,source:{sourceType:s.SourceType.Webhook},isBackground:!1,logger:o},C;try{C=await g({block:x})}catch(t){throw o?.error({code:`EventActionError`,message:`Event action "${e}" failed: ${t.message}`}),await recordActionResult({action:v,resultBlock:{...x,response:{successful:!1,statusCode:500,message:t.message},statistics:{startTime:b,endTime:new Date}},...S}),t}if(C.statistics={startTime:b,endTime:new Date},typeof C.outputs?.statusCode!=`number`)throw await recordActionResult({action:v,resultBlock:{...C,response:{successful:!1,statusCode:500,message:`Event action output must include a numeric statusCode`}},...S}),new InvalidEventOutputError(_,`Event action output must include a numeric statusCode`);return await recordActionResult({action:v,resultBlock:C,...S}),C},runTestActions=async({account:e,connector:t,settings:n,source:r,logger:i,getHttpClient:a,getOlapClient:o,enabledActions:s,parseConnector:c=parseYamlConnector,getTestActionsFn:l=getTestActions,createBlockContextFn:u=createBlockContext,createBlockFn:d=createBlock,runStepActionFn:f=runStepAction})=>(await runAction({mode:`test_actions`,account:e,connector:t,settings:n,source:r,logger:i,getHttpClient:a,getOlapClient:o,enabledActions:s,parseConnector:c,getTestActionsFn:l,createBlockContextFn:u,createBlockFn:d,runStepActionFn:f}))?.response?.successful??!1,phaseKindToActionType=e=>e===`deletion`?`delete`:`create`,phaseAsAction=(e,t)=>({id:`webhook-setup-${t}`,categories:[],label:`Webhook Setup ${t}`,description:`Webhook setup ${t} phase execution`,schemaType:`native`,actionType:phaseKindToActionType(t),steps:e.steps,result:e.result,responses:{success:{statusCode:200},errors:{}},cursor:{enabled:!1,pageSize:0},compositeIdentifiers:{enabled:!1}}),runWebhookSetupPhase=async({connector:e,phase:n,phaseKind:r,inputs:i,credentials:a,accountSecureId:o,projectSecureId:c,organizationId:l,originOwnerId:u,originOwnerName:d,connectorKey:f,connectorVersion:p,authConfigKey:m,environment:h,logger:g,getHttpClient:_,getOlapClient:v,createBlockFn:y=createBlock,createBlockContextFn:b=createBlockContext,runStepActionFn:x=runStepAction})=>{let S=e.categories?.[0];if((0,t.isMissing)(S))throw Error(`Connector category is required for webhook setup phase execution (connector '${f}')`);let C=phaseAsAction(n,r),w=b({category:S,connectorKey:f,connectorVersion:p,authConfigKey:m,environment:h,action:C,accountSecureId:o,projectSecureId:c,organizationId:l,originOwnerId:u,originOwnerName:d,flowType:`action`}),T=new Date,E=await y({connector:e,inputs:i,credentials:a,context:w,action:C,logger:g,getHttpClient:_,getOlapClient:v}),D={mode:`webhook_setup`,organizationId:l,body:i,source:{sourceType:s.SourceType.Internal},isBackground:!0,logger:g},O;try{O=await x({block:E})}catch(e){throw await recordActionResult({action:C,resultBlock:{...E,response:{successful:!1,statusCode:500,message:e.message},statistics:{startTime:T,endTime:new Date}},...D}),e}if(O.statistics={startTime:T,endTime:new Date},(0,t.isMissing)(O.response))throw await recordActionResult({action:C,resultBlock:{...O,response:{successful:!1,statusCode:500,message:`Webhook setup ${r} phase produced no response`}},...D}),Error(`Webhook setup ${r} phase produced no response (connector '${f}')`);return await recordActionResult({action:C,resultBlock:O,...D}),{successful:O.response.successful,statusCode:O.response.statusCode,outputs:O.outputs}};exports.ACTION_SCHEMA=W,exports.ActingUserRequiredError=ActingUserRequiredError,exports.CATEGORY_ACRONYMS=p,exports.CONNECTOR_YAML_SCHEMA=xe,exports.ConnectSDKError=Z,exports.DEFAULT_TIME_FILTER_SAFETY_BUFFER_SECONDS=60,exports.DELTA_TOKEN_INCREMENTAL_SCHEMA=b,exports.INCREMENTAL_SCHEMA=S,exports.IncompatibleAuthTypeError=IncompatibleAuthTypeError,exports.InvalidActionInputsError=InvalidActionInputsError,exports.InvalidEventOutputError=InvalidEventOutputError,exports.MAX_FIELD_PATHS=250,exports.POLICY_ERROR_STATUS=Q,exports.PolicyDeniedError=PolicyDeniedError,exports.PolicyEvaluationError=PolicyEvaluationError,exports.PolicyPreparseError=PolicyPreparseError,exports.TIME_FILTER_INCREMENTAL_SCHEMA=x,exports.UserScopeViolationError=UserScopeViolationError,exports.addMcpToolActions=addMcpToolActions,exports.applyDefender=applyDefender,exports.applyReleaseStageResolutionToMeta=applyReleaseStageResolutionToMeta,exports.applyReleaseStageToConnector=applyReleaseStageToConnector,exports.buildReleaseStageProfile=buildReleaseStageProfile,exports.completeMcpConnector=completeMcpConnector,exports.computeCredentialsVerifiedByAuth=computeCredentialsVerifiedByAuth,exports.countReleaseStageProfile=countReleaseStageProfile,exports.createBlock=createBlock,exports.createCursorPaginator=createCursorPaginator,exports.createDeltaTokenStrategy=createDeltaTokenStrategy,exports.createIncrementalStrategy=createIncrementalStrategy,exports.createLabellingDecideReadFields=createLabellingDecideReadFields,exports.createOffsetPaginator=createOffsetPaginator,exports.createPagePaginator=createPagePaginator,exports.createPaginator=createPaginator,exports.createTimeFilterStrategy=createTimeFilterStrategy,exports.decideInvokeTool=decideInvokeTool,exports.decideReadFields=decideReadFields,exports.definitionVersionOf=definitionVersionOf,exports.evaluateExternalAccountIdExtractorByConnector=evaluateExternalAccountIdExtractorByConnector,exports.executeStepFunction=executeStepFunction,exports.extractItems=extractItems,exports.fieldPathsOf=fieldPathsOf,exports.filterActionsByAuthType=filterActionsByAuthType,exports.formatValidationErrorResponse=formatValidationErrorResponse,exports.generateMcpConnector=generateMcpConnector,exports.getActionAuthenticationMethods=getActionAuthenticationMethods,exports.getActionFromUrl=getActionFromUrl,exports.getActionMeta=getActionMeta,exports.getActionsMeta=getActionsMeta,exports.getActionsMetaFromConnectors=getActionsMetaFromConnectors,exports.getActionsMetaSummary=getActionsMetaSummary,exports.getActionsMetaSummaryFromConnectors=getActionsMetaSummaryFromConnectors,exports.getRefreshTokenExpiresIn=getRefreshTokenExpiresIn,exports.getTokenExpiresIn=getTokenExpiresIn,exports.hasCatastrophicBacktrackingRisk=hasCatastrophicBacktrackingRisk,exports.isConnectorReleased=isConnectorReleased,exports.isMcpConnector=isMcpConnector,exports.isPolicyErrorType=isPolicyErrorType,exports.labelKeyOf=labelKeyOf,exports.labelsReferencedBy=labelsReferencedBy,exports.loadConnector=loadConnector,exports.maskFields=maskFields,exports.paginate=paginate,exports.parseActionInputs=parseActionInputs,exports.parseYamlConnector=parseYamlConnector,exports.providerRequestsOf=providerRequestsOf,exports.refusalOf=refusalOf,exports.resolveReleaseStageCounts=resolveReleaseStageCounts,exports.resolveReleaseStageProfile=resolveReleaseStageProfile,exports.runAction=runAction,exports.runConnectorActionById=runConnectorActionById,exports.runConnectorActionByPath=runConnectorActionByPath,exports.runEventActionById=runEventActionById,exports.runStepAction=runStepAction,exports.runTestActions=runTestActions,exports.runWebhookSetupPhase=runWebhookSetupPhase,exports.supportsRefreshAuthentication=supportsRefreshAuthentication,exports.unlabelledAllowPolicyIdsOf=unlabelledAllowPolicyIdsOf,exports.validateYamlConnector=validateYamlConnector;
|