# Declaring by hand

## What you want to do

The decorators have declared the shop's workflow since the first chapters, and checked it. You want to see what they stand for, and to write part of the shop without them: for a compiler that records no decorator metadata, for a declaration put together as the program starts, or to have its mistakes reported where you choose.

## The code

### The shop by hand

The shop is the one [chapter 36](https://itinera-dev.org/book/typescript/36-orders-refused-before-they-start.md) runs, declared in the **long form**: with the builder rather than the decorators, for its pricing step, its audit and its workflow. The pricing is [chapter 20](https://itinera-dev.org/book/typescript/20-an-optional-input.md)'s class without decorators. Its builder, `Price.builder("price")`, takes its requests in order: `needs` one for each parameter of the constructor, and `run` one for each of `run`'s, each made by the decorator's own function, such as `input("discount", optional(integer))` or `contributor()`:

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

```typescript
/**
 * Works out what an order costs: its price, less its discount if it has one,
 * given back as the amount to charge.
 */
class Price extends Step {
  constructor(
    private readonly price: number,
    private readonly discount: Option<number>,
  ) {
    super();
  }

  override run(contributor: Contributor): Outcome {
    contributor.contribute("amount", this.price - this.discount.unwrapOr(0));
    return this.succeed();
  }
}

/** The pricing, under its name, with the requests of its parameters. */
const pricing = Price.builder("price")
  .needs(input("price", integer), input("discount", optional(integer)))
  .run(contributor());
```

The audit is [chapter 34](https://itinera-dev.org/book/typescript/34-saying-which-attempt-took-the-money.md)'s class without decorators. Its builder names the policy, and `onStepSuccess` makes its method `charged` the hook, with a request for each parameter, in order:

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

```typescript
/**
 * Writes an audit line for every step it is attached to that succeeds: the
 * journey, the attempt that took the money, the amount the order was charged,
 * and the receipt the step gave back.
 */
class Audit extends StepPolicy {
  charged(
    journey: JourneyId,
    step: StepName,
    attempt: Attempt,
    amount: number,
    receipt: string,
    contributor: Contributor,
  ): OnSuccess {
    contributor.contribute(
      "audit",
      `${journey}: ${step} took ${String(amount)} on attempt ${String(attempt)}, receipt ${receipt}`,
    );
    return this.keepDefault();
  }
}

/** The audit, under its name, with its hook and the requests of its parameters. */
const audit = Audit.builder("audit").onStepSuccess(
  "charged",
  journeyId(),
  stepName(),
  attempt(),
  fromWorkflow("amount", integer),
  fromStep("receipt", string),
  contributor(),
);
```

`Orders` keeps the role implementations of [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md), and its ID generator, input adapter and providers are plain methods now:

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

```typescript
/**
 * The shop's workflow class: the roles its policies ask for, through the
 * channel the shop configures, and the methods that name its journeys,
 * adapt the shipping's inputs and provide its services.
 */
class Orders extends Workflow implements Messages, Refunds {
  constructor(private readonly channel: string) {
    super();
  }

  async tell(customer: string, message: string): Promise<void> {
    await network();
    console.log(`${this.channel} to ${customer}: ${message}`);
  }

  async refund(receipt: string, amount: number): Promise<void> {
    await network();
    console.log(`the bank gives ${String(amount)} back on receipt ${receipt}`);
  }

  /** Names each journey after its order. */
  orderNumber(data: DataBag): string {
    return data.read("order", string).option().expect("the order's number");
  }

  /**
   * Gives the shipping the weight of the order's parcel, as the warehouse
   * describes it. Every other input of the shipping is read from the data bag.
   */
  parcels(key: string, parcel: Parcel): Supplied {
    if (key !== "weight") return this.fromDataBag();
    return this.supply(parcel.weight);
  }

  /** The bank, as the payment client of the journey. */
  bank(): Provided<Payments> {
    return this.provide(new Bank(2026));
  }

  /**
   * A carrier for every attempt of a step: the main carrier first, the backup
   * carrier after.
   */
  carriers(attempt: Attempt): Provided<Carrier> {
    if (attempt.isFirst()) return this.provide(new MainCarrier());
    return this.provide(new BackupCarrier());
  }

  /** The bank's card registry in Europe, for the charge's rescue step only. */
  cards(): Provided<Cards> {
    return this.provide(cardRegistry("eu"), "eu");
  }

  /** The order book, which has the orders completed before today. */
  ledger(): Provided<OrderBook> {
    return this.provide(new Ledger(["A-13"]));
  }
}
```

`Parcel` and `PARCEL` are [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s, `OrderBook` is [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md)'s, `Carrier`, `Messages`, `Refunds` and `network` are [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md)'s, and `Payments`, `Cards`, `CARDS` and `cardRegistry` are [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md)'s, with the tokens `PAYMENTS` and `CARRIER` of [chapter 7](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md) and `ORDER_BOOK` of [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md).

And `Orders.builder()` puts the workflow together, part by part. The other steps and policies keep their decorators: each goes in as its class, a step through its own builder, which reads its requests from them. A method of `Orders` is named, followed by its requests:

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

```typescript
/**
 * The shop's workflow: it looks the order up, and finishes an order already
 * completed. Otherwise it works out what the order costs, then charges it,
 * repairing a charge that fails and auditing one that succeeds, then ships,
 * and shipping may be tried once more, its charge refunded if it is given up.
 * Once a journey has ended, the customer is told, through the channel the shop
 * configures.
 */
const shop = Orders.builder()
  .name("orders")
  .reporter(Log)
  .reporter(Desk)
  .policy(Notify)
  .step(Lookup.builder("lookup").policy(AlreadyCompleted))
  .step(pricing)
  .step(Charge.builder("charge").rescue(RenewCard).policy(audit).policy(Outage))
  .step(Ship.builder("ship").retryBudget(1).policy(FailedShipping))
  .idGenerator("orderNumber", dataBag())
  .inputAdapter(
    "parcels",
    { steps: ["ship"] },
    key(),
    fromWorkflow("parcel", PARCEL),
  )
  .provider("bank", PAYMENTS, { key: "payments" })
  .provider(
    "carriers",
    CARRIER,
    { key: "carrier", perAttempt: true },
    attempt(),
  )
  .provider("cards", CARDS, { key: "cards", steps: ["charge_rescue"] })
  .provider("ledger", ORDER_BOOK, { key: "orderBook" })
  .constructWith("email")
  .build();
```

The rest is as earlier chapters show it: the lookup and `AlreadyCompleted` in [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md), the charge in [chapter 33](https://itinera-dev.org/book/typescript/33-giving-every-reporter-what-it-needs.md), `RenewCard` in [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md), the shipping, `Notify` and `FailedShipping` in [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md), `Outage` in [chapter 34](https://itinera-dev.org/book/typescript/34-saying-which-attempt-took-the-money.md), the log in [chapter 33](https://itinera-dev.org/book/typescript/33-giving-every-reporter-what-it-needs.md), [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md) and [chapter 36](https://itinera-dev.org/book/typescript/36-orders-refused-before-they-start.md), and the desk in [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md).

`shop` replaces `Orders.build("email")`, and each order's instance is made from it as [chapter 33](https://itinera-dev.org/book/typescript/33-giving-every-reporter-what-it-needs.md) shows, its result followed up by [chapter 34](https://itinera-dev.org/book/typescript/34-saying-which-attempt-took-the-money.md)'s `followUp`. The program runs Ann's order and Jo's, and prints:

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

```text
Ann's order:
log orders A-1 for Ann #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 for Ann #2 attempt_started lookup, attempt 1
log orders A-1 for Ann #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-1 yet
log orders A-1 for Ann #4 step_succeeded lookup
log orders A-1 for Ann #5 contribution_committed completed
log orders A-1 for Ann #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 for Ann #7 attempt_started price, attempt 1
log orders A-1 for Ann #8 step_succeeded price
log orders A-1 for Ann #9 contribution_committed amount
log orders A-1 for Ann #10 attempt_started charge, attempt 1
log orders A-1 for Ann #11 service_provided charge gets payments from bank, a Bank
the bank charges 30 for order A-1
log orders A-1 for Ann, receipt R-A-1 #12 global_metadata_set receipt
log orders A-1 for Ann, receipt R-A-1 #13 step_succeeded charge
log orders A-1 for Ann, receipt R-A-1 #14 contribution_committed receipt
log orders A-1 for Ann, receipt R-A-1 #15 hook_called audit: on step success of charge
log orders A-1 for Ann, receipt R-A-1 #16 contribution_committed audit
log orders A-1 for Ann, receipt R-A-1 #17 attempt_started ship, attempt 1
log orders A-1 for Ann, receipt R-A-1 #18 input_adapter_supplied ship gets weight from parcels
log orders A-1 for Ann, receipt R-A-1 #19 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-1
log orders A-1 for Ann, receipt R-A-1 #20 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 for Ann, receipt R-A-1 #21 step_succeeded ship
log orders A-1 for Ann, receipt R-A-1 #22 contribution_committed tracking
log orders A-1 for Ann, receipt R-A-1 #23 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 for Ann, receipt R-A-1 #24 hook_called notify: on workflow success
log orders A-1 for Ann, receipt R-A-1 #25 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: A-1: charge took 30 on attempt 1, receipt R-A-1
Jo's order:
log orders A-8 for Jo #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 for Jo #2 attempt_started lookup, attempt 1
log orders A-8 for Jo #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-8 yet
log orders A-8 for Jo #4 step_succeeded lookup
log orders A-8 for Jo #5 contribution_committed completed
log orders A-8 for Jo #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 for Jo #7 attempt_started price, attempt 1
log orders A-8 for Jo #8 optional_input_absent discount
log orders A-8 for Jo #9 step_succeeded price
log orders A-8 for Jo #10 contribution_committed amount
log orders A-8 for Jo #11 attempt_started charge, attempt 1
log orders A-8 for Jo #12 service_provided charge gets payments from bank, a Bank
the bank declines card jo-2024: it has expired
log orders A-8 for Jo #13 step_failed charge: card-expired
log orders A-8 for Jo #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 for Jo #15 attempt_started charge_rescue, attempt 1
log orders A-8 for Jo #16 service_provided charge_rescue gets cards from cards, a Cards, with eu
the card registry in eu says card jo-2024 was replaced by jo-2029
log orders A-8 for Jo #17 step_succeeded charge_rescue
log orders A-8 for Jo #18 contribution_committed card
log orders A-8 for Jo #19 data_overwritten card
log orders A-8 for Jo #20 step_rescued charge by charge_rescue
log orders A-8 for Jo #21 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 for Jo, receipt R-A-8 #22 global_metadata_set receipt
log orders A-8 for Jo, receipt R-A-8 #23 step_succeeded charge
log orders A-8 for Jo, receipt R-A-8 #24 contribution_committed receipt
log orders A-8 for Jo, receipt R-A-8 #25 hook_called audit: on step success of charge
log orders A-8 for Jo, receipt R-A-8 #26 contribution_committed audit
log orders A-8 for Jo, receipt R-A-8 #27 attempt_started ship, attempt 1
log orders A-8 for Jo, receipt R-A-8 #28 input_adapter_supplied ship gets weight from parcels
log orders A-8 for Jo, receipt R-A-8 #29 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-8
log orders A-8 for Jo, receipt R-A-8 #30 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 for Jo, receipt R-A-8 #31 step_succeeded ship
log orders A-8 for Jo, receipt R-A-8 #32 contribution_committed tracking
log orders A-8 for Jo, receipt R-A-8 #33 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 for Jo, receipt R-A-8 #34 hook_called notify: on workflow success
log orders A-8 for Jo, receipt R-A-8 #35 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: A-8: charge took 30 on attempt 2, receipt R-A-8
```

### A workflow put together wrongly

This small shop is declared by hand throughout, and `charge()` and `ship()` start a step's builder:

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

```typescript
/** Charges an order's price, and gives back the amount it charged. */
class Charge extends Step {
  constructor(private readonly price: number) {
    super();
  }

  override run(contributor: Contributor): Outcome {
    if (this.price <= 0) return this.fail("nothing-to-charge");
    contributor.contribute("charged", this.price);
    return this.succeed();
  }
}

/** Ships an order's parcel, of this weight in kg, up to the shop's limit. */
class Ship extends Step {
  constructor(private readonly weight: number) {
    super();
  }

  override run(): Outcome {
    if (this.weight > 80) return this.fail("over-parcel-limit");
    return this.succeed();
  }
}

/** Audits every successful charge. */
class Audit extends StepPolicy {
  audited(charged: number, contributor: Contributor): OnSuccess {
    contributor.contribute("audit", `charged ${String(charged)}`);
    return this.keepDefault();
  }
}

/** Writes a receipt for every successful charge. */
class Receipts extends StepPolicy {
  written(charged: number, contributor: Contributor): OnSuccess {
    contributor.contribute("receipt", `R-${String(charged)}`);
    return this.keepDefault();
  }
}

/**
 * How the warehouse describes an order's parcel: its weight in kg, and its
 * length, width and height in cm.
 */
interface Parcel {
  weight: number;
  size: number[];
}

/** The type token of a parcel. */
const PARCEL = objectOf({ weight: integer, size: listOf(integer) });

/** The shop's workflow class, whose one method is the parcels adapter. */
class Orders extends Workflow {
  /**
   * Gives the shipping the weight of the order's parcel. Every other input is
   * read from the data bag.
   */
  parcels(key: string, parcel: Parcel): Supplied {
    if (key !== "weight") return this.fromDataBag();
    return this.supply(parcel.weight);
  }
}

/** The charge, under its name, with the requests of its parameters. */
function charge() {
  return Charge.builder("charge")
    .needs(input("price", integer))
    .run(contributor());
}

/** The shipping, under its name, with the request of its parameter. */
function ship() {
  return Ship.builder("ship").needs(input("weight", integer));
}

const audit = Audit.builder("audit").onStepSuccess(
  "audited",
  fromStep("charged", integer),
  contributor(),
);
const receipts = Receipts.builder("receipts").onStepSuccess(
  "written",
  fromStep("charged", integer),
  contributor(),
);
```

It is put together with three mistakes: `ship` listed twice, two policies of the charge that both define `on step success`, and the parcels adapter attached to `shipping`, a step the workflow doesn't have:

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

```typescript
const wrong = Orders.builder()
  .name("orders")
  .step(charge().policy(audit).policy(receipts))
  .step(ship())
  .step(ship().retryBudget(1))
  .inputAdapter(
    "parcels",
    { steps: ["shipping"] },
    key(),
    fromWorkflow("parcel", PARCEL),
  );
```

The mistakes are found when the program calls `build()`, which throws a `Violations`, as the decorators do in [chapter 37](https://itinera-dev.org/book/typescript/37-mistakes-caught-before-a-journey.md):

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

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

Fixed, the builder's `listing()` lists its steps:

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

```typescript
const fixed = Orders.builder()
  .name("orders")
  .step(charge().policy(audit))
  .step(ship().retryBudget(1))
  .inputAdapter(
    "parcels",
    { steps: ["ship"] },
    key(),
    fromWorkflow("parcel", PARCEL),
  );
console.log("the fixed workflow is put together as:");
for (const listed of fixed.listing()) {
  console.log(`${String(listed.position)}. ${listed.step}`);
}
```

It prints:

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

```text
the workflow was refused:
duplicate step name: ship
hook defined twice: on step success on step charge
input adapter for unknown step: parcels on shipping
the fixed workflow is put together as:
1. charge
2. ship
```

## How it works

1. **Both forms make the same declaration.** A workflow is a **workflow descriptor**: its name, a **step descriptor** for each step, in order, giving its name, how to build it, its retry budget, policies and rescue step, then the workflow's policies, reporters, ID generator, input adapters and providers. The decorators record it from your classes, and the builder takes it part by part. The executor runs either the same way, and the two forms mix, as here: write by hand only what needs it.
2. **Each decorator stands for a call of a builder.** A step's decorators stand for its builder's `needs` and `run`, and `@withStep` for the workflow builder's `step`, its name for the step builder's, and its options for `retryBudget`, `rescue` and `policy`. `@stepPolicy` and a hook's decorator stand for a policy's builder and its `onStepSuccess`, or its other hooks' methods. `@workflow` stands for `name`, `reporter` and `policy`, `@idGenerator()`, `@inputAdapter` and `@provider` for the methods of their names, and `Orders.build("email")` for `constructWith("email")` and `build()`.
3. **TypeScript checks each request against its parameter.** A request missing, or for a parameter of another type, doesn't compile, and a step whose `needs` or `run` is never given throws an `Error` naming the parameter when the workflow's builder takes it.
4. **`build()` checks the declaration, as admission.** It throws a `Violations` listing every violation, as `@workflow` does, but where the program calls it. `listing()` runs the same check without making the workflow object.
5. **When you need the long form.** With a compiler that records no decorator metadata, such as esbuild, tsx or Vite, declare every step, rescue step, policy and workflow with its `builder`; of [chapter 3](https://itinera-dev.org/book/typescript/03-installing-itinera.md)'s compiler options, only `strict` is then needed. It also suits a declaration put together from configuration as the program starts. `itinera` has no options, as chapter 3 said, so nothing turns the decorators off: a program uses the form its compiler allows.

What the book hasn't said is how to decide, for a new rule of the shop, which part it belongs in.

## Outcomes

We have shown what the decorators stand for, how to write it by hand, and when a workflow declared by hand reports its mistakes.

| The usual way                                                                                         | With Itinera                                                                            |
| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Code wired by decorators often works only with the compilers that support them.                       | The builder takes the same declaration part by part, from classes without decorators.   |
| Wiring checked at start-up usually runs wherever the framework decides, before the program has a say. | `build()` checks it at the point the program chooses, and throws every violation there. |
