Kitten

Technical Manual sections
🐱 Installing Kitten…

  • Development install detected.
  • Runtime v24.22.2 already exists, not updating.
  • Skipping npm install step (pass --npm to NOT skip)
  • Creating distribution build.

  ╭─ Building Kitten distribution.
  │
  ├─── Deleting existing dist/ folder. 
  ├─── Creating dist/ folder. 
  ├─── Updating version. 
  │
  ├─── Building Kitten (main process).
  │     
  │       dist/kitten-bundle.js  14.6mb ⚠️
  │     
  │     ⚡ Done in 143ms
  │
  ├─── Building Kitten (update guard).
  │     
  │       dist/update-guard.js  21.9kb
  │     
  │     ⚡ Done in 2ms
  │
  ├─── Building Kitten (ES Module loader).
  │     
  │       dist/loader-bundle.js  2.7mb ⚠️
  │     
  │     ⚡ Done in 22ms
  │
  ├─── Installing dependencies for Kitten's internal web app.
  ├─── Copying Kitten's internal web app.
  │
  ├─── Building Kitten Crypto(graphy) module (version ^1) for browser.
  │     
  │       dist/web/🐱/library/crypto-1.js  86.3kb
  │     
  │     ⚡ Done in 5ms
  │
  ├─── Building Kitten Key Store module (version ^1) for browser.
  │     
  │       dist/web/🐱/library/key-store-1.js  34.7kb
  │     
  │     ⚡ Done in 4ms
  │
  ├─── Copying Kitten images.
  ├─── Copying Prism theme (version ^1) (for syntax highlighting in error messages).
  │
  ├─── Copying/minifying htmx distribution (version ^2 pre-release; our own fork).
  │     
  │       lib/htmx-2-min.js  56.9kb
  │     
  │     ⚡ Done in 4ms
  │
  ├─── Building htmx idiomorph extension (idiomorph version ^0.8.0; our own copy).
  │     
  │       lib/idiomorph-htmx-min.js  751b 
  │     
  │     ⚡ Done in 1ms
  │
  ├─── Copying htmx WebSocket extension (ws). (version ^2 pre-release)
  ├─── Copying kitten-1.js and kitten-hot-reload-1.js (version ^1).
  │
  ├─── Building/minifying Kitten Alpine.js module (version ^1).
  │     
  │       dist/web/🐱/library/kitten-alpine-1.js  101.5kb
  │     
  │     ⚡ Done in 5ms
  │     
  │       lib/kitten-alpine-1-min.js  45.2kb
  │     
  │     ⚡ Done in 4ms
  │
  ├─── Copying/gzipping Alpine.js distribution (version ^3).
  ├─── Copying Water.css distribution (version ^2).
  ├─── Copying Kitten Process Manager script (used in development mode).
  ├─── Copying kitten sixel (because cute).
  ├─── Copying kitten init command resouces.
  ├─── Writing package file (to set ECMAScript module mode and pin esbuild).
  ├─── Copying launcher script (kitten command).
  ├─── Making launcher script executable.
  ├─── Copying installer and runtime checksums.
  ├─── Generating contributors list.
  │
  ╰─ Done!

  • Copying app directory.
  • Runtime v24.22.2 already exists, not updating.

Installed.

╭───────────────────────────────╮
│ macOS Additional Instructions │
╰───────────────────────────────╯

  1. Update your system’s path to add the location of the kitten command.

     zsh (default shell on macOS):

     echo "export PATH=$PATH:~/.local/bin" >> ~/.zshrc
     source ~/.zshrc

     Fish shell

     echo 'set -gx PATH "~/.local/bin" "$PATH"' >> ~/.config/fish/config.fish
     source ~/.config/fish/config.fish

  2. Add localhost aliases to your hosts file.

     If you want to test peer-to-peer apps locally, edit your /etc/hosts file
     to ensure your localhost line resembles the one below:

     127.0.0.1  localhost place1.localhost place2.localhost place3.localhost place4.localhost

Run using: kitten [path to serve]
The installer running from a Kitten source checkout (a development install).

Kitten’s installer is a single Bash script (install) that has customised behaviour depending on whether it is:

It runs a development install when it is run from a file that has an executable build script next to it, and a web install otherwise. (When the script is piped into Bash, BASH_SOURCE[0] is empty.)

The installer has a third mode, install --stage <directory>, which KittenPackage uses to prepare a downloaded Kitten package for automatic updates, the kitten update command, and the kitten deploy command. In this mode, the installer checks the package, installs its runtime and its dependencies, and exits without switching to it.

Kitten and its installer are supported on Linux and macOS. The installer exits on any other operating system.

The installer also exits on any processor architecture other than x86_64, aarch64, and arm64. (The mapArchitecture() function maps these to the x64 and arm64 Node.js builds.)

The installer script is written for Bash version 3.2, the version of Bash that macOS ships with, so it doesn’t use newer Bash features and refuses to run on Bash versions earlier than 3.

