Canica

canica/client

Pages, live queries, mutations, forms, navigation and sign-in, for src/. Apps import nothing from React directly (except with app({ ui: "own" })).

Functions and values

page layout useQuery useMutation useAction useUpload useForm useNavigate useAuth useSignInProviders signInWithGoogle signInWithAnotherAccount signOut signOutEverywhere setSignInScreen setNoAccessScreen useNow useToday useRelativeFormatter redirect match start modal string number cents boolean id userId literal array object day file emailId addDays daysBetween weekday startOfWeek lastDays formatCents plural formatDate formatTime fileUrlAtWidth snapWidth IMAGE_WIDTHS

page functionsrc/client/page.tsx

A screen. view is a pure function of params, state and live queries.

export default page({
  params: { id: id("todos") },
  view: ({ params }) => {
    const todo = useQuery("todo", { id: params.id })
    ...
  },
})
function page<const P extends ArgsFields = {}, const S extends SearchFields = {}>(def: {
  readonly params?: P
  /**
   * Search params the page reads, e.g. `{ q: string().trim().optional() }`: the view gets `search.q`, and
   * `<SearchInput param="q">` keeps it in the URL (`/?q=milk`). For filters only: what the page shows, not data.
   */
  readonly search?: S
  readonly title?: string | ((params: ArgsOf<P>) => string)
  /**
   * `"signedIn"`: only signed-in users see this page; guests get a sign-in screen (inside the layout) and
   * come back here after signing in. Protect the data on the server too (`requireSignIn`).
   */
  readonly auth?: "signedIn"
  readonly view: (props: PageProps<P, S>) => ReactNode
}): PageDef<P, S>

layout functionsrc/client/page.tsx

Wraps every page. Export it from src/routes/__root.tsx. auth: "signedIn" puts the whole app behind sign-in (the layout itself still shows, e.g. the header).

const layout = (def: {
  readonly auth?: "signedIn"
  readonly view: (props: { readonly children: ReactNode }) => ReactNode
}): LayoutDef => …

useQuery functionsrc/client/runtime.tsx

Subscribe to a query. Re-renders whenever the result changes on the server. Pass "skip" as args to not run it yet.

const todos = useQuery("todos")
if (todos._tag === "Loading") return <Spinner />
if (todos._tag === "Failure") return <p>{todos.error._tag}</p>
return todos.value.map(...)
function useQuery<N extends QueryName>(
  name: N,
  ...args: {} extends QueryArgs<N> ? [args?: QueryArgs<N> | "skip"] : [args: QueryArgs<N> | "skip"]
): QueryResult<QueryValue<N>, QueryError<N>>

useMutation functionsrc/client/runtime.tsx

Get a function that runs a mutation. It resolves after every live query affected by the write has updated, and never rejects: failures (including server bugs, as ServerError) come back as { _tag: "Failure", error }. .status / .waiting track the latest call for spinners and messages.

function useMutation<N extends MutationName>(name: N): MutationFn<N>

useAction functionsrc/client/runtime.tsx

