Bend Web Framework

The Singularity
Framework.

Bend is a programming language designed for AI agents. It brings dependent types to traditional software development. The same idea underlies Lean, which checked AI-assisted proofs of the Riemann hypothesis and the Navier–Stokes blowup result. In Bend, your agent can prove that its code obeys the laws you define, and the compiler checks the proof.

Bend Web Framework brings this to the web.

OpenAPI

One contract to rule them all.

Let your agent define the contract in openapi.yaml. BWF derives the API routes and types, then checks path and query parameters, forms, and controller responses against that same contract at build time.

Read the OpenAPI guide
openapi.yamlType check succeeded
paths:
  /articles:
    post:
      operationId: createArticle
      x-bwf-response-type: ArticleWrite
      requestBody:
        $ref: '#/components/requestBodies/ArticleForm'
# components / schemas
ArticleForm:
  type: object
  required: [title, description, body]
  additionalProperties: false
  properties:
    title: {type: string}
    description: {type: string}
    body: {type: string}
    tags: {type: string}

View/Editor.bsx

New article
<form method="post"
  action={url("/articles")}>
  <input name="title" required />
  <input name="description" required />
  <textarea name="body" required></textarea>
  <input name="tags" />
</form>

Unknown form field "headline" for createArticle

Controller/Articles/Create.bend

# Generated from openapi.yaml
type ArticleForm is Data:
  ArticleForm{
    title: String,
    description: String,
    body: String,
    tags: Maybe<&2, String>
  }

def action(
  context: Controller.SignedIn,
  input: Api.ArticleForm
) -> IO(Api.ArticleWriteResponse):
  publish(Draft.prepare(input), context)

Dependent types

Let your agent prove laws about your code.

With dependent types, you can prove that a rule holds for every valid input, even when there are infinitely many possible inputs. Write the rule in LAWS.bend and let Bend check your agent’s proof.

Controller/Articles/Create.bend

Proof passed
def action(context: Controller.SignedIn,
           input: Api.ArticleForm)
    -> IO(Api.ArticleWriteResponse):
  # Invalid drafts return 422 before any insert.
  publish(Draft.prepare(input), context)

LAWS.bend

law invalid_draft_cannot_publish:
  # A failed validation must produce the 422 response without writing.
  for context: Controller.SignedIn
  for input: Api.ArticleForm
  for invalid: {None{} == Draft.prepare(input)
    : Maybe<&2, Api.ArticleForm>}
  {ArticleCreate.action(context, input)
    == rejected_publication()
    : IO(Api.ArticleWriteResponse)}

Model/Account/Validation.bend

Proof passed
def valid_password(+password: String) -> Bool:
  # Reject passwords shorter than 8 characters.
  Nat.is_ge(String.length(password), 8n)
    && Nat.is_le(String.length(password), 256n)

LAWS.bend

law password_requires_eight_characters:
  # Prove rejection for every password shorter than 8 characters.
  for password: String
  for too_short: {False{}
    == Nat.is_ge(String.length(password), 8n)
    : Bool}
  {Account.valid_password(password)
    == False{} : Bool}

TypedSQL

Catch SQL errors at build time.

Write arbitrary SQL queries directly in Bend. At build time, PostgreSQL checks the query against your migrated schema, and BWF checks its parameters and result columns against your Bend types.

Read the TypedSQL guide

Controller/Articles/Show.bend

Type check succeeded
def load_article(
  database: String,
  +viewer: Maybe<&2, Sql.Id<"users">>,
  +address: String
) -> IO(Sql.Outcome(Maybe<&2, Api.ArticleView>)):
  do IO<Sql.Outcome(Maybe<&2, Api.ArticleView>)>:
    article <- sql(database) as Api.ArticleView """
      SELECT
        a.slug AS "article.slug",
        a.title AS "article.title",
        a.description AS "article.description",
        a.body AS "article.body",
        u.username AS "article.author.username",
        EXISTS (
          SELECT FROM follows f
          WHERE f.followed = a.author_id AND f.follower = ${viewer}
        ) AS "article.author.following",
        COALESCE(array_remove(a.tags, NULL::text), '{}'::text[])
          AS "article.tagList",
        COALESCE((SELECT count(*) FROM article_favorites f
          WHERE f.article_id = a.id), 0) AS "article.favoritesCount",
        EXISTS (SELECT FROM article_favorites f
          WHERE f.article_id = a.id AND f.user_id = ${viewer})
          AS "article.favorited",
        COALESCE(to_char(a.created_at, 'Mon DD, YYYY'), '') AS published,
        COALESCE(a.author_id = ${viewer}, false) AS owner
      FROM articles a JOIN users u ON u.id = a.author_id
      WHERE a.slug = ${address} OR a.legacy_id = ${address}
         OR a.id = CASE
           WHEN ${address}::text ~ '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'
           THEN ${address}::text::uuid END
      ORDER BY (a.slug = ${address}) DESC LIMIT 1
    """
    return article

