aws-local-stepfunctions 0.6.0 → 1.0.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.
@@ -19806,27 +19806,11 @@ var ExecutionAbortedError = class extends Error {
19806
19806
  }
19807
19807
  };
19808
19808
 
19809
- // src/error/RuntimeError.ts
19810
- var RuntimeError = class extends Error {
19811
- constructor(message) {
19812
- super(message);
19813
- this.name = "RuntimeError";
19814
- this.retryable = true;
19815
- this.catchable = true;
19816
- }
19817
- get isRetryable() {
19818
- return this.retryable;
19819
- }
19820
- get isCatchable() {
19821
- return this.catchable;
19822
- }
19823
- };
19824
-
19825
- // src/error/predefined/StatesTimeoutError.ts
19826
- var StatesTimeoutError = class extends RuntimeError {
19809
+ // src/error/ExecutionTimeoutError.ts
19810
+ var ExecutionTimeoutError = class extends Error {
19827
19811
  constructor() {
19828
- super("States.Timeout");
19829
- this.name = "States.Timeout";
19812
+ super("Execution timed out");
19813
+ this.name = "ExecutionTimeoutError";
19830
19814
  }
19831
19815
  };
19832
19816
 
@@ -19877,20 +19861,32 @@ function sfc32(a3, b3, c3, d3) {
19877
19861
  return (t2 >>> 0) / 4294967296;
19878
19862
  };
19879
19863
  }
