@prismatic-io/spectral 7.10.0 → 8.0.0-preview11

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.
Files changed (40) hide show
  1. package/dist/clients/http/index.d.ts +1 -1
  2. package/dist/clients/soap/index.d.ts +2 -0
  3. package/dist/clients/soap/index.js +18 -0
  4. package/dist/clients/soap/types.d.ts +71 -0
  5. package/dist/clients/soap/types.js +24 -0
  6. package/dist/clients/soap/utils.d.ts +12 -0
  7. package/dist/clients/soap/utils.js +191 -0
  8. package/dist/index.d.ts +41 -12
  9. package/dist/index.js +43 -1
  10. package/dist/serverTypes/convert.d.ts +2 -1
  11. package/dist/serverTypes/convert.js +250 -1
  12. package/dist/serverTypes/index.d.ts +27 -24
  13. package/dist/testing.d.ts +14 -9
  14. package/dist/testing.js +57 -49
  15. package/dist/types/ActionDefinition.d.ts +3 -3
  16. package/dist/types/ActionInputParameters.d.ts +14 -1
  17. package/dist/types/ActionPerformFunction.d.ts +12 -9
  18. package/dist/types/ComponentDefinition.d.ts +2 -2
  19. package/dist/types/{Customer.d.ts → CustomerAttributes.d.ts} +1 -1
  20. package/dist/types/DataSourcePerformFunction.d.ts +4 -4
  21. package/dist/types/{Flow.d.ts → FlowAttributes.d.ts} +1 -1
  22. package/dist/types/Inputs.d.ts +44 -50
  23. package/dist/types/{Instance.d.ts → InstanceAttributes.d.ts} +1 -1
  24. package/dist/types/{Integration.d.ts → IntegrationAttributes.d.ts} +2 -1
  25. package/dist/types/IntegrationDefinition.d.ts +273 -0
  26. package/dist/types/IntegrationDefinition.js +78 -0
  27. package/dist/types/TriggerDefinition.d.ts +5 -5
  28. package/dist/types/TriggerEventFunction.d.ts +2 -2
  29. package/dist/types/TriggerPayload.d.ts +6 -6
  30. package/dist/types/TriggerPerformFunction.d.ts +2 -2
  31. package/dist/types/TriggerResult.d.ts +4 -4
  32. package/dist/types/{User.d.ts → UserAttributes.d.ts} +1 -1
  33. package/dist/types/index.d.ts +6 -5
  34. package/dist/types/index.js +6 -5
  35. package/package.json +6 -4
  36. /package/dist/types/{Customer.js → CustomerAttributes.js} +0 -0
  37. /package/dist/types/{Flow.js → FlowAttributes.js} +0 -0
  38. /package/dist/types/{Instance.js → InstanceAttributes.js} +0 -0
  39. /package/dist/types/{Integration.js → IntegrationAttributes.js} +0 -0
  40. /package/dist/types/{User.js → UserAttributes.js} +0 -0
@@ -10,8 +10,13 @@ var __rest = (this && this.__rest) || function (s, e) {
10
10
  }
11
11
  return t;
12
12
  };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
13
16
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.convertComponent = void 0;
17
+ exports.convertIntegration = exports.convertComponent = void 0;
18
+ const yaml_1 = __importDefault(require("yaml"));
19
+ const uuid_1 = require("uuid");
15
20
  const types_1 = require("../types");
16
21
  const perform_1 = require("./perform");