HTMX

Forms and links are all you need.

A few HTML attributes tell HTMX when to search, when to load more, and where to put the results.

Compare the same search in HTMX, React, and React with TanStack Query.

Read the HTMX guide
BWF Guide
  • Explore and modify the Journal

    Run the Journal shipped with Bwf. Follow a two-reader workflow through its views, controllers, PostgreSQL queries, and live updates.

  • Set up your first Bwf project

    Clone Bwf, create a small application called my-site, and change the heading on its home page.

  • Your first BSX page

    We’ll build a page you can open at localhost:8080. All it needs is a heading and a function to send that heading to the browser.

  • What the build checks

    Suppose we change the address of an article. How do we find the links that still point to the old address? We’ll use a link from the Journal to see which mistakes the build can catch.

  • Changing the article page

    Let’s make a small change to the Journal. We’ll add “Summary” under the title of each article. Open an article from the feed and keep it open so you can check your edit. The files we’ll use are in examples/canonical.

  • Route a request and link to it

    Let’s rename the home operation in the project you created during installation. Its URL will stay the same. The compiler will show us which names depend on the operation.

  • Controllers and typed responses

    We’ll start with a health check. When a client asks whether the Journal is running, our action only needs to send back the word “ok”.

  • Write a BSX view

    Let’s make a small badge we can use anywhere in the Journal. We’ll give it a label and use it in another view just as we would call a Bend function.

  • HTML forms and CSRF

    When you click Save in the Journal editor, the browser sends the field names along with what you typed. We’ll connect those names to the operation that handles the form.

  • Validation and error responses

    Try submitting three spaces as an article title. We’ll see where the Journal catches that mistake, then follow a registration error all the way back to its field in the form.

  • Serve JSON from an OpenAPI contract

    A client asks the Journal for JSON. What should the action return? We’ll start with the response in the OpenAPI file and construct a value of that shape in Bend.

  • Add a column to the Journal

    We’d like to give each article a short summary. There are already articles in the Journal, written before anyone thought to ask for a summary. Let’s add a column they can leave empty.

  • TypedSQL

    Let’s read a row from PostgreSQL in a Bend function. We can write the query next to the code that uses it and have the build check the fields we get back.

  • Relationships, joins and SQL projections

    An article card shows a headline and the name of the person who wrote it. Let’s fetch the two together and pass the result to the view.

  • Running two queries in one transaction

    In the example below, the first query returns an email address. The second counts the articles written by the account at that address. Follow the value called email from one query into the other.

  • Sessions and cookie context

    A visitor can read the Journal before they sign in. By the time they save an article, the action needs to know which account is writing. We’ll choose what each route receives.

  • Password authentication

    We’ll follow a Journal account from registration to its next sign-in. Along the way we’ll see what goes into the account table and how the controller starts a session.

  • Authorization and ownership

    Sign in to the Journal with a second account and open somebody else’s article. You can read it. What stops you from sending the editor’s request yourself?

  • Static assets

    Let’s add a file the browser can request on its own. We’ll put it under static/ and build its URL in a BSX view.

  • Typed translations

    We’ll ask the Journal for the same missing page twice. Watch the sign-in link in the navigation. The first request asks for English and the second for Canadian French.

  • HTMX and fragment responses

    Open the feed in a fresh tab, then click Next. The second page only needs a new list of articles. We’ll use the same URL whether the reader follows the link or pastes it into another tab.

  • Auto Refresh

    Open the same article in two sessions of the Journal. Leave a comment in one and watch the other. We’ll set up the subscription that lets the new comment appear in the open page.

  • Auto Refresh for HTMX fragments

    Click Next on the Journal feed and leave that page open. For new articles to appear there, Auto Refresh needs to know which slice of the feed you’re looking at.

  • Where the Next link comes from

    Look at LIMIT 11 in the query below. A page in the Journal only has room for ten articles. We’ll use the extra article to answer one question before we send the page to the browser.

  • Personalized lists and viewer state

    Open the same article in two accounts and mark it as a favorite in one. Both readers should see the same total, but only one should see the article marked as theirs.

  • Testing a Bwf application

    Before starting a server, we can already check the Journal’s routes, queries and views. Then we’ll make an HTTP request to check what a reader actually receives.

  • Build and deploy an application

    We’ll build the server and put its public files beside it. Once the service is running, we can make a health request to check the deployment.

  • Troubleshoot a Bwf application

    Keep the terminal running bwf dev in sight while you reproduce the problem. First we need to know whether the build stopped or the running server received a request.

Scroll for more chapters ↓28 chapters

HTMX
import { useEffect, useRef, useState } from 'react'

function GuideSearch() {
  const [draft, setDraft] = useState('')
  const [q, setQuery] = useState('')

  useEffect(() => {
    const timer = setTimeout(() => setQuery(draft.trim()), 300)
    return () => clearTimeout(timer)
  }, [draft])

  return <>
    <form onSubmit={event => {
      event.preventDefault()
      setQuery(draft.trim())
    }}>
      <input type="search" name="q" aria-label="Search the guide"
        value={draft} onChange={event => setDraft(event.target.value)} />
    </form>
    <ChapterPages key={q} q={q} />
  </>
}

function ChapterPages({ q }) {
  const [page, setPage] = useState(1)
  const [pages, setPages] = useState([])
  const [failed, setFailed] = useState(false)
  const busy = !failed && pages.length < page

  useEffect(() => {
    const request = new AbortController()
    const { signal } = request
    readPage(q, page, signal).then(result => {
      if (!signal.aborted) setPages(current => [...current, result])
    }).catch(() => {
      if (!signal.aborted) setFailed(true)
    })
    return () => request.abort()
  }, [q, page])

  const next = pages.at(-1)?.nextPage
  const loadMore = next && !busy && !failed ? () => setPage(next) : null
  const list = useRef(null)
  const more = useRef(null)
  useEffect(() => {
    if (!loadMore || !more.current) return
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) loadMore()
    }, { root: list.current })
    observer.observe(more.current)
    return () => observer.disconnect()
  }, [loadMore])

  return <div ref={list} style={{ maxHeight: 272, overflowY: 'auto' }}>
    {busy && <p role="status">Loading…</p>}
    {failed && <p role="alert">Couldn’t load chapters.</p>}
    <ChapterLinks pages={pages} />
    {loadMore && <div ref={more} style={{ height: 1 }} aria-hidden="true" />}
  </div>
}
<div id="htmx-demo" hx-sync="this:replace">
  <form method="get" action="/browse"
    hx-get="/browse"
    hx-trigger="load, input delay:300ms, submit"
    hx-target="#htmx-results" hx-swap="outerHTML show:none"
    hx-indicator="#htmx-loading">
    <label>Search the guide <input name="q" type="search"></label>
    <span id="htmx-loading" class="htmx-indicator">Searching…</span>
  </form>
  <div id="htmx-results"></div>
</div>

<!-- /browse returns this trigger after the last result. -->
<li class="htmx-more"
  hx-get="/browse?page=2"
  hx-trigger="intersect once root:#htmx-results"
  hx-swap="outerHTML"
  hx-sync="#htmx-demo:abort"></li>

Auto Refresh

Make your site collaborative in real time.

PostgreSQL is your reactive state. When one request commits a change, BWF refreshes every open view watching that data, across users and tabs. Your frontend renders fresh HTML while BWF handles synchronization.

Read the Auto Refresh guide
When
A comment is saved on this article
Refresh
This article in every reader’s open tab

Camille’s tab

Observatory notes

CamilleThe photos are in.

Write a comment…
Post

Alex’s tab

Observatory notes

CamilleThe photos are in.

I’ll add the captions.
Draft preserved
WebSocketComment synced

Typed translations

Catch missing translations at build time.

Import a MessageFormat 2 catalog and each message becomes a typed Bend function. If a translation drops a key or changes an argument’s type, the build fails.

Read the translation guide

messages.mf2.json

comment_count
.input {$article :string}
.input {$count :integer}
.match $count
0    {{No comments on {$article}}}
one  {{One comment on {$article}}}
*    {{{$count} comments on {$article}}}

TranslationDemo.bsx

import ./messages.mf2.json as Messages

<strong>
  {Messages.comment_count(locale, "Observatory notes", 1234n)}
</strong>

# "1234" fails type checking. count requires Nat.
Accept-Language
Comment count
lang="en"No comments on Observatory notesOne comment on Observatory notes1,234 comments on Observatory notes
lang="fr"Aucun commentaire sur Observatory notesUn commentaire sur Observatory notes1 234 commentaires sur Observatory notes

Explore the Journal.

Journal is BWF’s implementation of the RealWorld example app. Create an account, publish an article, and trace live comments from the OpenAPI route through PostgreSQL to the HTML view.

Start the tutorial
Selected RealWorld apps
ImplementationClient + server lines
Ours !2,317
Next.js + tRPC2,824
Vue + FastAPI4,021
React + Django Ninja4,139
React + Express4,191
Angular + Spring Boot4,449
React + ASP.NET Core6,300