19880
- function getRandomNumber(min, max, rngGenerator = Math.random) {
19881
- return Math.floor(rngGenerator() * (max - min + 1)) + min;
19864
+ function getRandomNumber(min, max, rng2 = Math.random) {
19865
+ return Math.floor(rng2() * (max - min + 1)) + min;
19882
19866
  }
19883
19867
 
19884
19868
  // src/util/index.ts
19885
19869
  function isPlainObj(value) {
19886
19870
  return !!value && Object.getPrototypeOf(value) === Object.prototype;
19887
19871
  }
19888
- function sleep(ms, abortSignal) {
19872
+ function sleep(ms, abortSignal, rootAbortSignal) {
19889
19873
  return new Promise((resolve) => {
19890
- const timeout = setTimeout(resolve, ms);
19891
- abortSignal?.addEventListener("abort", () => {
19874
+ if (abortSignal?.aborted || rootAbortSignal?.aborted) {
19875
+ return resolve();
19876
+ }
19877
+ const onAbort = () => {
19878
+ abortSignal?.removeEventListener("abort", onAbort);
19879
+ rootAbortSignal?.removeEventListener("abort", onAbort);
19892
19880
  clearTimeout(timeout);
19893
- });
19881
+ resolve();
19882
+ };
19883
+ const timeout = setTimeout(() => {
19884
+ abortSignal?.removeEventListener("abort", onAbort);
19885
+ rootAbortSignal?.removeEventListener("abort", onAbort);
19886
+ resolve();
19887
+ }, ms);
19888
+ abortSignal?.addEventListener("abort", onAbort);
19889
+ rootAbortSignal?.addEventListener("abort", onAbort);
19894
19890
  });
19895
19891
  }
19896
19892
  function byteToHex(byte) {
@@ -19906,6 +19902,22 @@ function jsonPathQuery(pathExpression, json, context) {
19906
19902
  return JSONPath({ path: pathExpression, json, wrap: false });
19907
19903
  }
19908
19904
 
19905
+ // src/error/RuntimeError.ts
19906
+ var RuntimeError = class extends Error {
19907
+ constructor(message) {
19908
+ super(message);
19909
+ this.name = "RuntimeError";
19910
+ this.retryable = true;
19911
+ this.catchable = true;
19912
+ }
19913
+ get isRetryable() {
19914
+ return this.retryable;
19915
+ }
19916
+ get isCatchable() {
19917
+ return this.catchable;
19918
+ }
19919
+ };
19920
+
19909
19921
  // src/error/predefined/StatesResultPathMatchFailureError.ts
19910
19922
  var StatesResultPathMatchFailureError = class extends RuntimeError {
19911
19923
  constructor() {
@@ -19950,7 +19962,7 @@ function validateArgumentType(allowedTypes, argPosition, funcArg, funcName) {
19950
19962
  if (matchesAllowedType)
19951
19963
  break;
19952
19964
  }
19953
- const expectedType = allowedTypes.map((type) => `"${type}"`).join(" | ");
19965
+ const expectedType = allowedTypes.map((type) => `'${type}'`).join(" | ");
19954
19966
  if (!matchesAllowedType) {
19955
19967
  throw new StatesRuntimeError(
19956
19968
  `Intrinsic function ${funcName} expected argument ${argPosition} to be of type ${expectedType}, but received ${typeof funcArg}`
@@ -19978,7 +19990,7 @@ function validateArgumentConstraints(argConstraints, argPosition, funcArg, funcN
19978
19990
  if (matchesAllConstraints)
19979
19991
  break;
19980
19992
  }
19981
- const expectedConstraints = argConstraints.map((constraint) => `"${constraint}"`).join(" | ");
19993
+ const expectedConstraints = argConstraints.map((constraint) => `'${constraint}'`).join(" | ");
19982
19994
  if (!matchesAllConstraints) {
19983
19995
  throw new StatesRuntimeError(
19984
19996
  `Intrinsic function ${funcName} expected argument ${argPosition} to satisfy the following constraints: ${expectedConstraints}`
@@ -20600,7 +20612,7 @@ function processPayloadTemplate(payloadTemplate, json, context) {
20600
20612
  let sanitizedKey = key;
20601
20613
  let resolvedValue = value;
20602
20614
  if (isPlainObj(value)) {
20603
- resolvedValue = processPayloadTemplate(value, json);
20615
+ resolvedValue = processPayloadTemplate(value, json, context);
20604
20616
  }
20605
20617
  if (key.endsWith(".$") && typeof value === "string") {
20606
20618
  sanitizedKey = key.replace(".$", "");
@@ -20640,8 +20652,9 @@ function processOutputPath(path, result, context) {
20640
20652
 
20641
20653
  // src/stateMachine/stateActions/BaseStateAction.ts
20642
20654
  var BaseStateAction = class {
20643
- constructor(stateDefinition) {
20655
+ constructor(stateDefinition, stateName) {
20644
20656
  this.stateDefinition = stateDefinition;
20657
+ this.stateName = stateName;
20645
20658
  }
20646
20659
  buildExecutionResult(stateResult) {
20647
20660
  const executionResult = { stateResult, nextState: "", isEndState: false };
@@ -20783,8 +20796,8 @@ var index_es_default = wildcardMatch;
20783
20796
 
20784
20797
  // src/stateMachine/stateActions/ChoiceStateAction.ts
20785
20798
  var ChoiceStateAction = class extends BaseStateAction {
20786
- constructor(stateDefinition) {
20787
- super(stateDefinition);
20799
+ constructor(stateDefinition, stateName) {
20800
+ super(stateDefinition, stateName);
20788
20801
  }
20789
20802
  testChoiceRule(choiceRule, input) {
20790
20803
  if ("And" in choiceRule) {
@@ -21007,8 +21020,8 @@ var FailStateError = class extends RuntimeError {
21007
21020
 
21008
21021
  // src/stateMachine/stateActions/FailStateAction.ts
21009
21022
  var FailStateAction = class extends BaseStateAction {
21010
- constructor(stateDefinition) {
21011
- super(stateDefinition);
21023
+ constructor(stateDefinition, stateName) {
21024
+ super(stateDefinition, stateName);
21012
21025
  }
21013
21026
  async execute(input, context, options) {
21014
21027
  throw new FailStateError(this.stateDefinition.Error, this.stateDefinition.Cause);
@@ -21019,10 +21032,17 @@ var FailStateAction = class extends BaseStateAction {
21019
21032
  var import_p_limit = __toESM(require_p_limit(), 1);
21020
21033
  var DEFAULT_MAX_CONCURRENCY = 40;
21021
21034
  var MapStateAction = class extends BaseStateAction {
21022
- constructor(stateDefinition) {
21023
- super(stateDefinition);
21035
+ constructor(stateDefinition, stateName) {
21036
+ super(stateDefinition, stateName);
21024
21037
  this.executionAbortFuncs = [];
21025
21038
  }
21039
+ async forwardEventsToRootEventLogger(eventLogger, executionEventLogs, index, parentStateRawInput) {
21040
+ if (!eventLogger)
21041
+ return;
21042
+ for await (const event of executionEventLogs) {
21043
+ eventLogger.forwardNestedMapEvent(event, index, this.stateName, parentStateRawInput);
21044
+ }
21045
+ }
21026
21046
  processItem(stateMachine, item, input, context, index, options) {
21027
21047
  const state = this.stateDefinition;
21028
21048
  let paramValue;
@@ -21037,6 +21057,7 @@ var MapStateAction = class extends BaseStateAction {
21037
21057
  }
21038
21058
  const execution = stateMachine.run(paramValue ?? item, options?.runOptions);
21039
21059
  this.executionAbortFuncs.push(execution.abort);
21060
+ this.forwardEventsToRootEventLogger(options?.eventLogger, execution.eventLogs, index, options?.rawInput);
21040
21061
  return execution.result;
21041
21062
  }
21042
21063
  async execute(input, context, options) {
@@ -21048,7 +21069,10 @@ var MapStateAction = class extends BaseStateAction {
21048
21069
  if (!Array.isArray(items)) {
21049
21070
  throw new StatesRuntimeError("Input of Map state must be an array or ItemsPath property must point to an array");
21050
21071
  }
21051
- const iteratorStateMachine = new StateMachine(state.Iterator, options?.stateMachineOptions);
21072
+ const iteratorStateMachine = new StateMachine(state.Iterator, {
21073
+ ...options?.stateMachineOptions,
21074
+ validationOptions: { _noValidate: true }
21075
+ });
21052
21076
  const limit = (0, import_p_limit.default)(state.MaxConcurrency || DEFAULT_MAX_CONCURRENCY);
21053
21077
  const processedItemsPromise = items.map(
21054
21078
  (item, i3) => limit(() => this.processItem(iteratorStateMachine, item, input, context, i3, options))
@@ -21072,14 +21096,25 @@ var MapStateAction = class extends BaseStateAction {
21072
21096
  var import_p_limit2 = __toESM(require_p_limit(), 1);
21073
21097
  var DEFAULT_CONCURRENCY = 40;
21074
21098
  var ParallelStateAction = class extends BaseStateAction {
21075
- constructor(stateDefinition) {
21076
- super(stateDefinition);
21099
+ constructor(stateDefinition, stateName) {
21100
+ super(stateDefinition, stateName);
21077
21101
  this.executionAbortFuncs = [];
21078
21102
  }
21103
+ async forwardEventsToRootEventLogger(eventLogger, executionEventLogs, parentStateRawInput) {
21104
+ if (!eventLogger)
21105
+ return;
21106
+ for await (const event of executionEventLogs) {
21107
+ eventLogger.forwardNestedParallelEvent(event, this.stateName, parentStateRawInput);
21108
+ }
21109
+ }
21079
21110
  processBranch(branch, input, context, options) {
21080
- const stateMachine = new StateMachine(branch, options?.stateMachineOptions);
21111
+ const stateMachine = new StateMachine(branch, {
21112
+ ...options?.stateMachineOptions,
21113
+ validationOptions: { _noValidate: true }
21114
+ });
21081
21115
  const execution = stateMachine.run(input, options?.runOptions);
21082
21116
  this.executionAbortFuncs.push(execution.abort);
21117
+ this.forwardEventsToRootEventLogger(options?.eventLogger, execution.eventLogs, options?.rawInput);
21083
21118
  return execution.result;
21084
21119
  }
21085
21120
  async execute(input, context, options) {
@@ -21103,8 +21138,8 @@ var ParallelStateAction = class extends BaseStateAction {
21103
21138
 
21104
21139
  // src/stateMachine/stateActions/PassStateAction.ts
21105
21140
  var PassStateAction = class extends BaseStateAction {
21106
- constructor(stateDefinition) {
21107
- super(stateDefinition);
21141
+ constructor(stateDefinition, stateName) {
21142
+ super(stateDefinition, stateName);
21108
21143
  }
21109
21144
  async execute(input, context, options) {
21110
21145
  if (this.stateDefinition.Result) {
@@ -21116,8 +21151,8 @@ var PassStateAction = class extends BaseStateAction {
21116
21151
 
21117
21152
  // src/stateMachine/stateActions/SucceedStateAction.ts
21118
21153
  var SucceedStateAction = class extends BaseStateAction {
21119
- constructor(stateDefinition) {
21120
- super(stateDefinition);
21154
+ constructor(stateDefinition, stateName) {
21155
+ super(stateDefinition, stateName);
21121
21156
  }
21122
21157
  async execute(input, context, options) {
21123
21158
  return { stateResult: input, nextState: "", isEndState: true };
@@ -27039,12 +27074,12 @@ var LambdaClient2 = class {
27039
27074
  if (config) {
27040
27075
  if (!config.region) {
27041
27076
  throw new StatesRuntimeError(
27042
- "`awsConfig` option was specified for state machine, but `region` property is not set"
27077
+ "'awsConfig' option was specified for state machine, but 'region' property is not set"
27043
27078
  );
27044
27079
  }
27045
27080
  if (config.credentials) {
27046
27081
  const credentialsTypes = Object.keys(config.credentials);
27047
- const credentialsNames = credentialsTypes.map((name) => `\`${name}\``).join(", ");
27082
+ const credentialsNames = credentialsTypes.map((name) => `'${name}'`).join(", ");
27048
27083
  if (credentialsTypes.length > 1) {
27049
27084
  throw new StatesRuntimeError(
27050
27085
  `More than one type of AWS credentials were specified: ${credentialsNames}. Only one type may be specified`
@@ -27078,7 +27113,7 @@ var LambdaClient2 = class {
27078
27113
  }
27079
27114
  if (invocationResult.FunctionError) {
27080
27115
  const errorResult = resultValue;
27081
- throw new FailStateError(errorResult.errorType, `Execution of Lambda function "${funcNameOrArn}" failed`);
27116
+ throw new FailStateError(errorResult.errorType, `Execution of Lambda function '${funcNameOrArn}' failed`);
27082
27117
  }
27083
27118
  return resultValue;
27084
27119
  }
@@ -27086,8 +27121,8 @@ var LambdaClient2 = class {
27086
27121
 
27087
27122
  // src/stateMachine/stateActions/TaskStateAction.ts
27088
27123
  var TaskStateAction = class extends BaseStateAction {
27089
- constructor(stateDefinition) {
27090
- super(stateDefinition);
27124
+ constructor(stateDefinition, stateName) {
27125
+ super(stateDefinition, stateName);
27091
27126
  }
27092
27127
  async execute(input, context, options) {
27093
27128
  const state = this.stateDefinition;
@@ -27103,36 +27138,44 @@ var TaskStateAction = class extends BaseStateAction {
27103
27138
 
27104
27139
  // src/stateMachine/stateActions/WaitStateAction.ts
27105
27140
  var WaitStateAction = class extends BaseStateAction {
27106
- constructor(stateDefinition) {
27107
- super(stateDefinition);
27141
+ constructor(stateDefinition, stateName) {
27142
+ super(stateDefinition, stateName);
27108
27143
  }
27109
27144
  async execute(input, context, options) {
27110
27145
  const state = this.stateDefinition;
27111
27146
  if (options?.waitTimeOverrideOption !== void 0) {
27112
- await sleep(options.waitTimeOverrideOption, options.abortSignal);
27147
+ await sleep(options.waitTimeOverrideOption, options.abortSignal, options.rootAbortSignal);
27113
27148
  return this.buildExecutionResult(input);
27114
27149
  }
27115
27150
  if (state.Seconds) {
27116
- await sleep(state.Seconds * 1e3, options?.abortSignal);
27151
+ await sleep(state.Seconds * 1e3, options?.abortSignal, options?.rootAbortSignal);
27117
27152
  } else if (state.Timestamp) {
27118
27153
  const dateTimestamp = new Date(state.Timestamp);
27119
27154
  const currentTime = Date.now();
27120
27155
  const timeDiff = dateTimestamp.getTime() - currentTime;
27121
- await sleep(timeDiff, options?.abortSignal);
27156
+ await sleep(timeDiff, options?.abortSignal, options?.rootAbortSignal);
27122
27157
  } else if (state.SecondsPath) {
27123
27158
  const seconds = jsonPathQuery(state.SecondsPath, input, context);
27124
- await sleep(seconds * 1e3, options?.abortSignal);
27159
+ await sleep(seconds * 1e3, options?.abortSignal, options?.rootAbortSignal);
27125
27160
  } else if (state.TimestampPath) {
27126
27161
  const timestamp = jsonPathQuery(state.TimestampPath, input, context);
27127
27162
  const dateTimestamp = new Date(timestamp);
27128
27163
  const currentTime = Date.now();
27129
27164
  const timeDiff = dateTimestamp.getTime() - currentTime;
27130
- await sleep(timeDiff, options?.abortSignal);
27165
+ await sleep(timeDiff, options?.abortSignal, options?.rootAbortSignal);
27131
27166
  }
27132
27167
  return this.buildExecutionResult(input);
27133
27168
  }
27134
27169
  };
27135
27170
 
27171
+ // src/error/predefined/StatesTimeoutError.ts
27172
+ var StatesTimeoutError = class extends RuntimeError {
27173
+ constructor() {
27174
+ super("States.Timeout");
27175
+ this.name = "States.Timeout";
27176
+ }
27177
+ };
27178
+
27136
27179
  // src/stateMachine/StateExecutor.ts
27137
27180
  var import_cloneDeep2 = __toESM(require_cloneDeep(), 1);
27138
27181
  var DEFAULT_MAX_ATTEMPTS2 = 3;
@@ -27170,6 +27213,7 @@ var StateExecutor = class {
27170
27213
  } = await this.stateHandlers[this.stateDefinition.Type](
27171
27214
  // @ts-expect-error Indexing `this.stateActions` by non-literal value produces a `never` type for the `this.stateDefinition` parameter of the handler being called
27172
27215
  this.stateDefinition,
27216
+ rawInput,
27173
27217
  processedInput,
27174
27218
  context,
27175
27219
  this.stateName,
@@ -27180,7 +27224,7 @@ var StateExecutor = class {
27180
27224
  } catch (error) {
27181
27225
  const { shouldRetry, waitTimeBeforeRetry } = this.shouldRetry(error);
27182
27226
  if (shouldRetry && waitTimeBeforeRetry) {
27183
- await sleep(waitTimeBeforeRetry, options.abortSignal);
27227
+ await sleep(waitTimeBeforeRetry, options.abortSignal, options.runOptions?._rootAbortSignal);
27184
27228
  return this.execute(input, context, options);
27185
27229
  }
27186
27230
  const { nextState, errorOutput, resultPath } = this.catchError(error);
@@ -27282,10 +27326,10 @@ var StateExecutor = class {
27282
27326
  * Invokes the Lambda function specified in the `Resource` field
27283
27327
  * and sets the current result of the state machine to the value returned by the Lambda.
27284
27328
  */
27285
- async executeTaskState(stateDefinition, input, context, stateName, options) {
27329
+ async executeTaskState(stateDefinition, rawInput, input, context, stateName, options) {
27286
27330
  const overrideFn = options.runOptions?.overrides?.taskResourceLocalHandlers?.[stateName];
27287
27331
  const awsConfig = options.stateMachineOptions?.awsConfig;
27288
- const taskStateAction = new TaskStateAction(stateDefinition);
27332
+ const taskStateAction = new TaskStateAction(stateDefinition, stateName);
27289
27333
  const executionResult = await taskStateAction.execute(input, context, { overrideFn, awsConfig });
27290
27334
  return executionResult;
27291
27335
  }
@@ -27295,11 +27339,13 @@ var StateExecutor = class {
27295
27339
  * Creates a new state machine for each of the branches specified in the `Branches` field,
27296
27340
  * and then executes each branch state machine by passing them the Parallel state input.
27297
27341
  */
27298
- async executeParallelState(stateDefinition, input, context, stateName, options) {
27299
- const parallelStateAction = new ParallelStateAction(stateDefinition);
27342
+ async executeParallelState(stateDefinition, rawInput, input, context, stateName, options) {
27343
+ const parallelStateAction = new ParallelStateAction(stateDefinition, stateName);
27300
27344
  const executionResult = await parallelStateAction.execute(input, context, {
27301
27345
  stateMachineOptions: options.stateMachineOptions,
27302
- runOptions: options.runOptions
27346
+ runOptions: options.runOptions,
27347
+ eventLogger: options.eventLogger,
27348
+ rawInput
27303
27349
  });
27304
27350
  return executionResult;
27305
27351
  }
@@ -27310,11 +27356,13 @@ var StateExecutor = class {
27310
27356
  * by the `ItemsPath` field, and then processes each item by passing it
27311
27357
  * as the input to the state machine specified in the `Iterator` field.
27312
27358
  */
27313
- async executeMapState(stateDefinition, input, context, stateName, options) {
27314
- const mapStateAction = new MapStateAction(stateDefinition);
27359
+ async executeMapState(stateDefinition, rawInput, input, context, stateName, options) {
27360
+ const mapStateAction = new MapStateAction(stateDefinition, stateName);
27315
27361
  const executionResult = await mapStateAction.execute(input, context, {
27316
27362
  stateMachineOptions: options.stateMachineOptions,
27317
- runOptions: options.runOptions
27363
+ runOptions: options.runOptions,
27364
+ eventLogger: options.eventLogger,
27365
+ rawInput
27318
27366
  });
27319
27367
  return executionResult;
27320
27368
  }
@@ -27324,8 +27372,8 @@ var StateExecutor = class {
27324
27372
  * If the `Result` field is specified, copies `Result` into the current result.
27325
27373
  * Else, copies the current input into the current result.
27326
27374
  */
27327
- async executePassState(stateDefinition, input, context, stateName, options) {
27328
- const passStateAction = new PassStateAction(stateDefinition);
27375
+ async executePassState(stateDefinition, rawInput, input, context, stateName, options) {
27376
+ const passStateAction = new PassStateAction(stateDefinition, stateName);
27329
27377
  const executionResult = await passStateAction.execute(input, context);
27330
27378
  return executionResult;
27331
27379
  }
@@ -27335,13 +27383,13 @@ var StateExecutor = class {
27335
27383
  * Pauses the state machine execution for a certain amount of time
27336
27384
  * based on one of the `Seconds`, `Timestamp`, `SecondsPath` or `TimestampPath` fields.
27337
27385
  */
27338
- async executeWaitState(stateDefinition, input, context, stateName, options) {
27386
+ async executeWaitState(stateDefinition, rawInput, input, context, stateName, options) {
27339
27387
  const waitTimeOverrideOption = options.runOptions?.overrides?.waitTimeOverrides?.[stateName];
27340
- const abortSignal = options.abortSignal;
27341
- const waitStateAction = new WaitStateAction(stateDefinition);
27388
+ const waitStateAction = new WaitStateAction(stateDefinition, stateName);
27342
27389
  const executionResult = await waitStateAction.execute(input, context, {
27343
27390
  waitTimeOverrideOption,
27344
- abortSignal
27391
+ abortSignal: options.abortSignal,
27392
+ rootAbortSignal: options.runOptions?._rootAbortSignal
27345
27393
  });
27346
27394
  return executionResult;
27347
27395
  }
@@ -27359,8 +27407,8 @@ var StateExecutor = class {
27359
27407
  * If no rule matches and the `Default` field is not specified, throws a
27360
27408
  * States.NoChoiceMatched error.
27361
27409
  */
27362
- async executeChoiceState(stateDefinition, input, context, stateName, options) {
27363
- const choiceStateAction = new ChoiceStateAction(stateDefinition);
27410
+ async executeChoiceState(stateDefinition, rawInput, input, context, stateName, options) {
27411
+ const choiceStateAction = new ChoiceStateAction(stateDefinition, stateName);
27364
27412
  const executionResult = await choiceStateAction.execute(input, context);
27365
27413
  return executionResult;
27366
27414
  }
@@ -27369,8 +27417,8 @@ var StateExecutor = class {
27369
27417
  *
27370
27418
  * Ends the state machine execution successfully.
27371
27419
  */
27372
- async executeSucceedState(stateDefinition, input, context, stateName, options) {
27373
- const succeedStateAction = new SucceedStateAction(stateDefinition);
27420
+ async executeSucceedState(stateDefinition, rawInput, input, context, stateName, options) {
27421
+ const succeedStateAction = new SucceedStateAction(stateDefinition, stateName);
27374
27422
  const executionResult = await succeedStateAction.execute(input, context);
27375
27423
  return executionResult;
27376
27424
  }
@@ -27379,13 +27427,186 @@ var StateExecutor = class {
27379
27427
  *
27380
27428
  * Ends the state machine execution and marks it as a failure.
27381
27429
  */
27382
- async executeFailState(stateDefinition, input, context, stateName, options) {
27383
- const failStateAction = new FailStateAction(stateDefinition);
27430
+ async executeFailState(stateDefinition, rawInput, input, context, stateName, options) {
27431
+ const failStateAction = new FailStateAction(stateDefinition, stateName);
27384
27432
  const executionResult = await failStateAction.execute(input, context);
27385
27433
  return executionResult;
27386
27434
  }
27387
27435
  };
27388
27436
 
27437
+ // src/stateMachine/EventLogger.ts
27438
+ var EventLogger = class {
27439
+ constructor() {
27440
+ this.eventTarget = new EventTarget();
27441
+ this.eventQueue = [];
27442
+ this.isLoggerClosed = false;
27443
+ }
27444
+ async *getEvents() {
27445
+ while (true) {
27446
+ if (this.eventQueue.length === 0) {
27447
+ await this.waitForNewEvent();
27448
+ }
27449
+ let event = null;
27450
+ while (event = this.eventQueue.shift()) {
27451
+ yield event;
27452
+ }
27453
+ if (this.isLoggerClosed)
27454
+ return;
27455
+ }
27456
+ }
27457
+ /**
27458
+ * Forward nested events created by `Map` states, to the root state machine event logger.
27459
+ * @param event An event dispatched by the nested state machine spawned by a `Map` state.
27460
+ * @param index Index of the current iteration being processed.
27461
+ * @param mapStateName Name of the `Map` state being executed.
27462
+ * @param mapStateRawInput Raw input passed to the `Map` state being executed.
27463
+ */
27464
+ forwardNestedMapEvent(event, index, mapStateName, mapStateRawInput) {
27465
+ switch (event.type) {
27466
+ case "ExecutionStarted":
27467
+ this.dispatchMapIterationStartedEvent(event, index, mapStateName, mapStateRawInput);
27468
+ break;
27469
+ case "ExecutionSucceeded":
27470
+ this.dispatchMapIterationSucceededEvent(event, index, mapStateName, mapStateRawInput);
27471
+ break;
27472
+ case "ExecutionFailed":
27473
+ this.dispatchMapIterationFailedEvent(event, index, mapStateName, mapStateRawInput);
27474
+ break;
27475
+ case "StateEntered":
27476
+ case "StateExited":
27477
+ event.index = index;
27478
+ this.dispatch(event);
27479
+ break;
27480
+ case "ExecutionAborted":
27481
+ case "ExecutionTimeout":
27482
+ return;
27483
+ default:
27484
+ this.dispatch(event);
27485
+ break;
27486
+ }
27487
+ }
27488
+ /**
27489
+ * Forward nested events created by `Parallel` states, to the root state machine event logger.
27490
+ * @param event An event dispatched by the nested state machines spawned by a `Parallel` state.
27491
+ * @param parallelStateName Name of the `Parallel` state being executed.
27492
+ * @param parallelStateRawInput Raw input passed to the `Parallel` state being executed.
27493
+ */
27494
+ forwardNestedParallelEvent(event, parallelStateName, parallelStateRawInput) {
27495
+ switch (event.type) {
27496
+ case "ExecutionStarted":
27497
+ this.dispatchParallelBranchStartedEvent(event, parallelStateName, parallelStateRawInput);
27498
+ break;
27499
+ case "ExecutionSucceeded":
27500
+ this.dispatchParallelBranchSucceededEvent(event, parallelStateName, parallelStateRawInput);
27501
+ break;
27502
+ case "ExecutionFailed":
27503
+ this.dispatchParallelBranchFailedEvent(event, parallelStateName, parallelStateRawInput);
27504
+ break;
27505
+ case "ExecutionAborted":
27506
+ case "ExecutionTimeout":
27507
+ return;
27508
+ default:
27509
+ this.dispatch(event);
27510
+ break;
27511
+ }
27512
+ }
27513
+ dispatchExecutionStartedEvent(input) {
27514
+ this.dispatch({ type: "ExecutionStarted", timestamp: Date.now(), input });
27515
+ }
27516
+ dispatchExecutionSucceededEvent(output) {
27517
+ this.dispatch({ type: "ExecutionSucceeded", timestamp: Date.now(), output });
27518
+ this.close();
27519
+ }
27520
+ dispatchExecutionFailedEvent(error) {
27521
+ this.dispatch({ type: "ExecutionFailed", timestamp: Date.now(), Error: error.name, Cause: error.message });
27522
+ this.close();
27523
+ }
27524
+ dispatchExecutionAbortedEvent() {
27525
+ this.dispatch({ type: "ExecutionAborted", timestamp: Date.now() });
27526
+ this.close();
27527
+ }
27528
+ dispatchExecutionTimeoutEvent() {
27529
+ this.dispatch({ type: "ExecutionTimeout", timestamp: Date.now() });
27530
+ this.close();
27531
+ }
27532
+ dispatchStateEnteredEvent(stateName, stateType, input) {
27533
+ this.dispatch({
27534
+ type: "StateEntered",
27535
+ timestamp: Date.now(),
27536
+ state: { name: stateName, type: stateType, input }
27537
+ });
27538
+ }
27539
+ dispatchStateExitedEvent(stateName, stateType, input, output) {
27540
+ this.dispatch({
27541
+ type: "StateExited",
27542
+ timestamp: Date.now(),
27543
+ state: { name: stateName, type: stateType, input, output }
27544
+ });
27545
+ }
27546
+ dispatchMapIterationStartedEvent(event, index, mapStateName, mapStateRawInput) {
27547
+ this.dispatch({
27548
+ ...event,
27549
+ type: "MapIterationStarted",
27550
+ index,
27551
+ parentState: { type: "Map", name: mapStateName, input: mapStateRawInput }
27552
+ });
27553
+ }
27554
+ dispatchMapIterationSucceededEvent(event, index, mapStateName, mapStateRawInput) {
27555
+ this.dispatch({
27556
+ ...event,
27557
+ type: "MapIterationSucceeded",
27558
+ index,
27559
+ parentState: { type: "Map", name: mapStateName, input: mapStateRawInput }
27560
+ });
27561
+ }
27562
+ dispatchMapIterationFailedEvent(event, index, mapStateName, mapStateRawInput) {
27563
+ this.dispatch({
27564
+ ...event,
27565
+ type: "MapIterationFailed",
27566
+ index,
27567
+ parentState: { type: "Map", name: mapStateName, input: mapStateRawInput }
27568
+ });
27569
+ }
27570
+ dispatchParallelBranchStartedEvent(event, parallelStateName, parallelStateRawInput) {
27571
+ this.dispatch({
27572
+ ...event,
27573
+ type: "ParallelBranchStarted",
27574
+ parentState: { type: "Parallel", name: parallelStateName, input: parallelStateRawInput }
27575
+ });
27576
+ }
27577
+ dispatchParallelBranchSucceededEvent(event, parallelStateName, parallelStateRawInput) {
27578
+ this.dispatch({
27579
+ ...event,
27580
+ type: "ParallelBranchSucceeded",
27581
+ parentState: { type: "Parallel", name: parallelStateName, input: parallelStateRawInput }
27582
+ });
27583
+ }
27584
+ dispatchParallelBranchFailedEvent(event, parallelStateName, parallelStateRawInput) {
27585
+ this.dispatch({
27586
+ ...event,
27587
+ type: "ParallelBranchFailed",
27588
+ parentState: { type: "Parallel", name: parallelStateName, input: parallelStateRawInput }
27589
+ });
27590
+ }
27591
+ close() {
27592
+ this.isLoggerClosed = true;
27593
+ this.eventTarget.dispatchEvent(new Event("newEvent"));
27594
+ }
27595
+ dispatch(event) {
27596
+ if (this.isLoggerClosed)
27597
+ return;
27598
+ this.eventQueue.push(event);
27599
+ this.eventTarget.dispatchEvent(new Event("newEvent"));
27600
+ }
27601
+ waitForNewEvent() {
27602
+ if (this.isLoggerClosed)
27603
+ return;
27604
+ return new Promise((resolve) => {
27605
+ this.eventTarget.addEventListener("newEvent", resolve, { once: true });
27606
+ });
27607
+ }
27608
+ };
27609
+
27389
27610
  // src/stateMachine/StateMachine.ts
27390
27611
  var import_asl_validator = __toESM(require_validator(), 1);
27391
27612
  var import_cloneDeep3 = __toESM(require_cloneDeep(), 1);
@@ -27397,14 +27618,16 @@ var StateMachine = class {
27397
27618
  * These options also apply to state machines defined in the `Iterator` field of `Map` states and in the `Branches` field of `Parallel` states.
27398
27619
  */
27399
27620
  constructor(definition, stateMachineOptions) {
27400
- const { isValid, errorsText } = (0, import_asl_validator.default)(definition, {
27401
- checkArn: true,
27402
- checkPaths: true,
27403
- ...stateMachineOptions?.validationOptions
27404
- });
27405
- if (!isValid) {
27406
- throw new Error(`State machine definition is invalid, see error(s) below:
27621
+ if (!stateMachineOptions?.validationOptions?._noValidate) {
27622
+ const { isValid, errorsText } = (0, import_asl_validator.default)(definition, {
27623
+ checkArn: true,
27624
+ checkPaths: true,
27625
+ ...stateMachineOptions?.validationOptions
27626
+ });
27627
+ if (!isValid) {
27628
+ throw new Error(`State machine definition is invalid, see error(s) below:
27407
27629
  ${errorsText("\n")}`);
27630
+ }
27408
27631
  }
27409
27632
  this.definition = definition;
27410
27633
  this.stateMachineOptions = stateMachineOptions;
@@ -27414,6 +27637,9 @@ var StateMachine = class {
27414
27637
  * If the execution fails, the result will throw an `ExecutionError` explaining why the
27415
27638
  * execution failed.
27416
27639
  *
27640
+ * If the execution times out because the number of seconds specified in
27641
+ * the `TimeoutSeconds` top-level field has elapsed, the result will throw an `ExecutionTimeoutError`.
27642
+ *
27417
27643
  * By default, if the execution is aborted, the result will throw an `ExecutionAbortedError`. This behavior can be changed by setting
27418
27644
  * the `noThrowOnAbort` option to `true`, in which case the result will be `null`.
27419
27645
  *
@@ -27422,30 +27648,47 @@ var StateMachine = class {
27422
27648
  */
27423
27649
  run(input, options) {
27424
27650
  const abortController = new AbortController();
27651
+ const eventLogger = new EventLogger();
27425
27652
  let onAbortHandler;
27426
27653
  const settleOnAbort = new Promise((resolve, reject) => {
27427
27654
  if (options?.noThrowOnAbort) {
27428
- onAbortHandler = () => resolve(null);
27655
+ onAbortHandler = () => {
27656
+ eventLogger.dispatchExecutionAbortedEvent();
27657
+ resolve(null);
27658
+ };
27429
27659
  } else {
27430
- onAbortHandler = () => reject(new ExecutionAbortedError());
27660
+ onAbortHandler = () => {
27661
+ eventLogger.dispatchExecutionAbortedEvent();
27662
+ reject(new ExecutionAbortedError());
27663
+ };
27431
27664
  }
27432
27665
  abortController.signal.addEventListener("abort", onAbortHandler);
27433
27666
  });
27434
- let rejectOnTimeout = null;
27435
- if (this.definition.TimeoutSeconds) {
27667
+ let rejectOnTimeout;
27668
+ let timeoutId;
27669
+ if (this.definition.TimeoutSeconds !== void 0) {
27436
27670
  rejectOnTimeout = new Promise((_, reject) => {
27437
- setTimeout(() => {
27671
+ timeoutId = setTimeout(() => {
27438
27672
  abortController.signal.removeEventListener("abort", onAbortHandler);
27439
27673
  abortController.abort();
27440
- reject(new StatesTimeoutError());
27674
+ eventLogger.dispatchExecutionTimeoutEvent();
27675
+ reject(new ExecutionTimeoutError());
27441
27676
  }, this.definition.TimeoutSeconds * 1e3);
27442
27677
  });
27443
27678
  }
27444
- const executionResult = this.execute(input, {
27445
- stateMachineOptions: this.stateMachineOptions,
27446
- runOptions: options,
27447
- abortSignal: abortController.signal
27448
- });
27679
+ const executionResult = this.execute(
27680
+ input,
27681
+ {
27682
+ stateMachineOptions: this.stateMachineOptions,
27683
+ runOptions: { ...options, _rootAbortSignal: options?._rootAbortSignal ?? abortController.signal },
27684
+ abortSignal: abortController.signal,
27685
+ eventLogger
27686
+ },
27687
+ () => {
27688
+ abortController.signal.removeEventListener("abort", onAbortHandler);
27689
+ clearTimeout(timeoutId);
27690
+ }
27691
+ );
27449
27692
  const racingPromises = [executionResult, settleOnAbort];
27450
27693
  if (rejectOnTimeout) {
27451
27694
  racingPromises.push(rejectOnTimeout);
@@ -27453,38 +27696,46 @@ var StateMachine = class {
27453
27696
  const result = Promise.race(racingPromises);
27454
27697
  return {
27455
27698
  abort: () => abortController.abort(),
27699
+ eventLogs: eventLogger.getEvents(),
27456
27700
  result
27457
27701
  };
27458
27702
  }
27459
27703
  /**
27460
27704
  * Helper method that handles the execution of the machine states and the transitions between them.
27461
27705
  */
27462
- async execute(input, options) {
27706
+ async execute(input, options, cleanupFn) {
27707
+ options.eventLogger.dispatchExecutionStartedEvent(input);
27708
+ const context = options.runOptions?.context ?? {};
27463
27709
  let currState = this.definition.States[this.definition.StartAt];
27464
27710
  let currStateName = this.definition.StartAt;
27465
27711
  let currInput = (0, import_cloneDeep3.default)(input);
27466
27712
  let currResult = null;
27467
27713
  let nextState = "";
27468
27714
  let isEndState = false;
27469
- let context = {};
27470
27715
  try {
27471
27716
  do {
27717
+ options.eventLogger.dispatchStateEnteredEvent(currStateName, currState.Type, currInput);
27472
27718
  const stateExecutor = new StateExecutor(currStateName, currState);
27473
27719
  ({ stateResult: currResult, nextState, isEndState } = await stateExecutor.execute(currInput, context, options));
27720
+ options.eventLogger.dispatchStateExitedEvent(currStateName, currState.Type, currInput, currResult);
27474
27721
  currInput = currResult;
27475
27722
  currState = this.definition.States[nextState];
27476
27723
  currStateName = nextState;
27477
27724
  } while (!isEndState && !options.abortSignal.aborted);
27478
27725
  } catch (error) {
27726
+ options.eventLogger.dispatchExecutionFailedEvent(error);
27479
27727
  throw new ExecutionError(error);
27728
+ } finally {
27729
+ cleanupFn();
27480
27730
  }
27731
+ options.eventLogger.dispatchExecutionSucceededEvent(currResult);
27481
27732
  return currResult;
27482
27733
  }
27483
27734
  };
27484
27735
  export {
27485
27736
  ExecutionAbortedError,
27486
27737
  ExecutionError,
27487
- StatesTimeoutError as ExecutionTimeoutError,
27738
+ ExecutionTimeoutError,
27488
27739
  StateMachine
27489
27740
  };
27490
27741
  /*! Bundled license information: