strict-script strict-script

Examples

invoice

The sources of the example, as they are at the commit this site was built from. Examples says what each example is about, and the playground runs a text of the language in the page.

#invoice.sts

examples/invoice/invoice.sts
// Typing and errors: what comes from outside is read against its type, and every failure is in a type.

type Line = { label: string, quantity: number, unitPrice: number }
type Status = "draft" | "sent" | "paid" | "cancelled"
export type Invoice = { id: string, customer: string, status: Status, lines: Line[], paidAt?: string }

extern "node:crypto" {
  function randomUUID(): string
}

export function createInvoice(customer: string, lines: Line[]): Result<Invoice, "no-lines" | Thrown> {
  if (lines.length == 0) return Err("no-lines")
  Ok({ id: randomUUID()?, customer, lines, status: "draft" })
}

export function total(invoice: Invoice): number {
  invoice.lines.sum(line => line.quantity * line.unitPrice)
}

export function parseInvoice(json: string): Result<Invoice, JsonError | ParseError> {
  Invoice.parse(JSON.parse(json)?)
}

export function firstLine(invoice: Invoice): Option<Line> {
  invoice.lines[0]
}

export function statusLabel(status: Status): string {
  match status {
    "draft" => "Draft",
    "sent" => "Sent",
    "paid" => "Paid",
    "cancelled" => "Cancelled",
  }
}

export function reminder(invoice: Invoice): Option<string> {
  match invoice.status {
    "sent" => Some(`Reminder sent to ${invoice.customer} (${total(invoice)} €)`),
    _ => None,
  }
}

export function reminders(invoices: Invoice[]): string[] {
  invoices.flatMap(invoice => match reminder(invoice) {
    Some(text) => [text],
    None => [],
  })
}

#main.sts

examples/invoice/main.sts
import { createInvoice, parseInvoice, reminders, statusLabel, total, Invoice } from "./invoice.sts"

function describe(invoice: Invoice): string {
  `${invoice.customer}: ${total(invoice)} € (${statusLabel(invoice.status)})`
}

export function main(args: string[]): Result<void, string> {
  const made = match createInvoice("Ada", [{ label: "pen", quantity: 2, unitPrice: 1.5 }]) {
    Ok(invoice) => invoice,
    Err(_) => return Err("the invoice could not be made"),
  }
  console.log(describe(made))

  const text = args[0] ?? `{"id":"7","customer":"Grace","status":"sent","lines":[{"label":"ink","quantity":1,"unitPrice":4}]}`
  match parseInvoice(text) {
    Ok(invoice) => {
      console.log(describe(invoice))
      for (const line of reminders([invoice, made])) {
        console.log(line)
      }
      Ok()
    },
    Err({ kind: "json", message }) => Err(`not JSON: ${message}`),
    Err({ kind: "parse", path, expected }) => Err(`not an invoice: at ${path}, expected ${expected}`),
  }
}
Esc

    Type a word of the language, a rule, a command: mut, extern, match-not-covered.