# Mistakes caught before a journey

## What you want to do

The shop's workflow is now put together from many parts: steps and their names, policies attached to them, an input adapter, services and their providers, a rescue step and roles. You want to see how it is put together without running an order, and to know that a mistake in putting it together is caught before any order runs.

## The code

### How the workflow is put together

The shop is the one [chapter 36](https://itinera-dev.org/book/typescript/36-orders-refused-before-they-start.md) runs; its workflow class is [chapter 23](https://itinera-dev.org/book/typescript/23-undoing-a-charge-when-the-shipping-fails.md)'s, with the role implementations of [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md) and [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md)'s provider for `cards`. The program prints its **listing**, which `Orders.listing()` reads from the workflow's declaration, one entry for each step:

TypeScript, from the program [`ch37_listing`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch37_listing.ts)

```typescript
for (const listed of Orders.listing()) {
  console.log(entry(listed));
}
```

`entry` writes each step's line from what the listing says about it, and `services`, with `served` for each one, writes the services of a step or of its rescue step. The entries are `ListedStep`s, and their services `ListedService`s, both types from `itinera/workflow`:

TypeScript, from the program [`ch37_listing`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch37_listing.ts)

```typescript
/** A service in the listing: its key, and the provider that serves it. */
function served(listed: ListedService): string {
  return `${listed.key} from ${listed.provider}`;
}

/** The services of a listing's entry, separated by commas. */
function services(listed: readonly ListedService[]): string {
  return listed.map(served).join(", ");
}

/**
 * One entry of the listing: a step's position and name, its policies, its
 * adapter, its services with the provider that serves each, and its rescue
 * step with its services.
 */
function entry(listed: ListedStep): string {
  let line = `${String(listed.position)}. ${listed.step}`;
  if (listed.policies.length > 0) {
    line += `, with ${listed.policies.join(", ")}`;
  }
  if (listed.adapter !== undefined) {
    line += `; adapted by ${listed.adapter}`;
  }
  if (listed.services.length > 0) {
    line += `; services: ${services(listed.services)}`;
  }
  if (listed.rescue !== undefined) {
    line += `; rescued by ${listed.rescue.step}, services: ${services(listed.rescue.services)}`;
  }
  return line;
}
```

It prints:

What `ch37_listing` prints, recorded in [`ch37_listing.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch37_listing.txt)

```text
1. lookup, with alreadyCompleted; services: orderBook from ledger
2. price
3. charge, with audit, outage; services: payments from bank; rescued by charge_rescue, services: cards from cards
4. ship, with failedShipping; adapted by parcels; services: carrier from carriers
```

### Mistakes found as the class is defined

This small shop has steps and policies of its own:

TypeScript, from the program [`ch37_violations`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch37_violations.ts)

```typescript
/** Charges an order, and gives back the amount it charged. */
@step()
class Charge extends Step {
  override run(@contributor() contributor: Contributor): Outcome {
    contributor.contribute("charged", 40);
    return this.succeed();
  }
}

/** Ships an order. */
@step()
class Ship extends Step {
  override run(): Outcome {
    return this.succeed();
  }
}

/** Audits every successful charge. */
@stepPolicy({ name: "audit" })
class Audit extends StepPolicy {
  @onStepSuccess()
  audited(@fromStep("charged", integer) charged: number): OnSuccess {
    console.log(`audit: charged ${String(charged)}`);
    return this.keepDefault();
  }
}

/** Writes a receipt for every successful charge. */
@stepPolicy({ name: "receipts" })
class Receipts extends StepPolicy {
  @onStepSuccess()
  written(@fromStep("charged", integer) charged: number): OnSuccess {
    console.log(`receipt: R-${String(charged)}`);
    return this.keepDefault();
  }
}
```

Its workflow is put together with two mistakes: both policies are attached to the charge, though both define `on step success`, and the shipping is listed twice. The decorators check the class as it is defined, so a mistake stops a program as it loads, before its first order. To print what they found, this program defines the class inside a function, `defineOrders`:

TypeScript, from the program [`ch37_violations`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch37_violations.ts)

```typescript
/**
 * Defines the shop's workflow, with both policies attached to the charge and
 * the shipping listed twice.
 */
function defineOrders(): void {
  @workflow({ name: "orders" })
  @withStep(Charge, { name: "charge", policies: [Audit, Receipts] })
  @withStep(Ship, { name: "ship" })
  @withStep(Ship, { name: "ship", retryBudget: 1 })
  class Orders extends Workflow {}
}
```

It calls the function, and catches what the decorators throw:

TypeScript, from the program [`ch37_violations`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch37_violations.ts)

```typescript
try {
  defineOrders();
} catch (error) {
  if (!(error instanceof Violations)) throw error;
  console.log("the workflow was refused:");
  console.log(error.message);
}
```

It prints:

What `ch37_violations` prints, recorded in [`ch37_violations.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch37_violations.txt)

```text
the workflow was refused:
duplicate step name: ship
hook defined twice: on step success on step charge
```

### Mistakes that don't compile

Each program below is a small shop with one mistake, and none of them compiles. A policy that tells the customer through the `Messages` role, on a workflow that can't tell anyone anything:

TypeScript, the program [`ch37_role_not_provided`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_role_not_provided.ts). **Does not compile**

```typescript
// A policy that needs a role the workflow does not provide.

import { LocalExecutor } from "itinera/executor";
import {
  onWorkflowSuccess,
  role,
  WorkflowPolicy,
  workflowPolicy,
} from "itinera/policy";
import { type Outcome, Step, step } from "itinera/step";
import { string } from "itinera/value";
import { fromWorkflow, withStep, Workflow, workflow } from "itinera/workflow";

/** Charges an order. */
@step()
class Charge extends Step {
  override run(): Outcome {
    return this.succeed();
  }
}

/** The shop's way of telling a customer something. */
interface Messages {
  tell(customer: string, message: string): void;
}

/** Tells the customer once the order is complete. */
@workflowPolicy({ name: "notify" })
class Notify extends WorkflowPolicy<Messages> {
  @onWorkflowSuccess()
  completed(
    @fromWorkflow("customer", string) customer: string,
    @role<Messages>() messages: Messages,
  ): void {
    messages.tell(customer, "your order is complete");
  }
}

/** The shop's workflow, which has no way of telling a customer anything. */
@workflow({ name: "orders", policies: [Notify] })
@withStep(Charge, { name: "charge" })
class Orders extends Workflow {}

const result = await new LocalExecutor().run(
  Orders.build().instance({ customer: "Ann" }),
);
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_role_not_provided`, recorded in [`ch37_role_not_provided.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_role_not_provided.txt)

```text
compile-errors/ch37_role_not_provided.ts(40,2): error TS1238: Unable to resolve signature of class decorator when called as an expression.
  Argument of type 'typeof Orders' is not assignable to parameter of type 'WorkflowClass<Messages>'.
    Type 'Orders' is not assignable to type 'Workflow & Messages'.
      Property 'tell' is missing in type 'Workflow' but required in type 'Messages'.
```

An `on step failure` hook that tries to finish the journey as succeeded, which only `on step success` may do:

TypeScript, the program [`ch37_invalid_lifecycle`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_invalid_lifecycle.ts). **Does not compile**

```typescript
// A hook that returns a lifecycle it may not return: finishing the journey
// after a failure.

import { LocalExecutor } from "itinera/executor";
import {
  onStepFailure,
  type OnFailure,
  StepPolicy,
  stepPolicy,
} from "itinera/policy";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

/** Charges an order, and fails when there is nothing to charge. */
@step()
class Charge extends Step {
  override run(): Outcome {
    return this.fail("nothing-to-charge");
  }
}

/** Tries to end the journey as succeeded when the charge fails. */
@stepPolicy({ name: "forgive" })
class Forgive extends StepPolicy {
  @onStepFailure()
  forgiven(): OnFailure {
    return this.finishWorkflow();
  }
}

/** The shop's workflow. */
@workflow({ name: "orders" })
@withStep(Charge, { name: "charge", policies: [Forgive] })
class Orders extends Workflow {}

const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_invalid_lifecycle`, recorded in [`ch37_invalid_lifecycle.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_invalid_lifecycle.txt)

```text
compile-errors/ch37_invalid_lifecycle.ts(27,5): error TS2322: Type 'FinishWorkflow' is not assignable to type 'OnFailure'.
  Type 'FinishWorkflow' is not assignable to type 'KeepDefault'.
    Types of property 'kind' are incompatible.
      Type '"FinishWorkflow"' is not assignable to type '"KeepDefault"'.
```

A step that contributes its connection to the bank, which isn't a value:

TypeScript, the program [`ch37_not_a_value`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_not_a_value.ts). **Does not compile**

```typescript
// A step that contributes something that is not a value: its connection to
// the bank.

import { LocalExecutor } from "itinera/executor";
import { type Contributor, contributor } from "itinera/journey";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

/** A connection to the customer's bank, faked. */
class BankConnection {
  constructor(readonly bank: string) {}

  charge(amount: number): string {
    return `${this.bank} charged ${String(amount)}`;
  }
}

/** Charges an order, and hands its bank connection on. */
@step()
class Charge extends Step {
  override run(@contributor() contributor: Contributor): Outcome {
    const connection = new BankConnection("the customer's bank");
    contributor.contribute("bank", connection);
    return this.succeed();
  }
}

/** The shop's workflow. */
@workflow({ name: "orders" })
@withStep(Charge, { name: "charge" })
class Orders extends Workflow {}

const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_not_a_value`, recorded in [`ch37_not_a_value.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_not_a_value.txt)

```text
compile-errors/ch37_not_a_value.ts(23,36): error TS2345: Argument of type 'BankConnection' is not assignable to parameter of type 'BankConnection & { readonly bank: string; readonly charge: never; }'.
  Type 'BankConnection' is not assignable to type '{ readonly bank: string; readonly charge: never; }'.
    Types of property 'charge' are incompatible.
      Type '(amount: number) => string' is not assignable to type 'never'.
```

A rescue step that tries to skip the charge rather than repair it:

TypeScript, the program [`ch37_rescue_step_skips`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_rescue_step_skips.ts). **Does not compile**

```typescript
// A rescue step that tries to skip the step it rescues.

import { LocalExecutor } from "itinera/executor";
import {
  type Outcome,
  RescueStep,
  rescueStep,
  type RescueOutcome,
  Step,
  step,
} from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

/** Charges an order, and fails when its card has expired. */
@step()
class Charge extends Step {
  override run(): Outcome {
    return this.fail("card-expired");
  }
}

/** Tries to skip the charge rather than repair it. */
@rescueStep()
class RenewCard extends RescueStep {
  override run(): RescueOutcome {
    return this.skipBecause("no-card-to-renew");
  }
}

/** The shop's workflow. */
@workflow({ name: "orders" })
@withStep(Charge, { name: "charge", rescue: RenewCard })
class Orders extends Workflow {}

const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_rescue_step_skips`, recorded in [`ch37_rescue_step_skips.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_rescue_step_skips.txt)

```text
compile-errors/ch37_rescue_step_skips.ts(26,17): error TS2339: Property 'skipBecause' does not exist on type 'RenewCard'.
```

A provider that returns the bank as it is, rather than through `this.provide(...)`:

TypeScript, the program [`ch37_provider_without_provide`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_provider_without_provide.ts). **Does not compile**

```typescript
// A provider that returns its service itself, rather than through
// `this.provide(...)`.

import { LocalExecutor } from "itinera/executor";
import { provider, service, serviceType } from "itinera/service";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

/** A payment client: it charges an amount, and gives back a receipt. */
interface Payments {
  charge(amount: number): string;
}

const PAYMENTS = serviceType<Payments>("Payments");

/** The shop's bank, faked. */
class Bank implements Payments {
  charge(amount: number): string {
    return `R-${String(amount)}`;
  }
}

/** Charges an order through the payment client. */
@step()
class Charge extends Step {
  override run(@service("payments", PAYMENTS) payments: Payments): Outcome {
    payments.charge(30);
    return this.succeed();
  }
}

/** The shop's workflow, whose provider hands the bank over as it is. */
@workflow({ name: "orders" })
@withStep(Charge, { name: "charge" })
class Orders extends Workflow {
  @provider(PAYMENTS, { key: "payments" })
  bank(): Payments {
    return new Bank();
  }
}

const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_provider_without_provide`, recorded in [`ch37_provider_without_provide.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_provider_without_provide.txt)

```text
compile-errors/ch37_provider_without_provide.ts(36,4): error TS1241: Unable to resolve signature of method decorator when called as an expression.
  Argument of type 'TypedPropertyDescriptor<() => Payments>' is not assignable to parameter of type 'TypedPropertyDescriptor<(...requests: never[]) => Provided<Payments> | Promise<Provided<Payments>>>'.
    Types of property 'value' are incompatible.
      Type '(() => Payments) | undefined' is not assignable to type '((...requests: never[]) => Provided<Payments> | Promise<Provided<Payments>>) | undefined'.
        Type '() => Payments' is not assignable to type '(...requests: never[]) => Provided<Payments> | Promise<Provided<Payments>>'.
          Type 'Payments' is not assignable to type 'Provided<Payments> | Promise<Provided<Payments>>'.
```

An input adapter that asks for the data bag, as the ID generator of [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md) does, and tries to write the weight into it:

TypeScript, the program [`ch37_adapter_writes_the_data_bag`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_adapter_writes_the_data_bag.ts). **Does not compile**

```typescript
// An input adapter that tries to write into the data bag, which it may only
// read.

import { LocalExecutor } from "itinera/executor";
import { type DataBag, dataBag } from "itinera/journey";
import { input, type Outcome, Step, step } from "itinera/step";
import { integer } from "itinera/value";
import {
  inputAdapter,
  key,
  type Supplied,
  withStep,
  Workflow,
  workflow,
} from "itinera/workflow";

/** Ships an order, which has to weigh something. */
@step()
class Ship extends Step {
  constructor(@input("weight", integer) private readonly weight: number) {
    super();
  }

  override run(): Outcome {
    if (this.weight <= 0) return this.fail("weighs-nothing");
    return this.succeed();
  }
}

/** The shop's workflow, whose adapter writes the weight it supplies. */
@workflow({ name: "orders" })
@withStep(Ship, { name: "ship" })
class Orders extends Workflow {
  @inputAdapter({ steps: ["ship"] })
  parcels(@key() key: string, @dataBag() data: DataBag): Supplied {
    if (key !== "weight") return this.fromDataBag();
    data.write("weight", 1);
    return this.supply(1);
  }
}

const result = await new LocalExecutor().run(Orders.build().instance());
console.log(`the journey ${result.status.kind}`);
```

What the compiler says about `ch37_adapter_writes_the_data_bag`, recorded in [`ch37_adapter_writes_the_data_bag.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_adapter_writes_the_data_bag.txt)

```text
compile-errors/ch37_adapter_writes_the_data_bag.ts(37,10): error TS2339: Property 'write' does not exist on type 'DataBag'.
```

A journey run without awaiting its result:

TypeScript, the program [`ch37_result_not_awaited`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_result_not_awaited.ts). **Does not compile**

```typescript
// A journey run without awaiting its result.

import { LocalExecutor } from "itinera/executor";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

/** Charges an order. */
@step()
class Charge extends Step {
  override run(): Outcome {
    return this.succeed();
  }
}

/** The shop's workflow. */
@workflow({ name: "orders" })
@withStep(Charge, { name: "charge" })
class Orders extends Workflow {}

const result = new LocalExecutor().run(Orders.build().instance());
if (result.isSucceeded()) console.log("the journey succeeded");
```

What the compiler says about `ch37_result_not_awaited`, recorded in [`ch37_result_not_awaited.txt`](https://github.com/itinera-dev/book/blob/main/typescript/compile-errors/ch37_result_not_awaited.txt)

```text
compile-errors/ch37_result_not_awaited.ts(21,12): error TS2339: Property 'isSucceeded' does not exist on type 'Promise<JourneyResult>'.
```

## How it works

1. **The listing says how the workflow is put together.** It lists each step in order, with its position, the policies attached to it, its input adapter, each service it asks for with the provider that serves it, and its rescue step with that step's own services. It is read from the declaration: nothing runs, no provider is called, and no workflow object is made, so `listing` is called on the class itself. The listing alone shows, for example, that the card registry serves `charge_rescue` and nothing else.
2. **A mistake in putting a workflow together is a violation.** Checking how a workflow is put together, before any journey, is called **admission**, and the specification names each mistake it catches: `duplicate step name`, `hook defined twice`, `service not provided`, `rescued step retried` and a few more, all listed in [3.6, Configuration errors](https://github.com/itinera-dev/spec/blob/main/spec/03-workflow-definitions.md#36-configuration-errors). **Every violation found is reported at once, not only the first.**
3. **With the decorators, a violation is thrown as the class is defined.** `@workflow` checks the whole declaration as the class statement runs, and throws a `Violations`, from `itinera/workflow`, an `Error` whose message has one line for each violation, as the specification names it. A class defined at the top of a module, as the shop's is, is defined as the module loads, so the program stops there: no order can run on a workflow put together wrongly. The program checks that what it caught is a `Violations`, and throws anything else on.
4. **Some mistakes can't be written at all.** TypeScript's types rule out the seven that don't compile. A workflow policy that asks for a [role](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md) compiles only on a workflow class that has the role's methods. Each hook's return type lists only the [lifecycles](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md) that hook may return, so `OnFailure` holds no `FinishWorkflow`. A contribution must be a value, as [chapter 6](https://itinera-dev.org/book/typescript/06-passing-data-on.md) said, and an object with a method isn't one. A `RescueOutcome` is never a skip, as [chapter 14](https://itinera-dev.org/book/typescript/14-repairing-then-trying-once-more.md) said, so a rescue step has no `skipBecause`. A provider returns what [`this.provide(...)`](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md) makes, never the bare service. A `DataBag` has methods that read and none that write, since an adapter reads and never writes, as [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md) said. And [`run`](https://itinera-dev.org/book/typescript/05-a-first-journey.md) returns a promise, which has no [`isSucceeded`](https://itinera-dev.org/book/typescript/25-reading-the-result.md) until it is awaited.

The violations are caught because the decorators write the workflow's declaration for you, and check it as they write it. But you haven't seen what they write.

## Outcomes

We have shown how the listing says how a workflow is put together, and how a mistake in putting it together is caught before any order runs.

| The usual way                                                                                                        | With Itinera                                                                              |
| -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Which hooks run after a step, or which client serves a repair, is often learned only by reading every module.        | The listing names each step's policies, its adapter, and the services of its rescue step. |
| A wiring mistake, such as two handlers for one event, often shows only when a request takes that path in production. | The program doesn't compile, or stops as it loads, and the message names every mistake.   |