Flowchart: The installer flow

  1. Decide how to install Kitten (see above).

    a. In a development install, the installer first installs the runtime set in the runtimeVersion variable (see step 2, verified against build-templates/runtime-checksums) and points the runtime symlink and the kitten-node and kitten-npm commands at it, as the build needs Kitten’s Node.js and npm. Then it runs npm install if you pass the --npm flag, if there is no node_modules folder, or if package-lock.json is newer than node_modules/.package-lock.json. Finally, it runs the build script and copies the dist/ folder it creates into versions/.incoming in Kitten’s data home.

    If you pass a positional argument other than --npm to the installer in a development install, the installer interprets it as the path of a Kitten package file to install instead of building Kitten from source. (A relative path is relative to the folder you ran the installer from.) A Kitten package file is what’s served from kittens.small-web.org when Kitten is being installed via the single-line installation command from the Web.

    This feature lets you test these package files locally.

    Note that the npm being run is Kitten’s own npm from the runtime the installer downloaded. A system-wide Node.js installation is not required to build Kitten from source or even to develop with Kitten. (The installer rewrites the runtime’s npm launcher so it runs with Kitten’s Node.js, and puts Kitten’s Node.js first in the PATH environment variable when it runs npm.)

    You can run Kitten’s version of Node using the kitten-node command. Similarly, you can run Kitten’s version of npm using the kitten-npm command. Both link to the active runtime, so they run the exact same versions that Kitten does when you invoke the kitten command.

    b. In a web install, the installer downloads the latest Kitten package file from the Kitten deployment site (source) and extracts it into versions/.incoming. If you pass an API version as a positional argument (e.g., curl -sL https://kittens.small-web.org/install | bash -s -- 1), it downloads the latest package for that API version instead.

    The web-based single-line installation command defaults to curl for macOS and wget for Linux. The former is guaranteed to ship with macOS. On Linux, there is no such guarantee so it’s a best effort. (The installer itself downloads with curl if it is available and with wget otherwise. If neither is available, it refuses to continue.)

  2. Install the runtime the distribution needs, if necessary.

    The installer checks that the distribution in versions/.incoming has a node-version file and a version.json file with apiVersion, gitHash, nodeVersion, and versionStamp properties. Then it installs the Node.js version in node-version into runtimes/‹version›, unless that runtime already runs and reports the right version.

    The Kitten runtime is Node.js 24 LTS (currently v24.22.2, set in the runtimeVersion variable in the installer). By managing its own runtime, Kitten does not require Node.js to be installed on the machine and sidesteps versioning issues. Each Kitten version runs on the runtime in its own node-version file. We aim to update the runtime to the latest Node.js LTS release as soon as possible.

    The installer downloads the Node.js archive from nodejs.org and checks its SHA-256 checksum against the distribution’s runtime-checksums file (build-templates/runtime-checksums in the source). If the checksum does not match, it exits.

    Kitten stays on Node.js 24 as Node.js 25 and later need libatomic, which most Linux distributions do not install by default. (See the Node.js issue and the pull request that fixes it.)

    When you change the runtimeVersion variable, also update the esbuild target in src/lib/typeScriptTransformOptions.js, the engines field in package.json, .nvmrc, and build-templates/runtime-checksums. (The comment above the runtimeVersion variable in the installer lists these too.)

  3. Install the Kitten version.

    Each Kitten version is installed in its own folder, versions/‹exact version›, where exact version is <apiVersion>-<gitHash>-<nodeVersion>-<versionStamp> as calculated from version.json. If that folder already contains the same version, the installer uses it and discards versions/.incoming, as a running server may be using it. Otherwise, it runs npm install in the distribution to install esbuild for this platform (copying node_modules from the previous version first, if package.json has not changed) and moves the distribution to versions/‹exact version›.

  4. On a server with a deployed Kitten service, hand over to kitten update.

    If this is a web install and a Kitten systemd service unit exists (systemd/user/kitten.service in your configuration folder), the installer runs the new version’s kitten update command and exits with its exit code. The kitten update command then updates Kitten (and the app, if it declares a matching engines.kitten field) the same way that Check now on the Kitten Settings page does. The installer does not switch the active version itself in this case.

  5. Activate the new version and prune old ones.

    The installer points the app symlink at versions/‹exact version› and the runtime symlink at runtimes/‹version›, and links the kitten, kitten-node, and kitten-npm commands in ~/.local/bin. It then removes all versions except the new and previous ones, and all runtimes except the ones used by those two versions. Finally, it creates Kitten’s data folder (data/), if necessary.

  6. On Linux, lower the start of the unprivileged port range to 80, if necessary (so Kitten can run on ports 443 and 80).

    If the net.ipv4.ip_unprivileged_port_start setting is above 80, the installer sets it to 80 for the current session with sysctl and persists the change in /etc/sysctl.d/99-reduce-unprivileged-port-start-to-80.conf.

    This requires sudo access and may prompt you for your password.

    Privileged ports is a concept that dates back to mainframe computers. It made sense back then but it doesn’t today. Of the platforms Kitten supports, Linux is the only one that still clings to this archaic concept.

    One of the design principles behind Kitten is that Kitten should run the same regardless of whether you’re in a development or deployment environment without requiring the use of heavyweight technologies like Docker. So Kitten running with TLS locally and defaulting to ports 443 and 80 (for redirections) and behaving exactly as it does in deployment is a feature, not a bug.

    Furthermore, Kitten is designed to run one site/app on one machine (VPS, single-board computer, etc.) Running multiple sites/apps on one Kitten install or running Kitten under Docker, etc., in deployment is not a planned or supported feature. Again, this is to keep things as simple as possible and make the deployment process (e.g., using Catalyst) as quick and seamless as possible to enable everyday people who use technology as an everyday thing to get started on the Small Web as easily and effortlessly as possible.

  7. Show platform-specific post-installation instructions, if necessary.

    After printing how long the installation took (on Linux) or “Installed.” (on macOS), the installer shows:

    • On macOS, how to add ~/.local/bin to your path in zsh and Fish shell, and how to add localhost aliases for place1.localhost to place4.localhost to your /etc/hosts file. (These aliases are used when testing peer-to-peer Small Web apps locally during development.)

    • On Linux, how to add $HOME/.local/bin to your path, if it isn’t in your path already.

  8. Show the syntax for running the kitten command (Run using: kitten [path to serve]) and exit.

The installer installs Kitten in Kitten’s data home and sets the data home’s mode to 700. (See Data on disk for where the data home is and what it contains.)

Keeping the previous version on disk is what allows a production server to roll back an automatic update that fails to start. (The installer automatically migrates older installations – where app and runtime were folders – to the current layout.)

Source code:

🐱 Kitten
   by Aral Balkan, Small Technology Foundation

   Version 1-19e9fc-24.22.2-20261116114940
   Born 2026/11/16 at 11:49:40 UTC (Scorpio)
   Fav. colour #19e9fc ███
   API version 1
   Runtime Node.js 24.22.2
 ╭───────────────────────────────────────────╮
 │ Like this? Fund us!                       │
 │                                           │
 │ We’re a tiny, independent not-for-profit. │
 │ https://small-tech.org/fund-us            │
 ╰───────────────────────────────────────────╯
   Need help?
   Tutorials • Reference • Issues

⌛ Routes (Kitten’s internal web app’s): 5.055ms
⌛ Routes (your app’s): 1.056ms

🌍 Domain  https://localhost 
📂 Source  🏠/kitten-demo
💾 Data    Open app data folder

╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌

🔒 Don’t forget to create your identity

   One-time use identity creation link

╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌

🐢 To launch interactive shell, press the [s] key.

   Server is running and listening for connections…
The kitten command serving a new project, in a terminal that doesn’t support sixel graphics.

The launcher is a Bash script (build-templates/kitten), named kitten, in the folder of each Kitten version. The installer links ~/.local/bin/kitten to app/kitten, so the kitten command runs the launcher of the active version. The launcher runs the main process using the Kitten runtime with loader customisations.

Specifically, it:

  1. Saves the folder the kitten command was run from and changes the working directory to the folder of the Kitten version (the real path of the launcher).

  2. Finds its runtime in runtimes/‹version›/bin/node, using the version in its own node-version file. If that runtime is missing, it exits and asks you to run the installer again.

  3. Unsets the PRODUCTION environment variable unless it is true. Then, in production (PRODUCTION=true), if an update is pending (updates/pending exists in Kitten’s data home), runs the update guard (update-guard.js, built from src/entry/update-guard.ts; see Updates). If the guard exits with 3, it has pointed app at another version, and the launcher replaces itself with that version’s launcher (exec). Any other non-zero exit code ends the launcher with that code.

  4. Decides whether to run the Kitten Process Manager or the Kitten bundle directly. It runs the Kitten bundle directly:

    • In production (PRODUCTION=true).

    • When FLAME_GRAPH=true or INSPECT=true is set.

    • For the commands in its own list: run, db, _db, deploy, status, logs, start, stop, restart, enable, disable, update, uninstall, version, and help (and the --version and --help flags).

    In development, it runs the process manager for anything else. This includes the serve command (the default command, so also a bare path to serve) and any command that is missing from its list.

    Before you add a command, see the warning in Command-line interface (CLI).

    With FLAME_GRAPH=true, the launcher runs the Kitten bundle directly, as the 0x flame graph module doesn’t work with Node’s cluster module, which the Kitten Process Manager uses. Kitten still runs in development. (The launcher installs 0x globally with kitten-npm install -g 0x on every flame graph run.)

  5. Launches Kitten’s runtime (the Node.js version in its node-version file, installed by the Kitten installer) to run the main process using the ECMAScript Module loading customisations found in the loader script, setting:

    • The QUIET=true environment variable, to turn off console output from some of the modules used by Kitten (e.g., Auto Encrypt and JSDB).

    • --import ./loader-bundle.js to register the loader script’s module hooks before the main process starts.

    • 0x -o -- if the FLAME_GRAPH=true environment variable was set.

    • --inspect-brk if the INSPECT=true environment variable is set. In this mode, the launcher runs the Kitten bundle directly.

    • --enable-source-maps so that, in development, an error thrown in a TypeScript file compiled by the loader is reported at the correct line in the TypeScript source. (The loader adds inline source maps in development only, and the Kitten bundle does not have source maps.)

    • Kitten’s --working-directory to the directory that the kitten command was run from.

    In development, the launcher replaces itself with the process manager (exec), so no Bash process is left running alongside it. In every other case, it runs Node.js as a child process and waits for it to exit.

Source code:

The main process is different based on whether Kitten is running in development or production:

Flowchart: From the kitten command to the CLI

The Kitten Process Manager runs the Kitten bundle in a worker process using the Node cluster module to automatically restart it on restart requests (e.g., when the source code of the app/site being served changes, or after an uncaught exception).

Specifically, it:

  1. Sets the working directory of its workers to its own folder (so --import ./loader-bundle.js resolves) and records the version that the app symlink points to.

  2. Forks a worker with cluster.fork(). The worker imports kitten-bundle.js.

  3. Listens for the worker’s exit event.

  4. If the exit code is 99, which is Kitten’s code for a restart request (restartRequest in src/lib/system-exit-codes.ts), checks whether the app symlink now points to a different Kitten version. If it does, the process manager replaces itself with that version’s launcher (process.execve()), with the same arguments, in the folder the kitten command was run from. Otherwise, or if that fails, it goes back to step 2.

  5. For any other exit code, exits with that code.

This ensures that a development server restarts into the new version after you run the installer, as the installer removes all versions except the active and previous ones.

Sequence Diagram: The development reload loop

Basically, Kitten Process Manager does what we would use a module like Nodemon for but in a very focussed manner in under 80 lines of code.

Source code:

The loader script registers module customisation hooks with module.registerHooks(). It registers a hook that compiles TypeScript and then imports src/lib/loader.ts, which registers Kitten’s own resolve and load hooks. The build bundles both into loader-bundle.js, which the launcher loads with --import ./loader-bundle.js. (The test scripts in package.json load src/entry/loader.js directly to run Kitten’s modules from source.)

Specifically, it:

  1. Resolves imports of files with Kitten’s compound extensions (.page.js, .get.js, .post.js, and the other HTTP method routes, .socket.js, .component.js, .layout.js, .fragment.js, .script.js, .styles.js, and .page.md), and of TypeScript files, as ECMAScript modules.

  2. Wraps non-JavaScript files in JavaScript modules that render them as Kitten HTML: Markdown pages (.page.md, including the layout, script, stateful, and constructor keys in their front matter), and CSS, Markdown, and HTML fragments (.fragment.css, .fragment.md, and .fragment.html).

  3. Compiles TypeScript files to JavaScript with esbuild, using typeScriptTransformOptions() in src/lib/typeScriptTransformOptions.js.

Using compound extensions enables Kitten to apply specialised logic to different types of files while enabling authoring tools (editors, etc.) to work with them without requiring any additional tooling (like a custom language server).

The launcher loads the loader before the main process so that the hooks apply to every import that follows. Kitten’s own code is already bundled into kitten-bundle.js, so in an installed Kitten instance the hooks compile the app/site Kitten is serving, its app modules, and Kitten’s built-in web app in web/. The hooks run in the main thread, and each module is compiled once per process.

Source code:

Kitten is always run from a Kitten distribution created using the build script and installed using the installer, even during development. This ensures that what we’re testing in development is exactly the same as what we’ll be running in production. (The unit and regression test files import Kitten’s modules from source, but the Kitten servers that they and the end-to-end tests start run from the installed distribution.)

The entrypoint to the Kitten bundle is the main script.

The build creates the distribution in dist/ (see Building).

The main script is the entrypoint to the Kitten bundle and handles basic bootstrapping tasks before launching the command-line interface (CLI).

Specifically, it:

  1. Creates the global kitten object and populates it with the version property. (Other properties are added later during Kitten’s start-up process.)

  2. Initialises kitten.log, Kitten’s sectioned logger, whose sections the LOG environment variable turns on.

  3. If Kitten’s data folder (paths.KITTEN_DATA_DIRECTORY) does not exist, runs the data encapsulation migration. This moves the databases, uploads, and interactive shell history of each app from the separate databases/, uploads/, and repl/ folders of older Kitten versions into one folder per app in data/.

  4. Initialises Kitten’s global internal database (kitten.__db, in data/__db). Unlike Kitten’s internal and app databases, this database belongs to the Kitten instance, not to the app Kitten is serving.

  5. Instantiates the CLI and calls its parse() method, which runs the command.

Source code:

The Kitten command-line interface (CLI) parses the arguments passed to the kitten command and runs one of the Kitten commands. The main script creates it and calls its parse() method, which displays the Kitten header and then passes process.argv to the lightweight sade module.

The CommandLineInterface constructor registers each command with its options and its action, which, for most commands, is the default export of the command’s file in src/cli/commands. (The actions of the database commands are named exports of db.ts, and the actions of the version and help commands are defined in src/cli/index.ts itself.) sade also passes options that a command does not declare to its action. (For example, kitten db --port=444 opens the databases of the app that runs on port 444.)

The serve command is registered with {default: true}. So, when Kitten is invoked without a command, sade runs the serve command and treats the first argument, if any, as the path to serve: kitten, kitten ., and kitten serve . are equivalent.

The constructor also replaces two of sade’s methods: help() exits the process after displaying help, and _version() only exits, since the header already displays the version.

The launcher passes the --working-directory option to every command. The launcher changes to the Kitten distribution folder before it starts Node.js, so it passes the directory you ran kitten from in this option.

The launcher has its own list of command names. In development, it runs the Kitten bundle directly for the commands in that list, and the Kitten Process Manager for anything else, including serve and a bare path. So, when you add a command that must not run under the Kitten Process Manager, add it to both src/cli/index.ts and the launcher.

(The shell, init, add, and check commands, and the -v and -h options, are not in the launcher’s list, so they run under the Kitten Process Manager. This works because they never exit with the restart request code, 99.)

To see the full list of available commands, use the kitten help command. The Command-line interface (CLI) section of the reference covers how to use each command and its options. The Kitten commands section below covers how each one works.

The Kitten header is displayed at the top of every CLI command.

When Kitten is not running in production (the PRODUCTION environment variable is not set) and standard input is a terminal (TTY), Kitten asks the terminal whether it supports sixel graphics. It sends it the Primary Device Attributes request (ESC [ 0c) and treats a reply that contains ;4 as support. If the terminal supports sixels, the header starts with the image of the Kitten logo in kitten-day.sixel (which the build script copies into the Kitten bundle), followed by “Kitten”. Otherwise, it starts with “🐱 Kitten”.

Kitten runs this check once, when header.ts is first imported. It uses our own copies of Richie Bendall’s supports-sixel and replied modules. (The npm release of replied leaves standard input closed, so any later read from it, e.g., by readline, crashes silently.)

Following this are:

Coloured output is provided via the chalk module. Terminal links are created using our own terminal-link module, which wraps the text of each link in an OSC 8 hyperlink sequence and gives it a dotted underline (as some terminals do not underline links themselves).

Source code:

This is a full list of the Kitten commands, detailing what they do and how they do it. Each command is in its own file in src/cli/commands, and the larger ones call into modules in src/lib. For how to use each command and its options, see the Command-line interface (CLI) section of the reference.

The commands are in four groups:

The serve command is the default command. So kitten serve and kitten are equivalent.

It creates and initialises the Kitten Server with Server.getInstanceAsync(), passing it the options declared by the serve command: --domain, --aliases, --port, --open, --working-directory, and the two options that a Small Web host (Catalyst) passes, --domain-token and --small-web-host-domain. (See Domains and domain aliases.)

Before it creates the Kitten Server, the serve command calls setBasePath() with the --working-directory option and the path to serve (default: .). The setBasePath() function:

  1. Resolves the path to serve against the working directory, so a relative path works from wherever you ran kitten.

  2. Throws if that path does not exist. (The serve command then reports the error and exits with code 1.)

  3. Uses the src folder in that path as the base path, if there is one.

  4. Stores the base path in the basePath environment variable, which the rest of Kitten reads (e.g., Files.ts, Routes.ts, and AppDatabase.ts).

  5. Changes the current working directory to the base path.

The base path, along with the domain and the port, is part of the app’s project identifier (see getProjectIdentifierForDomain() in Utils.ts). Kitten stores each app’s data in a directory named using its project identifier, so the same app served from another folder, on another domain, or on another port has its own, separate data.

The run command is the local counterpart of deploy. It clones an app from a git repository and serves it as a regular process.

It refuses clone URLs that do not start with https:// and end with .git (the same check as the deploy command), deletes any earlier clone of the repository, and clones it into ~/.local/share/small-tech.org/kitten/clones/ (paths.KITTEN_CLONES_DIRECTORY), in a folder named after the URL (e.g., codeberg.org.aral.my-app for _https://codeberg.org/aral/my-app.git_). It then calls the serve command’s function with the clone’s path and the options you passed.

The run command serves the repository’s default branch and, unlike the deploy command, does not choose a Kitten release from the engines.kitten field. Since the clone path is the same on every run, so is the app’s data directory (for the same domain and port), and its data persists between runs.

Note that the launcher runs the run command without the Kitten Process Manager, so a restart request (exit code 99) ends the process.

The init command initialises a type-safe Kitten project in the working directory, in TypeScript (ts, the default) or JavaScript (js). The Init class does the work, one method per step, and skips any file that already exists. It:

  1. Runs npm init --init-type=module --init-license=AGPL-3.0-only -y if there is no package.json.

  2. Installs typescript and @small-web/kitten-types as development dependencies.

  3. Writes the root config (tsconfig.json or jsconfig.json), which references a server config (tsconfig.server.json or jsconfig.server.json) and a client config (tsconfig.client.json or jsconfig.client.json), and writes client-globals.d.ts. (When it writes the client config, it also adds .tsbuildinfo/ to the project’s .gitignore file, if there is one.) If a root config exists that does not reference both, it prints how to fix it and writes none of these files.

  4. If the root config references both, sets the typecheck script in package.json to npx tsc -b (or npx tsc -b jsconfig.json), unless you have set it to a command of your own.

  5. Writes globals.d.ts, which imports @small-web/kitten-types.

  6. Sets the engines.kitten field in package.json to the running Kitten’s API version, if it is missing. (A deployed app follows the newest Kitten release for this API version.)

  7. Writes LICENSE (AGPL version 3.0), README.md, CHANGELOG.md, .gitignore, and a sample src/index.page.ts (or .js). It does not write the index page if there is a src folder or an index page at the root of the project.

The templates are in src/cli/commands/init, which the build script copies to init in the Kitten bundle (Init.RESOURCES_BASE_PATH). The client config excludes server files using the extensions in DYNAMIC_ROUTE_EXTENSIONS and DEPENDENCY_EXTENSIONS from Utils.ts, so it stays in step with the file types Kitten knows.

Note that the init command runs the npm on your PATH, not the one in Kitten’s runtime.

The add command adds an aspect to an existing project. The only aspect that’s currently implemented is type safety: types (the default), or its aliases type-safety and kitten-types.

The type safety aspect runs the init command’s Init class with typesOnly set, so it runs the type-safety steps (1 to 5) and skips the rest, including the engines.kitten field. (This is because the engines.kitten field sets the API version that a deployed app’s automatic updates follow, and adding types must not change it.) It uses JavaScript if the project has a jsconfig.json and no tsconfig.json, and TypeScript otherwise.

The check command checks a project’s source code for what must change to run on the installed Kitten. The work is in src/lib/check/, and each check is a module in checks/ with an ID, an API version, a fixable flag, a link (a change log anchor, or url for a reference section), and a check() function that returns findings. registry.ts lists every check.

The loadProject() function in project.ts reads the project the way start-up does: it crawls the base path (src/ when it exists) with routedFilePaths() from src/Files.ts, and each app_modules folder Kitten looks in, and derives the routes with routeFilesFor(). It never imports a file from the project, so an app module that calls a payment provider or writes to a database when it is imported does nothing. sources.ts parses each file with acorn:

The template checks never contain a copy of the rules in src/lib/html.ts. Instead, probe.ts renders each kitten.html, kitten.markdown, kitten.css, and kitten.js template with probe values, then renders it again with a string probe in each field whose expression is a string or unknown (other than tag names and attribute names). It also checks whether the template displays markup as escaped text (isEscapedInText()) in each field whose expression is an array of strings or a kitten.md.render() call. When the html() function throws, the engine maps the error’s rule property to the check that the field belongs to. The project checks call the functions that start-up uses (routeTableProblems(), reservedPathProblems(), eventHandlerExportsBesideClass(), and enginesKittenOf()), so they can’t disagree with it.

The run() function in run.ts runs each check over the project and returns every finding. (A check’s apiVersion records the API version that introduced the change it checks, for the release process. The run() function doesn’t read it.) report.ts formats the output, and fix.ts applies the --fix option: it groups the edits by file identity (dev and ino), drops a finding whose edits overlap ones it has chosen, and writes only when every file still has the text that the checks read. A file is committed when git hash-object gives the blob that git ls-tree HEAD lists for it, run from the file’s own folder without the GIT_ variables of the process.

The database commands inspect and change an app’s databases from the command line. The db command works on the app’s database (kitten.db) and the _db command on Kitten’s internal database for the app (kitten._db). Each has the same subcommands: info (the default, so kitten db is kitten db info), delete, and tail.

All of them start with initialiseDatabases(), which:

  1. Sets the jsdbCompactOnLoad environment variable to false, so opening the databases does not compact their tables.

  2. Calls setBasePath() with the working directory and ., so you must run the command from the app’s folder.

  3. Works out the domain and port with getDomainsAndPort() (default: localhost and 443) and calls Globals.initialise(), which finds the app’s data directory from its project identifier.

  4. Opens InternalDatabase and AppDatabase, as the server does.

Then:

The database commands declare only the --working-directory option (and the tail subcommands, the --all option), but sade passes the --domain and --port options through, so you can use them to reach the databases of an app you serve on another domain or port.

The deploy command deploys an app from a git repository as a systemd user service, which starts at boot and restarts on failure. The command only calls deploy() in src/lib/deploy.ts and exits with 1 if it throws. Kitten also exposes the deploy() function as kitten.deploy (in globals.ts) for the /💕/deploy/ route and the app page of the Kitten Settings.

The deploy() function:

  1. Uses the --domain option, or the machine’s hostname, as the domain, and throws if it is not a valid hostname. It also throws if you pass the --small-web-host-domain option without the --domain-token option.

  2. Opens the global internal database to find out whether a Small Web host (Catalyst) is deploying it (__db.state.isBeingDeployedByDomain, which the hidden --is-being-deployed-by-domain option also sets). If so, it reports each step to the host at https://<Small Web host domain>/domain/<domain token>/status/<status>.

  3. Checks that systemctl and journalctl exist (ensure.canEnableService()).

  4. Throws for clone URLs that do not start with https:// and end with .git, and while an update is pending (updates/pending exists).

  5. Sets the machine’s hostname to the domain with sudo hostnamectl set-hostname if they differ.

  6. Clones the repository into a new folder in ~/.local/share/small-tech.org/kitten/deployments/ (paths.KITTEN_DEPLOYMENTS_DIRECTORY), named after the current timestamp and the URL.

  7. Chooses the branch with chooseDeployTarget() (deployTarget.ts): release if the repository has one, otherwise the remote’s default branch (or main). If that branch declares an API version in the engines.kitten field in its package.json (or src/package.json) other than the running Kitten’s, it also chooses the newest signed Kitten release for that API version. If there is no such release, it deletes the clone and throws.

  8. Deletes the clone and throws if the repository doesn’t have that branch. Otherwise, checks out the head of the branch as a detached HEAD and, if it chose a Kitten release, stages and activates it with KittenPackage (see Update).

  9. Writes the systemd unit to ~/.config/systemd/user/kitten.service (paths.KITTEN_SYSTEMD_UNIT_PATH). Its ExecStart runs ~/.local/bin/kitten with the deployment path, --domain, and any --aliases, --small-web-host-domain, and --domain-token. It sets PRODUCTION=true, Restart=on-failure, and the deployment path as the working directory.

  10. Enables lingering for the account with enableLingering() (deployedService.ts), first with loginctl enable-linger and then with sudo -n loginctl enable-linger, so the service runs when nobody is logged in. It warns you if neither works.

  11. Runs systemctl --user daemon-reload, systemctl restart --user kitten, and systemctl enable --user kitten.

Flowchart: The deploy flow

There is one Kitten service per account (the unit is always kitten), so deploying again replaces the app that is running. The unit does not pass the --port option, so a deployed app always runs on port 443.

Note that each deployment is in a new, timestamped folder, and the base path is part of the project identifier. So an app that you deploy again starts with an empty data directory. The earlier deployment folders and their data directories stay on disk.

The status command runs systemctl --user --no-pager --full --lines=0 status kitten and, when that exits, follows the service’s logs with journalctl --user --follow --unit=kitten until you press Ctrl C.

The logs command follows the service’s logs with journalctl --since <since> --no-pager --follow --user --unit kitten. The --since option defaults to 1 hour ago.

The start command starts the service with systemctl --user start kitten.

Like the stop, restart, enable, and disable commands, it first calls serviceStatus() in service-status.ts, which runs systemctl --user is-active kitten and systemctl --user is-enabled kitten, and exits with an error if there is nothing to do (here, if the service is already active).

The stop command stops the service with systemctl --user stop kitten. It exits with an error if the service is not active.

The restart command restarts the service by running systemctl --user stop kitten and then systemctl --user start kitten. It exits with an error if the service is not active.

The enable command enables the service with systemctl --user enable kitten, so systemd starts it at boot. It exits with an error if the service is already enabled.

The disable command disables the service with systemctl --user disable kitten, so systemd no longer starts it at boot. It exits with an error if the service is not enabled.

The shell command opens Kitten’s interactive shell (REPL) on a Kitten server that is not attached to a terminal, like the systemd service.

When standard output is not a terminal, the server’s REPL module listens on 127.0.0.1, port 1337, and starts a Node.js REPL for each connection. (When it is a terminal, you press s in the server’s own terminal instead.) The shell command connects to that port, puts standard input into raw mode, and pipes standard input to the socket and the socket to standard output.

Two details make the remote REPL behave like a local one:

If nothing listens on port 1337, the command reports that the shell is not running and exits with code 1.

The socket has no authentication. Any process on the machine that can connect to 127.0.0.1 can use the shell, with full access to the running Kitten process.

The update command updates Kitten or, on a server with a deployed app, Kitten and the app. It finds out which with readDeployedService() (deployedService.ts), which reads the app path and the domain from the ExecStart line of the systemd unit that the deploy command writes.

It points the currentVersion of KittenPackage (KittenPackage.ts) at the installed Kitten, so it works with the installed version even when you run another build. It asks for releases from its own build’s distribution host: the KITTEN_DISTRIBUTION_HOST environment variable, then the distributionHost property in its own version.json, then the installed Kitten’s (kittens.small-web.org by default).

It stages and activates releases with KittenPackage (see Updates).

Without a deployed service, the updateKitten() function:

  1. Chooses the newest release or, with the --api-version option, the newest release for that API version.

  2. Stops if that release is already installed, and asks you to type “yes” if it is older than the installed Kitten.

  3. Stages and activates the release, and prunes the versions and runtimes that neither the new Kitten nor the one it replaced uses, with prune() (updateConfirmation.ts). The prune() function also removes the snapshots and the staged dependencies of earlier updates (updates/snapshots and updates/staged-dependencies).

With a deployed service, the updateDeployedService() function runs the same update transaction as automatic updates and Check now on the Kitten Settings page:

  1. Deletes a pending update record that the installed Kitten cannot complete (because it has no update-guard.js).

  2. Calls setBasePath() with the app path, opens the app’s AppRepository, and creates an AutomaticUpdates instance whose collaborators point at the deployed app: its data directory on port 443, a request to its home page for the baseline status, and a restart with systemctl --user restart kitten.

  3. Calls check('requested'), which runs the check described in Updates.

  4. Waits for the outcome with waitForOutcome(), which checks updates/history.jsonl for the update’s id every second, for up to twice the record’s start deadline plus 30 seconds.

Flowchart: The update flow

When the service restarts, the update guard and the new server complete the update or roll it back (see Updates).

The command exits with:

The --api-version option is only valid without a deployed service (with one, the command exits with 1). On a server, the API version comes from the engines.kitten field in the app’s package.json.

The uninstall command removes Kitten after you type “yes”. It first displays a WarningBox (src/cli/lib/WarningBox.ts) that lists what it will do. Then it:

  1. Stops the service if it is active, and disables it and deletes its unit file if it is enabled.

  2. Deletes app, runtime, versions, runtimes, and updates in the Kitten data home (~/.local/share/small-tech.org/kitten).

  3. Removes the local certificate authority from the system trust stores with https.removeLocalCertificates() from @small-tech/https (which asks for your password), and then deletes the local certificates in tls/local.

  4. Deletes the kitten symlink in ~/.local/bin.

It does not delete the data directory (which contains every app’s databases), the global (Let’s Encrypt) certificates in tls/global, or the deployments, clones, and tmp directories in the data home.

The version and help commands are aliases for sade’s built-in --version (-v) and --help (-h) options, defined in src/cli/index.ts. Since the Kitten header already displays the version, the version command only exits. The help command displays sade’s help for all commands, or for the command you pass (e.g., kitten help serve), and exits.

Source code:

The Kitten Server contains the primary functionality of Kitten and is a singleton that is asynchronously constructed via its getInstanceAsync() method.

Alongside the HTML renderer (src/lib/html.ts) and the stateful component class (src/lib/KittenComponent.ts), it is among the largest files in Kitten. (It might make sense to break it up further in the future to improve maintainability.)

The Kitten server uses Polka (version 1.0.0-next). Polka runs middleware and routes in the order they are added. It passes errors, and unhandled requests, to Kitten’s error handler in src/ServerError.ts. (See Errors and restarts.)

As the Kitten Server is a singleton, you get a reference to it via its static factory method. Furthermore, since the initialisation of the Kitten Server instance is asynchronous, so is this factory method.

const server = await Server.getInstanceAsync(options)

The factory method returns a promise that either resolves immediately with a reference to the existing Kitten Server instance or does so after constructing and asynchronously initialising one.

Flowchart: Constructing the Kitten Server

The Kitten Server constructor only sets up process-wide behaviour: the stack trace limit, and how the process exits on crashes and signals. It does not configure the instance. The asynchronous initialisation method does everything else.

The constructor:

Flowchart: Initialising the Kitten Server

Attempting to call the initialise() method directly will result in an error. Await the getInstanceAsync(options) method instead to get a reference to the Kitten Server singleton.

Following the initial synchronous construction of the server instance, the singleton factory method awaits the server’s asynchronous initialise(options) method.

This method finishes configuring the Kitten Server by handling any asynchronous tasks that need to be done.

Specifically, it:

Source code:

The Kitten Server determines the main domain and port, as well as any domain aliases, if any, to respond to based on convention and the values present in the --domain, --port, and --aliases command-line options.

Convention:

  1. If a domain is not explicitly specified using the --domain command-line option, the default domain of localhost is used.

  2. If the domain is localhost or one of the localhost aliases – place1.localhost, place2.localhost, place3.localhost, or place4.localhost – the server is local. Its certificate, from Auto Encrypt Localhost, includes localhost, all four aliases, and your machine’s local IPv4 addresses, so the server responds at all of them. (The list of domains itself only contains the main domain.)

    These localhost aliases are used when testing peer-to-peer Small Web apps locally. Run each server with its alias as the --domain, so that each one has its own data, and give each one its own port.

  3. If a port is not explicitly specified using the --port command-line option, the default port of 443 is used.

  4. If the --port option is passed without a value, or, if its value is set to 0 (zero), the operating system assigns a random, available port. Kitten sets kitten.port to that port once the server is listening.

    The app’s data directory depends on its port, and Kitten only knows a random port once the server is listening. So, on a random port, it passes a random number between 100,000 and 199,999 (outside the range of real ports) to Globals.initialise() instead, and each run starts with an empty data directory.

  5. If the server is not local and a list of one or more comma-separated domains (without spaces between them) is provided as the value of the --aliases option, Kitten adds these domains to the list of domains after the main domain. Kitten’s TLS certificate includes the main domain and all aliases, and Kitten serves the same app at all of them. (Kitten ignores the --aliases option for a local server.)

  6. If the shorthand domain alias www is passed in the --aliases list, it is rewritten to its full www.<main domain> value.

  7. If the domain is ipv4 or ipv6, Kitten detects the machine’s external IP address and uses it as the main domain (Web Numbers). For ipv6, it uses the first stable IPv6 address it finds and adds any others to the aliases. If ipv4 is requested and there is no external IPv4 address, the getDomainsAndPort() function throws an error. An IP address is never local, so Kitten provisions a Let’s Encrypt certificate for it with Auto Encrypt.

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.