Get a function that runs an action (network, secrets; see the server's actions). Same shape as useMutation: never rejects, .status / .waiting for feedback. What the action saved shows through live queries.

function useAction<N extends ActionName>(name: N): ActionFn<N>

useUpload functionsrc/client/runtime.tsx

Upload files to the app: const upload = useUpload(), then const r = await upload(file) gives the file's id (r._tag === "Success": r.value), to pass to a mutation that stores it in a file() field. Never rejects: FileTooLarge, StorageFull, … come back as { _tag: "Failure", error }. .progress, .status, .waiting for feedback (<FileInput> from canica/ui shows them).

function useUpload(): UploadFn

useForm functionsrc/client/runtime.tsx

A native form: inputs keep their own values (use name and defaultValue); on submit the values are read, validated with the fields' schemas, and passed to onSubmit. Field errors (client or server InvalidArgs) show up in errors. The form resets after a successful submit.

const form = useForm("rename card", { title: string().trim().min(1).max(80) }, (values) =>
  rename({ id: params.card, ...values }),
)
<form {...form.props}>
  <input name="title" defaultValue={card.title} />
  {form.errors.title && <p>{form.errors.title}</p>}
  <button disabled={form.waiting}>Save</button>
</form>
function useForm<const F extends ArgsFields, R>(
  name: string,
  fields: F,
  onSubmit: (values: ArgsOf<F>) => Promise<R> | R,
  options?: {
    readonly resetOnSuccess?: boolean
    /** Runs after a successful submit (e.g. close a dialog, navigate to the new row). */
    readonly onSuccess?: (value: ActionValueOf<R>) => void
  },
): Form<ArgsOf<F>, R>

useNavigate functionsrc/client/runtime.tsx

Get a function that navigates to path. The destination is fixed here; params are passed when you call it.

const goToTodo = useNavigate("/todos/$id")
<li onClick={() => goToTodo({ id: todo.id })}>
function useNavigate<P extends RoutePath>(path: P): (...args: NavigateArgs<P>) => void

useAuth functionsrc/client/runtime.tsx

Who is using the app. Guests are automatic (isGuest); isSignedIn after signing in with a provider. Wait for isLoading to be false before showing account-only UI.

function useAuth(): AuthState

useSignInProviders functionsrc/client/runtime.tsx

Which sign-in the server offers: { known, google, note? } (known: false until it answered).

function useSignInProviders(): Providers

signInWithGoogle functionsrc/client/runtime.tsx

Sign in with Google (through the platform's broker) and come back to the current page.

const signInWithGoogle = async (redirect: string = location.pathname + location.search): Promise<void> => …

signInWithAnotherAccount functionsrc/client/runtime.tsx

Sign in with another Google account (the "no access" screen): the platform's sign-in forgets the account it remembers, then asks Google which one, and comes back to the current page.

const signInWithAnotherAccount = async (redirect: string = location.pathname + location.search): Promise<void> => …

signOut functionsrc/client/runtime.tsx

Sign out: the server ends this browser's session and clears its cookie; in a public app the browser continues as a new guest. Live queries re-run. { everywhere: true }: every session of this person ends, on every device.

const signOut = (options: { readonly everywhere?: boolean } = {}): void => …

signOutEverywhere functionsrc/client/runtime.tsx

Sign out on every device (every session of this person in this app ends; agents stay connected).

const signOutEverywhere = (): void => …

setSignInScreen functionsrc/client/runtime.tsx

Replace the full-page screen every route shows while the app needs signing in (app({ access }) other than "public") and the visitor has not: call it in src/main.tsx before start. Canica's (canica/ui) shows the app's icon and name, who may use it and "Sign in with Google"; signInWithGoogle() comes back to the page they asked for. gate.mode is the level, gate.domains an org's domains.

const setSignInScreen = (screen: (props: AccessScreenProps) => ReactNode) => …

setNoAccessScreen functionsrc/client/runtime.tsx

Replace the screen a signed-in person sees in an app not shared with them (org, private): Canica's says who they are signed in as, and offers another account (signInWithAnotherAccount()) and signOut().

const setNoAccessScreen = (screen: (props: AccessScreenProps) => ReactNode) => …

useNow functionsrc/client/runtime.tsx

The current time (epoch ms), rounded down to unit, updated when it changes. Views must not call Date.now(); this keeps them pure (the canvas and tests can fix the time).

function useNow(unit: TimeUnit = "minute"): number

useToday functionsrc/client/runtime.tsx

Today in the user's timezone, as "YYYY-MM-DD".

function useToday(): string

useRelativeFormatter functionsrc/client/runtime.tsx

For lists: const ago = useRelativeFormatter() once, then ago(message.createdAt) per row.

function useRelativeFormatter(): (ms: number) => string

redirect functionsrc/client/runtime.tsx

Go somewhere else instead of rendering (the URL is replaced, no history entry). Return it where you would return JSX: success: (m) => (m.isMember ? redirect("/groups/$group", { group }) : <JoinForm />).

function redirect<P extends RoutePath>(to: P, ...params: {} extends NavigateArgs<P>[0] ? [params?: NavigateArgs<P>[0]] : [params: NavigateArgs<P>[0]]): ReactNode

match functionsrc/client/runtime.tsx

Run a callback for the matching case of a query result.

const match = <A, E, R>(
  result: QueryResult<A, E>,
  cases: { readonly Loading: () => R; readonly Success: (value: A) => R; readonly Failure: (error: E) => R },
): R => …

start functionsrc/client/runtime.tsx

function start(table: RouteTable, options?: StartOptions): { unmount: () => void }
function start(table: RouteTable, element?: HTMLElement | null, options?: StartOptions): { unmount: () => void }

string functionsrc/server/fields.ts

A UTF-8 string. Chain .trim(), .min(n), .max(n), .pattern(re), .email(), .message(text).

const string = (): StringField => …

number functionsrc/server/fields.ts

A finite float64. Chain .int(), .min(n), .max(n).

const number = (): NumberField => …

cents functionsrc/server/fields.ts

Money as integer minor units (cents), more than 0 (an amount someone typed; for balances use number().int()). Stored and sent as an integer; in forms the user types a decimal amount ("12.50" or "12,50") and the field gets 1250. Display with (cents / 100).toLocaleString(undefined, { style: "currency", currency: "EUR" }).

const cents = (): NumberField => …

boolean functionsrc/server/fields.ts

const boolean = (): BooleanField => …

id functionsrc/server/fields.ts

A reference to a row in table.

const id = <const Table extends string>(table: Table): IdField<Table> => …

userId functionsrc/server/fields.ts

A reference to a Canica user (guest or signed in).

const userId = (): UserIdField => …

literal functionsrc/server/fields.ts

One of a fixed set of string/number/boolean values. Indexable.

const literal = <const L extends ReadonlyArray<string | number | boolean>>(...values: L): LiteralField<L[number]> => …

array functionsrc/server/fields.ts

An array of values. Stored as JSON; cannot be indexed. Chain .min(n), .max(n), .nonEmpty().

const array = <F extends AnyField>(item: F): ArrayField<FieldType<F>> => …

object functionsrc/server/fields.ts

A nested object. Stored as JSON; cannot be indexed.

const object = <const Fields extends Record<string, AnyField>>(fields: Fields): PlainField<Simplify<ObjectType<Fields>>> => …

day functionsrc/server/fields.ts

A calendar day without time or timezone, as "YYYY-MM-DD" (validated as a real date). Sorts correctly as text, so it can be indexed and range-queried.

const day = (): DayField => …

file functionsrc/server/fields.ts

An uploaded file, stored as its id (Id<"_files">). Upload with useUpload() in the page, then pass the id to a mutation that stores it here; queries turn it into a link with files.url(id). A file no row refers to is deleted (24 h after its upload if it was never stored; at the next hourly cleanup once its row is deleted or changed).

const file = (): FileField => …

emailId functionsrc/server/fields.ts

An email's id (EmailId), e.g. a query's argument: query({ id: emailId() }, …) that returns its status.

const emailId = (): EmailIdField => …

addDays functionsrc/server/days.ts

addDays("2026-03-01", -1) → "2026-02-28".

const addDays = (day: string, n: number): string => …

daysBetween functionsrc/server/days.ts

Whole days from a to b (daysBetween("2026-01-01", "2026-01-08") → 7).

const daysBetween = (a: string, b: string): number => …

weekday functionsrc/server/days.ts

Day of the week, 0 = Monday … 6 = Sunday.

const weekday = (day: string): number => …

startOfWeek functionsrc/server/days.ts

The Monday (or Sunday with { weekStartsOn: 0 }) of day's week.

const startOfWeek = (day: string, options?: { readonly weekStartsOn?: 0 | 1 }): string => …

lastDays functionsrc/server/days.ts

The n days ending at day, oldest first (lastDays(today, 7) = this past week).

const lastDays = (day: string, n: number): ReadonlyArray<string> => …

formatCents functionsrc/server/days.ts

Money in cents as text: formatCents(1250, "EUR") → "€12.50" (in the user's locale on the client).

const formatCents = (cents: number, currency: string, locale?: string): string => …

plural functionsrc/server/days.ts

"1 voter", "3 voters", "0 cards". Irregular plurals: plural(n, "person", "people").

const plural = (n: number, singular: string, pluralForm: string = `${singular}s`): string => …

formatDate functionsrc/server/days.ts

An unambiguous date for an epoch ms: "Oct 12, 2026" (in the user's locale on the client).

const formatDate = (ms: number, locale?: string): string => …

formatTime functionsrc/server/days.ts

A message-style time: "10:42" today, "Yesterday 10:42", "Mon 10:42" this week, else "Oct 12, 10:42". now comes from useNow("minute") on the client.

const formatTime = (ms: number, now: number, locale?: string): string => …

fileUrlAtWidth functionsrc/core/image-sizes.ts

A file link from a query, asking for the image at px pixels wide (snapped up; at most what the link grants). Anything that is not a Canica file link comes back as it is.

const fileUrlAtWidth = (src: string, px: number): string => …

snapWidth functionsrc/core/image-sizes.ts

The smallest width of the list at least px wide (1280 for anything larger).

const snapWidth = (px: number): ImageWidth => …

IMAGE_WIDTHS constsrc/core/image-sizes.ts

The widths images are resized to (CSS pixels × 2 for sharp screens, snapped up to one of these).

const IMAGE_WIDTHS = [160, 320, 640, 1280] as const

Components

Link

Types

PageDef PageProps LayoutDef SearchFields AuthState AccessGate AccessScreenProps RouteTable ScreenInfo MutationFn ActionFn UploadFn Form StartOptions SignInProviders AnyForm ModalDef ModalResult Close ModalCases CancelReason QueryCases Register QueryName MutationName ActionName RoutePath QueryArgs QueryValue QueryError MutationArgs MutationValue MutationError ActionArgs ActionValue ActionError QueryResult MutationResult Status ServerError ConnectionLost UploadError NavigateOptions SearchParamName Id UserId FileId EmailId EmailState EmailStatus EmailFailure ImageSize ImageWidth FileUrlOptions

PageDef interfacesrc/client/page.tsx

interface PageDef<P extends ArgsFields = {}, S extends SearchFields = {}> {
  readonly "~canica/page": true
  readonly params: P
  readonly search: S
  readonly title?: string | ((params: ArgsOf<P>) => string)
  readonly auth?: "signedIn"
  readonly view: (props: PageProps<P, S>) => ReactNode
}

PageProps interfacesrc/client/page.tsx

interface PageProps<P extends ArgsFields, S extends SearchFields = {}> {
  /** Path params, decoded and validated with the page's `params` schema. */
  readonly params: ArgsOf<P>
  /**
   * Search params (`?q=milk`) declared in `search`, decoded with their fields. A missing or invalid one is absent
   * (or its default). `<SearchInput param="q">` writes them.
   */
  readonly search: ArgsOf<S>
}

LayoutDef interfacesrc/client/page.tsx

interface LayoutDef {
  readonly "~canica/layout": true
  readonly auth?: "signedIn"
  readonly view: (props: { readonly children: ReactNode }) => ReactNode
}

SearchFields typesrc/client/page.tsx

Search params (?q=milk): each one optional or with a default, since a URL may leave it out.

type SearchFields = Record<string, FieldDef<any, "optional" | "default">>

AuthState interfacesrc/client/connection.ts

interface AuthState {
  readonly userId: string | undefined
  readonly isSignedIn: boolean
  readonly isGuest: boolean
  readonly profile: { readonly name?: string; readonly email?: string; readonly picture?: string } | undefined
  /** True until the server has answered the first hello. */
  readonly isLoading: boolean
  /**
   * Whether this person may use the app (`app({ access })`, `canica access`): "signIn" until they sign in to an app
   * that is not public, "forbidden" for a signed-in person it is not shared with. Pages show a screen for those.
   */
  readonly access: "ok" | "signIn" | "forbidden"
  /** Who may use the app (for the sign-in screen): its level, and the org's domains. */
  readonly gate: AccessGate
}

AccessGate interfacesrc/client/connection.ts

interface AccessGate {
  readonly mode: "public" | "signedIn" | "org" | "private"
  readonly domains: ReadonlyArray<string>
  /** The app's name, when `app({ name })` gives one. */
  readonly name?: string
}

AccessScreenProps interfacesrc/client/runtime.tsx

What the sign-in and no-access screens get: who may use the app (its level, and an org's domains).

interface AccessScreenProps {
  readonly gate: AccessGate
}

RouteTable interfacesrc/client/runtime.tsx

interface RouteTable {
  readonly routes: ReadonlyArray<{ readonly path: string; readonly page: AnyPage }>
  readonly layout?: LayoutDef
  readonly notFound?: AnyPage
}

ScreenInfo interfacesrc/client/runtime.tsx

interface ScreenInfo {
  readonly queries: Set<string>
  readonly mutations: Set<string>
  /** Server actions it calls (`useAction`). */
  readonly serverActions: Set<string>
  readonly navigations: Set<string>
  readonly actions: Map<string, Set<string>>
}

MutationFn typesrc/client/runtime.tsx

type MutationFn<N extends MutationName> = ((
  ...args: ArgsParam<MutationArgs<N>>
) => Promise<MutationResult<MutationValue<N>, MutationError<N>>>) & {
  /** The latest call from this component: Idle, Waiting, Success or Failure (with the typed error). */
  readonly status: Status<MutationValue<N>, MutationError<N>>
  readonly waiting: boolean
}

ActionFn typesrc/client/runtime.tsx

type ActionFn<N extends ActionName> = ((
  ...args: ArgsParam<ActionArgs<N>>
) => Promise<MutationResult<ActionValue<N>, ActionError<N>>>) & {
  /** The latest call from this component: Idle, Waiting, Success or Failure (with the typed error). */
  readonly status: Status<ActionValue<N>, ActionError<N>>
  readonly waiting: boolean
}

UploadFn typesrc/client/runtime.tsx

type UploadFn = ((
  file: Blob,
  options?: { readonly name?: string },
) => Promise<MutationResult<FileId, UploadError>>) & {
  /** The latest upload from this component: Idle, Waiting, Success (the id) or Failure. */
  readonly status: Status<FileId, UploadError>
  readonly waiting: boolean
  /** How much of the current upload went out (0 to 1); undefined when none is running. */
  readonly progress: number | undefined
}

Form interfacesrc/client/runtime.tsx

interface Form<V, R> {
  /** Unique per form instance; FormField uses it to give controls unique ids. */
  readonly id: string
  /** Spread onto `<form>`: `<form {...form.props}>`. */
  readonly props: { readonly onSubmit: (e: FormEvent<HTMLFormElement>) => void; readonly noValidate: true; readonly "data-canica-form"?: string }
  /** Error per field name (client validation, or the server's `InvalidArgs`). */
  readonly errors: Partial<Record<keyof V & string, string>>
  /** A failure that is not about one field (e.g. `{ _tag: "NameTaken" }` or `ServerError`). */
  readonly error: ActionErrorOf<R> | ServerError | ConnectionLost | undefined
  readonly status: Status<ActionValueOf<R>, ActionErrorOf<R> | ServerError | ConnectionLost>
  readonly waiting: boolean
}

StartOptions interfacesrc/client/runtime.tsx

Mount the app. Called from src/main.tsx with the generated route table.

interface StartOptions {
  /** Scene tests: no devtools, no service worker. */
  readonly test?: boolean
  /**
   * The "Add to home screen" prompt on phones and tablets (from the second visit on). `false` turns it off; so does
   * `app({ installPrompt: false })`.
   */
  readonly installPrompt?: boolean
}

SignInProviders typesrc/client/runtime.tsx

The sign-in the server offers. known once it answered; google when "Sign in with Google" works here; note says why not (the dev server offline, or not on localhost). Deployed and on the dev server it is the same: Google.

type SignInProviders = { readonly known: boolean; readonly google: boolean; readonly note?: string }

AnyForm typesrc/client/index.ts

Any form, for components that take a form as a prop: { form: AnyForm }.

type AnyForm = import("./runtime.tsx").Form<any, any>

ModalDef interfacesrc/client/modal.tsx

interface ModalDef<Props, A> {
  readonly "~canica/modal": true
  readonly alert: boolean
  readonly view: (props: Props) => ReactNode
  /** Open it and wait until it closes. */
  open(...props: {} extends Props ? [props?: Props] : [props: Props]): Promise<ModalResult<A>>
  /** In the modal's own component: how to close it. */
  useClose(): Close<A>
}

ModalResult typesrc/client/modal.tsx

How a modal ended: the value it was closed with, or cancelled (Escape, outside click, swipe, back, navigation).

type ModalResult<A> = (
  | { readonly _tag: "Done"; readonly value: A }
  | { readonly _tag: "Cancelled"; readonly reason: CancelReason }
) & {
  match<R>(cases: ModalCases<A, R>): R
}

Close typesrc/client/modal.tsx

Close the modal with its result (close("deleted"), or close() for void); close.cancel() without one.

type Close<A> = ([A] extends [void] ? () => void : (value: A) => void) & { readonly cancel: () => void }

ModalCases interfacesrc/client/modal.tsx

interface ModalCases<A, R> {
  readonly done: (value: A) => R
  readonly cancelled: (reason: CancelReason) => R
}

CancelReason typesrc/client/modal.tsx

Modals you await, like the browser's confirm(), but with React inside. A modal is a component; its result type goes first:

export const TodoDetails = modal<"closed" | "deleted">()(({ id }: { id: Id<"todos"> }) => {
  const close = TodoDetails.useClose()   // (value: "closed" | "deleted") => void; close.cancel()
  const todo = useQuery("todo", { id })
  return <><ModalTitle>Todo</ModalTitle> … <Button onClick={() => close("closed")}>Close</Button></>
})

const result = await TodoDetails.open({ id })
result.match({ done: (what) => …, cancelled: () => … })

It renders inside the app (same providers as pages), so every hook works. useClose() belongs to the modal's own component: everything that closes it lives there (not in child components, not passed down as a prop). Opening a modal adds a history entry (same URL): the back button or gesture closes it. Desktop shows a dialog, phones a bottom sheet (canica/ui registers the presentation). Open modals are a stack of independent modals: only the top one shows, the others wait folded away (still mounted), and closing one closes only that one (its caller gets the result; the one under it shows again as it was). A flow of steps that belong together is one modal with steps, not a modal that opens another.

type CancelReason = "dismissed" | "back" | "navigated"

QueryCases interfacesrc/client/types.ts

Every state of a query, each with its own view. All three are required.

interface QueryCases<A, E, R> {
  readonly loading: () => R
  readonly failure: (error: E) => R
  readonly success: (value: A) => R
}

Register interfacesrc/client/types.ts

Filled in by the generated src/routes.gen.ts:

declare module "canica/client" {
  interface Register {
    server: typeof import("../server/index.ts").default
    routes: { "/": typeof import("./routes/index.tsx").default, ... }
    emails: typeof import("../server/emails.tsx").emails // when there is one
  }
}
interface Register {}

QueryName typesrc/client/types.ts

type QueryName = keyof QueriesOf<ServerApp> & string

MutationName typesrc/client/types.ts

type MutationName = keyof MutationsOf<ServerApp> & string

ActionName typesrc/client/types.ts

type ActionName = keyof ActionsOf<ServerApp> & string

RoutePath typesrc/client/types.ts

type RoutePath = keyof RouteMap & string

QueryArgs typesrc/client/types.ts

type QueryArgs<N extends QueryName> = ArgsType<QueryDefOf<N>>

QueryValue typesrc/client/types.ts

type QueryValue<N extends QueryName> = SuccessType<QueryDefOf<N>>

QueryError typesrc/client/types.ts

type QueryError<N extends QueryName> = Serialized<ErrorType<QueryDefOf<N>> | InvalidArgs>

MutationArgs typesrc/client/types.ts

type MutationArgs<N extends MutationName> = ArgsType<MutationDefOf<N>>

MutationValue typesrc/client/types.ts

type MutationValue<N extends MutationName> = SuccessType<MutationDefOf<N>>

MutationError typesrc/client/types.ts

type MutationError<N extends MutationName> = Serialized<ErrorType<MutationDefOf<N>> | InvalidArgs> | ServerError | ConnectionLost

ActionArgs typesrc/client/types.ts

type ActionArgs<N extends ActionName> = ArgsType<ActionDefOf<N>>

ActionValue typesrc/client/types.ts

type ActionValue<N extends ActionName> = SuccessType<ActionDefOf<N>>

ActionError typesrc/client/types.ts

type ActionError<N extends ActionName> = Serialized<ErrorType<ActionDefOf<N>> | InvalidArgs> | ServerError | ConnectionLost

QueryResult typesrc/client/types.ts

The state of a live query.

type QueryResult<A, E> = (
  | { readonly _tag: "Loading" }
  | { readonly _tag: "Success"; readonly value: A }
  | { readonly _tag: "Failure"; readonly error: E }
) &
  Matchable<A, E>

MutationResult typesrc/client/types.ts

The outcome of a mutation. Never rejects: server bugs come back as ServerError.

type MutationResult<A, E> =
| { readonly _tag: "Success"; readonly value: A }
| { readonly _tag: "Failure"; readonly error: E }

Status typesrc/client/types.ts

The state of the latest call of a mutation, action or form.

type Status<A, E> =
| { readonly _tag: "Idle" }
| { readonly _tag: "Waiting" }
| { readonly _tag: "Success"; readonly value: A }
| { readonly _tag: "Failure"; readonly error: E }

ServerError interfacesrc/client/types.ts

A bug or outage on the server. Details are in the server log.

interface ServerError {
  readonly _tag: "ServerError"
  readonly message: string
}

ConnectionLost interfacesrc/client/types.ts

The socket dropped after the call was sent and the reply never came: it may have run. (A mutation is first sent again, with the same id, so the server runs it at most once; this is what is left when that fails too.)

interface ConnectionLost {
  readonly _tag: "ConnectionLost"
  readonly message: string
}

UploadError typesrc/client/types.ts

Why an upload was refused or did not finish.

type UploadError =
| { readonly _tag: "FileTooLarge"; readonly maxBytes: number; readonly message: string }
| { readonly _tag: "StorageFull"; readonly message: string }
| { readonly _tag: "Unauthenticated"; readonly message: string }
| { readonly _tag: "Forbidden"; readonly message: string }
| { readonly _tag: "LimitReached"; readonly message: string }
| { readonly _tag: "NoFileStorage"; readonly message: string }
| { readonly _tag: "UploadFailed"; readonly message: string }
| ConnectionLost

SearchParamName typesrc/client/types.ts

The search params some page declares (page({ search: { q: … } })): what <SearchInput param> accepts. Any name before the app's routes are registered (src/routes.gen.ts).

type SearchParamName = Register extends { routes: infer R }
? { [P in keyof R]: R[P] extends PageDef<any, infer S> ? keyof S & string : never }[keyof R]
: string

Id typesrc/server/fields.ts

A row id tagged with its table. Id<"todos"> is not assignable to Id<"users">.

type Id<Table extends string> = string & { readonly [IdBrand]: Table }

UserId typesrc/server/fields.ts

A Canica user reference (guest or signed in).

type UserId = string & { readonly [UserIdBrand]: "UserId" }

FileId typesrc/server/fields.ts

The id of an uploaded file (file() fields, useUpload(), files.url(id)).

type FileId = Id<"_files">

EmailId typesrc/server/fields.ts

The id of a queued email: what (yield* Email).send(…) returns; (yield* Email).status(id) reads its state.

type EmailId = Id<"_emails">

EmailState typesrc/server/services.ts

Where an email is: queued (waiting for its turn, or for its next try), sending (with the platform's relay now), sent (the platform took it), or failed (see reason; not tried again). The same everywhere: deployed, on the dev server and in tests (where nothing leaves: the dev outbox shows it).

type EmailState = "queued" | "sending" | "sent" | "failed"

EmailStatus interfacesrc/server/services.ts

What (yield* Email).status(id) tells about one email.

interface EmailStatus {
  readonly id: EmailId
  readonly template: string
  /** The recipient (check it is the viewer before showing it to them). */
  readonly to: UserId
  readonly state: EmailState
  /** Why it failed (`state: "failed"`); null otherwise. */
  readonly reason: EmailFailure | null
  /** The last problem in words: why it failed, or why the last try did not go through (a `queued` email being retried). */
  readonly message: string | null
  /** Tries so far (a try that could not reach the relay is tried again, up to 6 times over about a day). */
  readonly attempts: number
  /** When it was queued (epoch ms). */
  readonly queuedAt: number
}

EmailFailure typesrc/server/services.ts

Why an email failed: the person unsubscribed, is not-a-recipient any more (access, no sign-in proof), the daily limit, the address bounced, they complained (marked it as spam), the app is suspended from sending, sending is off on the platform, the body was invalid, the template is gone or failed to render, or the relay could not take it (after its last try).

type EmailFailure = "unsubscribed" | "not-a-recipient" | "limit" | "bounced" | "complained" | "suspended" | "off" | "invalid" | "template" | "relay"

ImageSize typesrc/core/image-sizes.ts

Named sizes: thumb 320 px wide, medium 640, large 1280, full the original file.

type ImageSize = "thumb" | "medium" | "large" | "full"

ImageWidth typesrc/core/image-sizes.ts

type ImageWidth = (typeof IMAGE_WIDTHS)[number]

FileUrlOptions interfacesrc/core/image-sizes.ts

interface FileUrlOptions {
  /** `"thumb"` (320 px wide), `"medium"` (640), `"large"` (1280) or `"full"` (the original, the default). */
  readonly size?: ImageSize
  /** A width in pixels instead, snapped up to 160, 320, 640 or 1280 (larger: 1280). */
  readonly width?: number
}

Re-exported

From react, as they are: ReactNode, CSSProperties, FormEvent, ChangeEvent, KeyboardEvent, MouseEvent, PropsWithChildren.