17
22
  const convertInput = (key, _a) => {
@@ -77,3 +82,247 @@ const convertComponent = (_a) => {
77
82
  return Object.assign(Object.assign({}, definition), { connections: connections.map(convertConnection), actions: convertedActions, triggers: convertedTriggers, dataSources: convertedDataSources });
78
83
  };
79
84
  exports.convertComponent = convertComponent;
85
+ const convertIntegration = (definition) => {
86
+ // Generate a unique reference key that will be used to reference the
87
+ // actions, triggers, data sources, and connections that are created
88
+ // inline as part of the integration definition.
89
+ const referenceKey = (0, uuid_1.v4)();
90
+ return Object.assign(Object.assign({}, codeNativeIntegrationComponent(definition, referenceKey)), { codeNativeIntegrationYAML: codeNativeIntegrationYaml(definition, referenceKey) });
91
+ };
92
+ exports.convertIntegration = convertIntegration;
93
+ const codeNativeIntegrationYaml = ({ name, description, category, documentation, version, labels, configVars, endpointType, triggerPreprocessFlowConfig, flows, configPages, }, referenceKey) => {
94
+ const DEFINITION_VERSION = 7;
95
+ // Find the preprocess flow config on the flow, if one exists.
96
+ const preprocessFlows = flows.filter((flow) => flow.preprocessFlowConfig);
97
+ // Do some validation of preprocess flow configs.
98
+ if (preprocessFlows.length > 1) {
99
+ throw new Error("Only one flow may define a Preprocess Flow Config.");
100
+ }
101
+ if (preprocessFlows.length && triggerPreprocessFlowConfig) {
102
+ throw new Error("Integration must not define both a Trigger Preprocess Flow Config and a Preprocess Flow.");
103
+ }
104
+ const hasPreprocessFlow = preprocessFlows.length > 0;
105
+ const preprocessFlowConfig = hasPreprocessFlow
106
+ ? preprocessFlows[0].preprocessFlowConfig
107
+ : triggerPreprocessFlowConfig;
108
+ if ([types_1.EndpointType.InstanceSpecific, types_1.EndpointType.SharedInstance].includes(endpointType || types_1.EndpointType.FlowSpecific) &&
109
+ !preprocessFlowConfig) {
110
+ throw new Error("Integration with specified EndpointType must define either a Trigger Preprocess Flow Config or a Preprocess Flow.");
111
+ }
112
+ // Transform the IntegrationDefinition into the structure that is appropriate
113
+ // for generating YAML, which will then be used by the Prismatic API to import
114
+ // the integration as a Code Native Integration.
115
+ const result = {
116
+ definitionVersion: DEFINITION_VERSION,
117
+ isCodeNative: true,
118
+ name,
119
+ description,
120
+ category,
121
+ documentation,
122
+ version,
123
+ labels,
124
+ requiredConfigVars: Object.entries(configVars || {}).map(([key, configVar]) => convertConfigVar(Object.assign(Object.assign({}, configVar), { key }), referenceKey)),
125
+ endpointType,
126
+ preprocessFlowName: hasPreprocessFlow ? preprocessFlows[0].name : undefined,
127
+ externalCustomerIdField: fieldNameToReferenceInput(hasPreprocessFlow ? "onExecution" : "payload", preprocessFlowConfig === null || preprocessFlowConfig === void 0 ? void 0 : preprocessFlowConfig.externalCustomerIdField),
128
+ externalCustomerUserIdField: fieldNameToReferenceInput(hasPreprocessFlow ? "onExecution" : "payload", preprocessFlowConfig === null || preprocessFlowConfig === void 0 ? void 0 : preprocessFlowConfig.externalCustomerUserIdField),
129
+ flowNameField: fieldNameToReferenceInput(hasPreprocessFlow ? "onExecution" : "payload", preprocessFlowConfig === null || preprocessFlowConfig === void 0 ? void 0 : preprocessFlowConfig.flowNameField),
130
+ flows: flows.map((flow) => convertFlow(flow, referenceKey)),
131
+ configPages,
132
+ };
133
+ return yaml_1.default.stringify(result);
134
+ };
135
+ /** Converts a Flow into the structure necessary for YAML generation. */
136
+ const convertFlow = (flow, referenceKey) => {
137
+ const result = Object.assign({}, flow);
138
+ delete result.onTrigger;
139
+ delete result.trigger;
140
+ delete result.onInstanceDeploy;
141
+ delete result.onInstanceDelete;
142
+ delete result.onExecution;
143
+ delete result.preprocessFlowConfig;
144
+ delete result.errorConfig;
145
+ const triggerStep = {
146
+ name: "On Trigger",
147
+ stableKey: `${flow.stableKey}-onTrigger`,
148
+ description: "The function that will be executed by the flow to return an HTTP response.",
149
+ isTrigger: true,
150
+ errorConfig: "errorConfig" in flow ? Object.assign({}, flow.errorConfig) : undefined,
151
+ action: {
152
+ key: flowFunctionKey(flow.name, "onTrigger"),
153
+ component: { key: referenceKey, version: "LATEST", isPublic: false },
154
+ },
155
+ };
156
+ if ("schedule" in flow && typeof flow.schedule === "object") {
157
+ triggerStep.schedule = {
158
+ type: "cronExpression" in flow.schedule
159
+ ? types_1.SimpleInputValueType.Value
160
+ : types_1.SimpleInputValueType.ConfigVar,
161
+ value: "cronExpression" in flow.schedule
162
+ ? flow.schedule.cronExpression
163
+ : flow.schedule.configVarKey,
164
+ meta: {
165
+ scheduleType: types_1.ScheduleType.Custom,
166
+ timeZone: flow.schedule.timeZone,
167
+ },
168
+ };
169
+ delete result.schedule;
170
+ }
171
+ const actionStep = {
172
+ action: {
173
+ key: flowFunctionKey(flow.name, "onExecution"),
174
+ component: { key: referenceKey, version: "LATEST", isPublic: false },
175
+ },
176
+ name: "On Execution",
177
+ stableKey: `${flow.stableKey}-onExecution`,
178
+ description: "The function that will be executed by the flow.",
179
+ errorConfig: "errorConfig" in flow ? Object.assign({}, flow.errorConfig) : undefined,
180
+ };
181
+ result.steps = [triggerStep, actionStep];
182
+ return result;
183
+ };
184
+ /** Converts a Config Var into the structure necessary for YAML generation. */
185
+ const convertConfigVar = (configVar, referenceKey) => {
186
+ // This is unfortunate but we need to strip out some fields that are not
187
+ // relevant to config vars.
188
+ const fields = [
189
+ "key",
190
+ "stableKey",
191
+ "description",
192
+ "orgOnly",
193
+ "inputs",
194
+ "defaultValue",
195
+ "dataType",
196
+ "pickList",
197
+ "scheduleType",
198
+ "timeZone",
199
+ "codeLanguage",
200
+ "collectionType",
201
+ "dataSource",
202
+ ];
203
+ const result = Object.entries(configVar).reduce((result, [key, value]) => {
204
+ if (!fields.includes(key)) {
205
+ return result;
206
+ }
207
+ return Object.assign(Object.assign({}, result), { [key]: value });
208
+ }, { meta: {} });
209
+ // Handle some non-standard fields.
210
+ if ("visibleToOrgDeployer" in configVar) {
211
+ result.meta.visibleToOrgDeployer = configVar.visibleToOrgDeployer;
212
+ }
213
+ if ("visibleToCustomerDeployer" in configVar) {
214
+ result.meta.visibleToCustomerDeployer = configVar.visibleToCustomerDeployer;
215
+ }
216
+ // Handle connections.
217
+ if ("label" in configVar) {
218
+ result.dataType = "connection";
219
+ // This refers to a connection we are creating.
220
+ result.connection = {
221
+ key: configVar.key,
222
+ component: { key: referenceKey, version: "LATEST", isPublic: false },
223
+ };
224
+ result.description = configVar.label;
225
+ // Convert connection inputs to the inputs expected in the YAML.
226
+ // FIXME: This is just a placeholder for now.
227
+ // TODO: It seems like using the default value as the value is probably correct?
228
+ result.inputs = Object.entries(configVar.inputs).reduce((result, [key, input]) => {
229
+ var _a;
230
+ return Object.assign(Object.assign({}, result), { [key]: {
231
+ type: types_1.SimpleInputValueType.Value,
232
+ value: (_a = input.default) !== null && _a !== void 0 ? _a : "",
233
+ } });
234
+ }, {});
235
+ }
236
+ // Handle data source references.
237
+ if ("dataSource" in result) {
238
+ // This is a reference to a data source we are creating.
239
+ result.dataSource = {
240
+ key: result.dataSource,
241
+ component: { key: referenceKey, version: "LATEST", isPublic: false },
242
+ };
243
+ }
244
+ return result;
245
+ };
246
+ /** Maps the step name field to a fully qualified input. */
247
+ const fieldNameToReferenceInput = (stepName, fieldName) => {
248
+ if (!fieldName) {
249
+ return undefined;
250
+ }
251
+ return {
252
+ type: types_1.SimpleInputValueType.Reference,
253
+ value: `${stepName}.results.${fieldName}`,
254
+ };
255
+ };
256
+ /** Actions and Triggers will be scoped to their flow by combining the flow
257
+ * name and the function name. This is to ensure that the keys are unique
258
+ * on the resulting object, which will be turned into a Component. */
259
+ const flowFunctionKey = (flowName, functionName) => {
260
+ const flowKey = flowName
261
+ .replace(/[^0-9a-zA-Z]+/g, " ")
262
+ .trim()
263
+ .split(" ")
264
+ .map((w, i) => i === 0
265
+ ? w.toLowerCase()
266
+ : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
267
+ .join("");
268
+ return `${flowKey}_${functionName}`;
269
+ };
270
+ /** Creates the structure necessary to import a Component as part of a
271
+ * Code Native integration. */
272
+ const codeNativeIntegrationComponent = ({ name, iconPath, description, flows = [], dataSources = {}, configVars = {}, }, referenceKey) => {
273
+ const convertedActions = flows.reduce((result, { name, onExecution }) => {
274
+ const actionKey = flowFunctionKey(name, "onExecution");
275
+ return Object.assign(Object.assign({}, result), { [actionKey]: convertAction(actionKey, {
276
+ display: {
277
+ label: `${name} - onExecution`,
278
+ description: "The function that will be executed by the flow.",
279
+ },
280
+ perform: onExecution,
281
+ inputs: {},
282
+ }) });
283
+ }, {});
284
+ const convertedTriggers = flows.reduce((result, flow) => {
285
+ // Filter out TriggerReferences.
286
+ if ("trigger" in flow)
287
+ return result;
288
+ const { name, onTrigger, onInstanceDeploy, onInstanceDelete } = flow;
289
+ const triggerKey = flowFunctionKey(name, "onTrigger");
290
+ return Object.assign(Object.assign({}, result), { [triggerKey]: convertTrigger(triggerKey, {
291
+ display: {
292
+ label: `${name} - onTrigger`,
293
+ description: "The function that will be executed by the flow to return an HTTP response.",
294
+ },
295
+ perform: onTrigger,
296
+ onInstanceDeploy: onInstanceDeploy,
297
+ onInstanceDelete: onInstanceDelete,
298
+ inputs: {},
299
+ scheduleSupport: "valid",
300
+ synchronousResponseSupport: "valid",
301
+ }) });
302
+ }, {});
303
+ const convertedDataSources = Object.entries(dataSources).reduce((result, [dataSourceKey, dataSource]) => (Object.assign(Object.assign({}, result), { [dataSourceKey]: convertDataSource(dataSourceKey, Object.assign(Object.assign({}, dataSource), { inputs: {} })) })), {});
304
+ const convertedConnections = Object.entries(configVars).reduce((result, [key, configVar]) => {
305
+ if (!("label" in configVar)) {
306
+ return result;
307
+ }
308
+ // Remove a few fields that are not relevant to connections.
309
+ const {
310
+ /* eslint-disable @typescript-eslint/no-unused-vars */
311
+ orgOnly, visibleToOrgDeployer, visibleToCustomerDeployer, stableKey } = configVar,
312
+ /* eslint-enable @typescript-eslint/no-unused-vars */
313
+ connection = __rest(configVar, ["orgOnly", "visibleToOrgDeployer", "visibleToCustomerDeployer", "stableKey"]);
314
+ return [...result, convertConnection(Object.assign(Object.assign({}, connection), { key }))];
315
+ }, []);
316
+ return {
317
+ key: referenceKey,
318
+ display: {
319
+ label: referenceKey,
320
+ iconPath,
321
+ description: description || name,
322
+ },
323
+ connections: convertedConnections,
324
+ actions: convertedActions,
325
+ triggers: convertedTriggers,
326
+ dataSources: convertedDataSources,
327
+ };
328
+ };
@@ -1,14 +1,14 @@
1
1
  /// <reference types="node" />
2
- import { Instance, Customer, DataSourceType, DataSourceResultType, User, TriggerEventFunctionReturn, Integration, Flow } from "../types";
2
+ import { InstanceAttributes, CustomerAttributes, DataSourceType, DataSourceResultType, UserAttributes, TriggerEventFunctionReturn, IntegrationAttributes, FlowAttributes, ConfigVarResultCollection } from "../types";
3
3
  interface DisplayDefinition {
4
4
  label: string;
5
5
  description: string;
6
6
  }
7
- export { Instance } from "../types";
8
- export { Customer } from "../types";
9
- export { User } from "../types";
10
- export { Integration } from "../types";
11
- export { Flow } from "../types";
7
+ export { InstanceAttributes } from "../types";
8
+ export { CustomerAttributes } from "../types";
9
+ export { UserAttributes } from "../types";
10
+ export { IntegrationAttributes } from "../types";
11
+ export { FlowAttributes } from "../types";
12
12
  export interface Component {
13
13
  key: string;
14
14
  public?: boolean;
@@ -21,6 +21,7 @@ export interface Component {
21
21
  triggers: Record<string, Trigger>;
22
22
  dataSources: Record<string, DataSource>;
23
23
  connections: Connection[];
24
+ codeNativeIntegrationYAML?: string;
24
25
  }
25
26
  export interface Action {
26
27
  key: string;
@@ -47,7 +48,7 @@ export interface ActionLogger {
47
48
  warn: ActionLoggerFunction;
48
49
  error: ActionLoggerFunction;
49
50
  }
50
- export interface ActionContext {
51
+ export declare type ActionContext<TConfigVars extends ConfigVarResultCollection, THasConfigVars extends boolean = false> = {
51
52
  logger: ActionLogger;
52
53
  instanceState: Record<string, unknown>;
53
54
  crossFlowState: Record<string, unknown>;
@@ -58,13 +59,15 @@ export interface ActionContext {
58
59
  webhookUrls: Record<string, string>;
59
60
  webhookApiKeys: Record<string, string[]>;
60
61
  invokeUrl: string;
61
- customer: Customer;
62
- instance: Instance;
63
- user: User;
64
- integration: Integration;
65
- flow: Flow;
62
+ customer: CustomerAttributes;
63
+ instance: InstanceAttributes;
64
+ user: UserAttributes;
65
+ integration: IntegrationAttributes;
66
+ flow: FlowAttributes;
66
67
  startedAt: string;
67
- }
68
+ } & (THasConfigVars extends true ? {
69
+ configVars: TConfigVars;
70
+ } : Record<string, never>);
68
71
  declare type TriggerOptionChoice = "invalid" | "valid" | "required";
69
72
  export interface TriggerPayload {
70
73
  headers: Record<string, string>;
@@ -82,11 +85,11 @@ export interface TriggerPayload {
82
85
  webhookApiKeys: Record<string, string[]>;
83
86
  invokeUrl: string;
84
87
  executionId: string;
85
- customer: Customer;
86
- instance: Instance;
87
- user: User;
88
- integration: Integration;
89
- flow: Flow;
88
+ customer: CustomerAttributes;
89
+ instance: InstanceAttributes;
90
+ user: UserAttributes;
91
+ integration: IntegrationAttributes;
92
+ flow: FlowAttributes;
90
93
  startedAt: string;
91
94
  }
92
95
  interface HttpResponse {
@@ -109,9 +112,9 @@ interface TriggerBranchingResult extends TriggerBaseResult {
109
112
  branch: string;
110
113
  }
111
114
  export declare type TriggerResult = TriggerBranchingResult | TriggerBaseResult | undefined;
112
- export declare type TriggerPerformFunction = (context: ActionContext, payload: TriggerPayload, params: Record<string, unknown>) => Promise<TriggerResult>;
115
+ export declare type TriggerPerformFunction = (context: ActionContext<any>, payload: TriggerPayload, params: Record<string, unknown>) => Promise<TriggerResult>;
113
116
  export declare type TriggerEventFunctionResult = TriggerEventFunctionReturn | void;
114
- export declare type TriggerEventFunction = (context: ActionContext, params: Record<string, unknown>) => Promise<TriggerEventFunctionResult>;
117
+ export declare type TriggerEventFunction = (context: ActionContext<any>, params: Record<string, unknown>) => Promise<TriggerEventFunctionResult>;
115
118
  export interface Trigger {
116
119
  key: string;
117
120
  display: DisplayDefinition & {
@@ -136,9 +139,9 @@ export interface Trigger {
136
139
  }
137
140
  export interface DataSourceContext {
138
141
  logger: ActionLogger;
139
- customer: Customer;
140
- instance: Instance;
141
- user: User;
142
+ customer: CustomerAttributes;
143
+ instance: InstanceAttributes;
144
+ user: UserAttributes;
142
145
  }
143
146
  export declare type DataSourceResult = {
144
147
  result: DataSourceResultType;
@@ -211,7 +214,7 @@ interface ServerPerformBranchingDataReturn extends ServerPerformDataReturn {
211
214
  branch: string;
212
215
  }
213
216
  export declare type ActionPerformReturn = ServerPerformDataStructureReturn | ServerPerformBranchingDataStructureReturn | ServerPerformDataReturn | ServerPerformBranchingDataReturn | undefined;
214
- export declare type ActionPerformFunction = (context: ActionContext, params: Record<string, unknown>) => Promise<ActionPerformReturn>;
217
+ export declare type ActionPerformFunction = (context: ActionContext<any>, params: Record<string, unknown>) => Promise<ActionPerformReturn>;
215
218
  interface InputFieldChoice {
216
219
  label: string;
217
220
  value: string;
package/dist/testing.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * https://prismatic.io/docs/custom-components/writing-custom-components/#testing-a-component
6
6
  */
7
7
  import { TriggerPayload, TriggerResult, ConnectionValue, ActionLogger, Component, ActionContext, ActionPerformReturn, DataSourceResult, DataSourceContext } from "./serverTypes";
8
- import { ConnectionDefinition, ActionDefinition, TriggerDefinition, Inputs, ActionInputParameters, DataSourceDefinition, ActionPerformReturn as InvokeActionPerformReturn, TriggerResult as InvokeTriggerResult, DataSourceResult as InvokeDataSourceResult, TriggerEventFunctionReturn } from "./types";
8
+ import { ConnectionDefinition, ActionDefinition, TriggerDefinition, Inputs, ActionInputParameters, DataSourceDefinition, ActionPerformReturn as InvokeActionPerformReturn, TriggerResult as InvokeTriggerResult, DataSourceResult as InvokeDataSourceResult, TriggerEventFunctionReturn, Flow, ConfigVarResultCollection, ConfigVarCollection, ConfigVarDefinitionsToResults } from "./types";
9
9
  export declare const createConnection: <T extends ConnectionDefinition>({ key }: T, values: Record<string, unknown>, tokenValues?: Record<string, unknown> | undefined) => ConnectionValue;
10
10
  /**
11
11
  * Pre-built mock of ActionLogger. Suitable for asserting logs are created as expected.
@@ -25,7 +25,7 @@ interface InvokeReturn<ReturnData> {
25
25
  * to avoid extra casting within test methods. Returns an InvokeResult containing both the
26
26
  * action result and a mock logger for asserting logging.
27
27
  */
28
- export declare const invoke: <TInputs extends Inputs, TAllowsBranching extends boolean, TReturn extends InvokeActionPerformReturn<TAllowsBranching, unknown>>({ perform }: ActionDefinition<TInputs, TAllowsBranching, TReturn>, params: ActionInputParameters<TInputs>, context?: Partial<ActionContext> | undefined) => Promise<InvokeReturn<TReturn>>;
28
+ export declare const invoke: <TInputs extends Inputs, TConfigVars extends ConfigVarResultCollection, TAllowsBranching extends boolean, TReturn extends InvokeActionPerformReturn<TAllowsBranching, unknown>>({ perform, }: ActionDefinition<TInputs, TConfigVars, TAllowsBranching, TReturn>, params: ActionInputParameters<TInputs>, context?: Partial<ActionContext<TConfigVars, false>> | undefined) => Promise<InvokeReturn<TReturn>>;
29
29
  export declare const defaultTriggerPayload: () => TriggerPayload;
30
30
  /**
31
31
  * Invokes specified TriggerDefinition perform function using supplied params
@@ -33,7 +33,7 @@ export declare const defaultTriggerPayload: () => TriggerPayload;
33
33
  * to avoid extra casting within test methods. Returns an InvokeResult containing both the
34
34
  * trigger result and a mock logger for asserting logging.
35
35
  */
36
- export declare const invokeTrigger: <TInputs extends Inputs, TAllowsBranching extends boolean, TResult extends InvokeTriggerResult<TAllowsBranching>>({ perform }: TriggerDefinition<TInputs, TAllowsBranching, TResult>, context?: Partial<ActionContext> | undefined, payload?: TriggerPayload | undefined, params?: ActionInputParameters<TInputs> | undefined) => Promise<InvokeReturn<TResult>>;
36
+ export declare const invokeTrigger: <TInputs extends Inputs, TConfigVars extends ConfigVarResultCollection, TAllowsBranching extends boolean, TResult extends InvokeTriggerResult<TAllowsBranching, TriggerPayload>>({ perform, }: TriggerDefinition<TInputs, TConfigVars, TAllowsBranching, TResult>, context?: Partial<ActionContext<TConfigVars, false>> | undefined, payload?: TriggerPayload | undefined, params?: ActionInputParameters<TInputs> | undefined) => Promise<InvokeReturn<TResult>>;
37
37
  /**
38
38
  * Invokes specified DataSourceDefinition perform function using supplied params.
39
39
  * Accepts a generic type matching DataSourceResult as a convenience to avoid extra
@@ -56,23 +56,28 @@ export declare const invokeDataSource: <TInputs extends Inputs, TDataSourceType
56
56
  objectFieldMap: import("./types").ObjectFieldMap;
57
57
  jsonForm: import("./types").JSONForm;
58
58
  }>({ perform }: DataSourceDefinition<TInputs, TDataSourceType>, params: ActionInputParameters<TInputs>, context?: Partial<DataSourceContext> | undefined) => Promise<InvokeDataSourceResult<TDataSourceType>>;
59
+ /**
60
+ * Invokes specified Flow of a Code Native Integration using supplied params.
61
+ * Runs the Trigger and then the Action function and returns the result of the Action.
62
+ */
63
+ export declare const invokeFlow: <TConfigVars extends ConfigVarCollection>(flow: Flow<TConfigVars, import("./types").TriggerPayload>, context?: Partial<ActionContext<ConfigVarDefinitionsToResults<TConfigVars>, true>> | undefined, payload?: TriggerPayload | undefined) => Promise<InvokeReturn<InvokeActionPerformReturn<false, unknown>>>;
59
64
  export declare class ComponentTestHarness<TComponent extends Component> {
60
65
  component: TComponent;
61
66
  constructor(component: TComponent);
62
67
  private buildContext;
63
68
  private buildParams;
64
69
  connectionValue({ key }: ConnectionDefinition): ConnectionValue;
65
- trigger(key: string, payload?: TriggerPayload, params?: Record<string, unknown>, context?: Partial<ActionContext>): Promise<TriggerResult>;
66
- triggerOnInstanceDeploy(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext>): Promise<void | TriggerEventFunctionReturn>;
67
- triggerOnInstanceDelete(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext>): Promise<void | TriggerEventFunctionReturn>;
68
- action(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext>): Promise<ActionPerformReturn>;
70
+ trigger<TConfigVars extends ConfigVarResultCollection>(key: string, payload?: TriggerPayload, params?: Record<string, unknown>, context?: Partial<ActionContext<TConfigVars>>): Promise<TriggerResult>;
71
+ triggerOnInstanceDeploy<TConfigVars extends ConfigVarResultCollection>(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext<TConfigVars>>): Promise<void | TriggerEventFunctionReturn>;
72
+ triggerOnInstanceDelete<TConfigVars extends ConfigVarResultCollection>(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext<TConfigVars>>): Promise<void | TriggerEventFunctionReturn>;
73
+ action<TConfigVars extends ConfigVarResultCollection>(key: string, params?: Record<string, unknown>, context?: Partial<ActionContext<TConfigVars>>): Promise<ActionPerformReturn>;
69
74
  dataSource(key: string, params?: Record<string, unknown>, context?: Partial<DataSourceContext>): Promise<DataSourceResult>;
70
75
  }
71
76
  export declare const createHarness: <TComponent extends Component>(component: TComponent) => ComponentTestHarness<TComponent>;
72
77
  declare const _default: {
73
78
  loggerMock: () => ActionLogger;
74
- invoke: <TInputs extends Inputs, TAllowsBranching extends boolean, TReturn extends InvokeActionPerformReturn<TAllowsBranching, unknown>>({ perform }: ActionDefinition<TInputs, TAllowsBranching, TReturn>, params: ActionInputParameters<TInputs>, context?: Partial<ActionContext> | undefined) => Promise<InvokeReturn<TReturn>>;
75
- invokeTrigger: <TInputs_1 extends Inputs, TAllowsBranching_1 extends boolean, TResult extends InvokeTriggerResult<TAllowsBranching_1>>({ perform }: TriggerDefinition<TInputs_1, TAllowsBranching_1, TResult>, context?: Partial<ActionContext> | undefined, payload?: TriggerPayload | undefined, params?: ActionInputParameters<TInputs_1> | undefined) => Promise<InvokeReturn<TResult>>;
79
+ invoke: <TInputs extends Inputs, TConfigVars extends ConfigVarResultCollection, TAllowsBranching extends boolean, TReturn extends InvokeActionPerformReturn<TAllowsBranching, unknown>>({ perform, }: ActionDefinition<TInputs, TConfigVars, TAllowsBranching, TReturn>, params: ActionInputParameters<TInputs>, context?: Partial<ActionContext<TConfigVars, false>> | undefined) => Promise<InvokeReturn<TReturn>>;
80
+ invokeTrigger: <TInputs_1 extends Inputs, TConfigVars_1 extends ConfigVarResultCollection, TAllowsBranching_1 extends boolean, TResult extends InvokeTriggerResult<TAllowsBranching_1, TriggerPayload>>({ perform, }: TriggerDefinition<TInputs_1, TConfigVars_1, TAllowsBranching_1, TResult>, context?: Partial<ActionContext<TConfigVars_1, false>> | undefined, payload?: TriggerPayload | undefined, params?: ActionInputParameters<TInputs_1> | undefined) => Promise<InvokeReturn<TResult>>;
76
81
  createHarness: <TComponent extends Component>(component: TComponent) => ComponentTestHarness<TComponent>;
77
82
  invokeDataSource: <TInputs_2 extends Inputs, TDataSourceType extends keyof {
78
83
  string: string;
package/dist/testing.js CHANGED
@@ -15,7 +15,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
15
15
  });
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.createHarness = exports.ComponentTestHarness = exports.invokeDataSource = exports.invokeTrigger = exports.defaultTriggerPayload = exports.invoke = exports.loggerMock = exports.createConnection = void 0;
18
+ exports.createHarness = exports.ComponentTestHarness = exports.invokeFlow = exports.invokeDataSource = exports.invokeTrigger = exports.defaultTriggerPayload = exports.invoke = exports.loggerMock = exports.createConnection = void 0;
19
19
  const jest_mock_1 = require("jest-mock");
20
20
  const createConnection = ({ key }, values, tokenValues) => ({
21
21
  configVarKey: "",
@@ -38,46 +38,32 @@ const loggerMock = () => ({
38
38
  error: (0, jest_mock_1.spyOn)(console, "error"),
39
39
  });
40
40
  exports.loggerMock = loggerMock;
41
- const baseActionContext = {
42
- logger: (0, exports.loggerMock)(),
43
- instanceState: {},
44
- crossFlowState: {},
45
- executionState: {},
46
- integrationState: {},
47
- stepId: "mockStepId",
48
- executionId: "mockExecutionId",
49
- webhookUrls: {
50
- "Flow 1": "https://example.com",
51
- },
52
- webhookApiKeys: {
53
- "Flow 1": ["example-123", "example-456"],
54
- },
55
- invokeUrl: "https://example.com",
56
- customer: {
57
- id: "customerId",
58
- name: "Customer 1",
59
- externalId: "1234",
60
- },
61
- instance: {
62
- id: "instanceId",
63
- name: "Instance 1",
64
- },
65
- user: {
66
- id: "userId",
67
- email: "user@example.com",
68
- name: "User 1",
69
- externalId: "1234",
70
- },
71
- integration: {
72
- id: "integrationId",
73
- name: "Integration 1",
74
- versionSequenceId: "1234",
75
- },
76
- flow: {
77
- id: "flowId",
78
- name: "Flow 1",
79
- },
80
- startedAt: new Date().toISOString(),
41
+ const createActionContext = (context) => {
42
+ return Object.assign({ logger: (0, exports.loggerMock)(), instanceState: {}, crossFlowState: {}, executionState: {}, integrationState: {}, stepId: "mockStepId", executionId: "mockExecutionId", webhookUrls: {
43
+ "Flow 1": "https://example.com",
44
+ }, webhookApiKeys: {
45
+ "Flow 1": ["example-123", "example-456"],
46
+ }, invokeUrl: "https://example.com", customer: {
47
+ id: "customerId",
48
+ name: "Customer 1",
49
+ externalId: "1234",
50
+ }, instance: {
51
+ id: "instanceId",
52
+ name: "Instance 1",
53
+ }, user: {
54
+ id: "userId",
55
+ email: "user@example.com",
56
+ name: "User 1",
57
+ externalId: "1234",
58
+ }, integration: {
59
+ id: "integrationId",
60
+ name: "Integration 1",
61
+ versionSequenceId: "1234",
62
+ externalVersion: "1.0.0",
63
+ }, flow: {
64
+ id: "flowId",
65
+ name: "Flow 1",
66
+ }, startedAt: new Date().toISOString() }, context);
81
67
  };
82
68
  /**
83
69
  * Invokes specified ActionDefinition perform function using supplied params
@@ -85,8 +71,8 @@ const baseActionContext = {
85
71
  * to avoid extra casting within test methods. Returns an InvokeResult containing both the
86
72
  * action result and a mock logger for asserting logging.
87
73
  */
88
- const invoke = ({ perform }, params, context) => __awaiter(void 0, void 0, void 0, function* () {
89
- const realizedContext = Object.assign(Object.assign({}, baseActionContext), context);
74
+ const invoke = ({ perform, }, params, context) => __awaiter(void 0, void 0, void 0, function* () {
75
+ const realizedContext = createActionContext(context);
90
76
  const result = yield perform(realizedContext, params);
91
77
  return {
92
78
  result,
@@ -138,6 +124,7 @@ const defaultTriggerPayload = () => {
138
124
  id: "integrationId",
139
125
  name: "Integration 1",
140
126
  versionSequenceId: "1234",
127
+ externalVersion: "1.0.0",
141
128
  },
142
129
  flow: {
143
130
  id: "flowId",
@@ -153,8 +140,8 @@ exports.defaultTriggerPayload = defaultTriggerPayload;
153
140
  * to avoid extra casting within test methods. Returns an InvokeResult containing both the
154
141
  * trigger result and a mock logger for asserting logging.
155
142
  */
156
- const invokeTrigger = ({ perform }, context, payload, params) => __awaiter(void 0, void 0, void 0, function* () {
157
- const realizedContext = Object.assign(Object.assign({}, baseActionContext), context);
143
+ const invokeTrigger = ({ perform, }, context, payload, params) => __awaiter(void 0, void 0, void 0, function* () {
144
+ const realizedContext = createActionContext(context);
158
145
  const realizedPayload = Object.assign(Object.assign({}, (0, exports.defaultTriggerPayload)()), payload);
159
146
  const realizedParams = params || {};
160
147
  const result = yield perform(realizedContext, realizedPayload, realizedParams);
@@ -193,6 +180,27 @@ const invokeDataSource = ({ perform }, params, context) => __awaiter(void 0, voi
193
180
  return result;
194
181
  });
195
182
  exports.invokeDataSource = invokeDataSource;
183
+ /**
184
+ * Invokes specified Flow of a Code Native Integration using supplied params.
185
+ * Runs the Trigger and then the Action function and returns the result of the Action.
186
+ */
187
+ const invokeFlow = (flow, context, payload) => __awaiter(void 0, void 0, void 0, function* () {
188
+ const realizedContext = createActionContext(context);
189
+ const realizedPayload = Object.assign(Object.assign({}, (0, exports.defaultTriggerPayload)()), payload);
190
+ const params = {
191
+ onTrigger: { results: null },
192
+ };
193
+ if ("onTrigger" in flow) {
194
+ const triggerResult = yield flow.onTrigger(realizedContext, realizedPayload, params);
195
+ params.onTrigger = { results: triggerResult === null || triggerResult === void 0 ? void 0 : triggerResult.payload };
196
+ }
197
+ const result = yield flow.onExecution(realizedContext, params);
198
+ return {
199
+ result,
200
+ loggerMock: realizedContext.logger,
201
+ };
202
+ });
203
+ exports.invokeFlow = invokeFlow;
196
204
  class ComponentTestHarness {
197
205
  constructor(component) {
198
206
  this.component = component;
@@ -215,7 +223,7 @@ class ComponentTestHarness {
215
223
  trigger(key, payload, params, context) {
216
224
  return __awaiter(this, void 0, void 0, function* () {
217
225
  const trigger = this.component.triggers[key];
218
- return trigger.perform(this.buildContext(baseActionContext, context), Object.assign(Object.assign({}, (0, exports.defaultTriggerPayload)()), payload), this.buildParams(trigger.inputs, params));
226
+ return trigger.perform(createActionContext(context), Object.assign(Object.assign({}, (0, exports.defaultTriggerPayload)()), payload), this.buildParams(trigger.inputs, params));
219
227
  });
220
228
  }
221
229
  triggerOnInstanceDeploy(key, params, context) {
@@ -224,7 +232,7 @@ class ComponentTestHarness {
224
232
  if (!trigger.onInstanceDeploy) {
225
233
  throw new Error("Trigger does not support onInstanceDeploy");
226
234
  }
227
- return trigger.onInstanceDeploy(this.buildContext(baseActionContext, context), this.buildParams(trigger.inputs, params));
235
+ return trigger.onInstanceDeploy(createActionContext(context), this.buildParams(trigger.inputs, params));
228
236
  });
229
237
  }
230
238
  triggerOnInstanceDelete(key, params, context) {
@@ -233,13 +241,13 @@ class ComponentTestHarness {
233
241
  if (!trigger.onInstanceDelete) {
234
242
  throw new Error("Trigger does not support onInstanceDelete");
235
243
  }
236
- return trigger.onInstanceDelete(this.buildContext(baseActionContext, context), this.buildParams(trigger.inputs, params));
244
+ return trigger.onInstanceDelete(createActionContext(context), this.buildParams(trigger.inputs, params));
237
245
  });
238
246
  }
239
247
  action(key, params, context) {
240
248
  return __awaiter(this, void 0, void 0, function* () {
241
249
  const action = this.component.actions[key];
242
- return action.perform(this.buildContext(baseActionContext, context), this.buildParams(action.inputs, params));
250
+ return action.perform(createActionContext(context), this.buildParams(action.inputs, params));
243
251
  });
244
252
  }
245
253
  dataSource(key, params, context) {
@@ -1,13 +1,13 @@
1
- import { ActionDisplayDefinition, ActionPerformFunction, ActionPerformReturn, Inputs } from ".";
1
+ import { ActionDisplayDefinition, ActionPerformFunction, ActionPerformReturn, ConfigVarResultCollection, Inputs } from ".";
2
2
  /**
3
3
  * ActionDefinition is the type of the object that is passed in to `action` function to
4
4
  * define a component action.
5
5
  */
6
- export interface ActionDefinition<TInputs extends Inputs, TAllowsBranching extends boolean, TReturn extends ActionPerformReturn<TAllowsBranching, unknown>> {
6
+ export interface ActionDefinition<TInputs extends Inputs = Inputs, TConfigVars extends ConfigVarResultCollection = ConfigVarResultCollection, TAllowsBranching extends boolean = boolean, TReturn extends ActionPerformReturn<TAllowsBranching, unknown> = ActionPerformReturn<TAllowsBranching, unknown>> {
7
7
  /** Defines how the Action is displayed in the Prismatic interface. */
8
8
  display: ActionDisplayDefinition;
9
9
  /** Function to perform when this Action is invoked. */
10
- perform: ActionPerformFunction<TInputs, TAllowsBranching, TReturn>;
10
+ perform: ActionPerformFunction<TInputs, TConfigVars, false, TAllowsBranching, TReturn>;
11
11
  /** InputFields to present in the Prismatic interface for configuration of this Action. */
12
12
  inputs: TInputs;
13
13
  /** Optional attribute that specifies whether an Action will terminate execution.*/
@@ -1,6 +1,6 @@
1
1
  import { Inputs } from ".";
2
2
  import { ConditionalExpression } from "./conditional-logic";
3
- import { InputFieldCollection, InputCleanFunction, Connection, KeyValuePair } from "./Inputs";
3
+ import { InputFieldCollection, InputCleanFunction, Connection } from "./Inputs";
4
4
  /**
5
5
  * Collection of input parameters.
6
6
  * Inputs can be static values, references to config variables, or
@@ -10,3 +10,16 @@ export declare type ActionInputParameters<TInputs extends Inputs> = {
10
10
  [Property in keyof TInputs]: TInputs[Property]["clean"] extends InputCleanFunction<any> ? ReturnType<TInputs[Property]["clean"]> : TInputs[Property]["type"] extends "connection" ? ExtractValue<Connection, TInputs[Property]["collection"]> : TInputs[Property]["type"] extends "conditional" ? ExtractValue<ConditionalExpression, TInputs[Property]["collection"]> : ExtractValue<TInputs[Property]["default"], TInputs[Property]["collection"]>;
11
11
  };
12
12
  export declare type ExtractValue<TType, TCollection extends InputFieldCollection | undefined> = TCollection extends "keyvaluelist" ? KeyValuePair<TType>[] : TCollection extends "valuelist" ? TType[] : TType;
13
+ /**
14
+ * KeyValuePair input parameter type.
15
+ * This allows users to input multiple keys / values as an input.
16
+ * To see an example of how this can be used, see the `tagging` input
17
+ * of the `putObject` action of the AWS S3 component:
18
+ * https://github.com/prismatic-io/examples/blob/main/components/aws-s3/src/actions.ts
19
+ */
20
+ export interface KeyValuePair<V = unknown> {
21
+ /** Key of the KeyValuePair */
22
+ key: string;
23
+ /** Value of the KeyValuePair */
24
+ value: V;
25
+ }