Technical Manual sections
Reference › Technical Manual › Initialisation
🐱 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]
Kitten’s installer is a single Bash script (install) that has customised behaviour depending on whether it is:
run from a Kitten source checkout (a development install), or,
piped into Bash from the Web (a web install).
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
Decide how to install Kitten (see above).
a. In a development install, the installer first installs the runtime set in the
runtimeVersionvariable (see step 2, verified against build-templates/runtime-checksums) and points the runtime symlink and thekitten-nodeandkitten-npmcommands at it, as the build needs Kitten’s Node.js and npm. Then it runsnpm installif you pass the--npmflag, if there is no node_modules folder, or if package-lock.json is newer than node_modules/.package-lock.json. Finally, it runs thebuildscript and copies the dist/ folder it creates into versions/.incoming in Kitten’s data home.If you pass a positional argument other than
--npmto 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
npmbeing 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’snpmlauncher so it runs with Kitten’s Node.js, and puts Kitten’s Node.js first in thePATHenvironment variable when it runs npm.)You can run Kitten’s version of Node using the
kitten-nodecommand. Similarly, you can run Kitten’s version of npm using thekitten-npmcommand. Both link to the active runtime, so they run the exact same versions that Kitten does when you invoke thekittencommand.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
curlfor macOS andwgetfor 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 withcurlif it is available and withwgetotherwise. If neither is available, it refuses to continue.)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, andversionStampproperties. 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
runtimeVersionvariable 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
runtimeVersionvariable, also update the esbuild target in src/lib/typeScriptTransformOptions.js, theenginesfield in package.json, .nvmrc, and build-templates/runtime-checksums. (The comment above theruntimeVersionvariable in the installer lists these too.)Install the Kitten version.
Each Kitten version is installed in its own folder, versions/‹exact version›, where
exact versionis<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 runsnpm installin 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›.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 updatecommand and exits with its exit code. Thekitten updatecommand then updates Kitten (and the app, if it declares a matchingengines.kittenfield) the same way that Check now on the Kitten Settings page does. The installer does not switch the active version itself in this case.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, andkitten-npmcommands 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.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_startsetting is above 80, the installer sets it to 80 for the current session withsysctland persists the change in /etc/sysctl.d/99-reduce-unprivileged-port-start-to-80.conf.This requires
sudoaccess 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.
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.
Show the syntax for running the
kittencommand (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 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:
Saves the folder the
kittencommand was run from and changes the working directory to the folder of the Kitten version (the real path of the launcher).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.
Unsets the
PRODUCTIONenvironment variable unless it istrue. 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.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=trueorINSPECT=trueis set.For the commands in its own list:
run,db,_db,deploy,status,logs,start,stop,restart,enable,disable,update,uninstall,version, andhelp(and the--versionand--helpflags).
In development, it runs the process manager for anything else. This includes the
servecommand (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 withkitten-npm install -g 0xon every flame graph run.)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=trueenvironment variable, to turn off console output from some of the modules used by Kitten (e.g., Auto Encrypt and JSDB).--import ./loader-bundle.jsto register the loader script’s module hooks before the main process starts.0x -o --if theFLAME_GRAPH=trueenvironment variable was set.--inspect-brkif theINSPECT=trueenvironment variable is set. In this mode, the launcher runs the Kitten bundle directly.--enable-source-mapsso 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-directoryto the directory that thekittencommand 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:
In development: For the
servecommand, the main process is the Kitten Process Manager. It runs the Kitten bundle in a worker process and starts a new worker when Kitten requests a restart. Most other commands run the Kitten bundle directly. (See step 4 of the launcher.)In production: The main process is the Kitten bundle. The
kitten deploycommand runs Kitten as a systemd user service (kitten.service) withPRODUCTION=true(see Errors and restarts for when systemd restarts it). (If you setPRODUCTION=trueyourself outside the service, nothing restarts Kitten when it exits.)
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:
Sets the working directory of its workers to its own folder (so
--import ./loader-bundle.jsresolves) and records the version that the app symlink points to.Forks a worker with
cluster.fork(). The worker imports kitten-bundle.js.Listens for the worker’s
exitevent.If the exit code is
99, which is Kitten’s code for a restart request (restartRequestin 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 thekittencommand was run from. Otherwise, or if that fails, it goes back to step 2.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:
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.Wraps non-JavaScript files in JavaScript modules that render them as Kitten HTML: Markdown pages (
.page.md, including thelayout,script,stateful, andconstructorkeys in their front matter), and CSS, Markdown, and HTML fragments (.fragment.css,.fragment.md, and.fragment.html).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:
Creates the global
kittenobject and populates it with theversionproperty. (Other properties are added later during Kitten’s start-up process.)Initialises
kitten.log, Kitten’s sectioned logger, whose sections theLOGenvironment variable turns on.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/.Initialises Kitten’s global internal database (
kitten.__db, indata/__db). Unlike Kitten’s internal and app databases, this database belongs to the Kitten instance, not to the app Kitten is serving.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:
The author credits (with links to Aral Balkan and Small Technology Foundation).
The version information displayed by
Version.printToConsole(): the exact version, the build date and time as the Kitten’s birthday, the git hash as the Kitten’s favourite colour, the API version, and the Node.js version of the runtime.A box with a link to the funding page for Small Technology Foundation.
A help section with links to the Kitten tutorials, the reference, and the issues.
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:
Development: Serve (the default command), Run, Init, Add, Check, and the database commands.
Deployment: Deploy.
Service management: Status, Logs, Start, Stop, Restart, Enable, Disable, and Shell.
Maintenance: Update, Uninstall, and Version and help.
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:
Resolves the path to serve against the working directory, so a relative path works from wherever you ran
kitten.Throws if that path does not exist. (The
servecommand then reports the error and exits with code1.)Uses the src folder in that path as the base path, if there is one.
Stores the base path in the
basePathenvironment variable, which the rest of Kitten reads (e.g., Files.ts, Routes.ts, and AppDatabase.ts).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:
Runs
npm init --init-type=module --init-license=AGPL-3.0-only -yif there is no package.json.Installs
typescriptand@small-web/kitten-typesas development dependencies.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.If the root config references both, sets the
typecheckscript in package.json tonpx tsc -b(ornpx tsc -b jsconfig.json), unless you have set it to a command of your own.Writes globals.d.ts, which imports
@small-web/kitten-types.Sets the
engines.kittenfield 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.)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:
- JavaScript as it is.
- TypeScript after Node’s
stripTypeScriptTypes()in strip mode, which preserves every offset. A file that strip mode rejects goes through transform mode, and its positions come through the source map, but only on an exact segment hit. esbuild, with the options of Kitten’s loader, decides whether a .ts file parses. A file that only esbuild can parse has no positions. .mts files go through Node’s strip mode only, as Node loads them that way. - Markdown pages, Markdown fragments, and HTML fragments through
markdownModule()(src/lib/markdownModule.ts), the transform that the loader uses. It returns the module’s source and its segments: the runs of text it copies verbatim (each interpolation, and each line of ascript: |orconstructor: |block). A position outside a segment has no line.
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:
Sets the
jsdbCompactOnLoadenvironment variable tofalse, so opening the databases does not compact their tables.Calls
setBasePath()with the working directory and., so you must run the command from the app’s folder.Works out the domain and port with
getDomainsAndPort()(default:localhostand443) and callsGlobals.initialise(), which finds the app’s data directory from its project identifier.Opens
InternalDatabaseandAppDatabase, as the server does.
Then:
The
infosubcommand lists the database folder and its tables or, for a table, its type and its file.The
deletesubcommand asks you to type “yes”, then callsdelete()on the__table__of each table, or of the one table you pass.The
tailsubcommand displays the first three and the last three lines of the table’s file (or all of it, with--all) and then follows the file with tail-file. It formats the first line, which contains the table’s initial value, by running it in avmcontext and passing the result toJSON.stringify(), and highlights each line with cli-highlight.
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:
Uses the
--domainoption, 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-domainoption without the--domain-tokenoption.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-domainoption also sets). If so, it reports each step to the host athttps://<Small Web host domain>/domain/<domain token>/status/<status>.Checks that
systemctlandjournalctlexist (ensure.canEnableService()).Throws for clone URLs that do not start with
https://and end with.git, and while an update is pending (updates/pending exists).Sets the machine’s hostname to the domain with
sudo hostnamectl set-hostnameif they differ.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.Chooses the branch with
chooseDeployTarget()(deployTarget.ts):releaseif the repository has one, otherwise the remote’s default branch (ormain). If that branch declares an API version in theengines.kittenfield 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.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).Writes the systemd unit to ~/.config/systemd/user/kitten.service (
paths.KITTEN_SYSTEMD_UNIT_PATH). ItsExecStartruns ~/.local/bin/kitten with the deployment path,--domain, and any--aliases,--small-web-host-domain, and--domain-token. It setsPRODUCTION=true,Restart=on-failure, and the deployment path as the working directory.Enables lingering for the account with
enableLingering()(deployedService.ts), first withloginctl enable-lingerand then withsudo -n loginctl enable-linger, so the service runs when nobody is logged in. It warns you if neither works.Runs
systemctl --user daemon-reload,systemctl restart --user kitten, andsystemctl 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:
The client sends its terminal size as three bytes – SYN (
0x16), the columns, and the rows – when it connects and whenever the terminal is resized. The server’scontrolChanneltransform reads these messages and setscolumnsandrowson the socket, so the REPL formats its previews to fit.The client’s
renderPreviewCompletiontransform removes the//prefix from the REPL’s preview completions and dims them.
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:
Chooses the newest release or, with the
--api-versionoption, the newest release for that API version.Stops if that release is already installed, and asks you to type “yes” if it is older than the installed Kitten.
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). Theprune()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:
Deletes a pending update record that the installed Kitten cannot complete (because it has no update-guard.js).
Calls
setBasePath()with the app path, opens the app’sAppRepository, and creates anAutomaticUpdatesinstance 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 withsystemctl --user restart kitten.Calls
check('requested'), which runs the check described in Updates.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:
0when the update is confirmed, nothing is newer, or you decline a downgrade.1when the update is rolled back or cannot be prepared.2when another update is in progress, or the outcome is not known in time.
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:
Stops the service if it is active, and disables it and deletes its unit file if it is enabled.
Deletes app, runtime, versions, runtimes, and updates in the Kitten data home (~/.local/share/small-tech.org/kitten).
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.Deletes the
kittensymlink 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:
Throws an error unless the
getInstanceAsync(options)factory method is calling it (i.e., unlessServer.isBeingConstructedViaFactoryMethodistrue). It leaves the flag set, asinitialise()checks it too and then resets it.Sets
Error.stackTraceLimitto 50 (STACK_TRACE_LIMIT).Logs uncaught exceptions and exits with the restart request code (99,
systemExitCodes.restartRequest). This includes unhandled promise rejections, as Node.js raises those as uncaught exceptions. In development, the Kitten Process Manager then starts a new worker. In production, systemd restarts Kitten.Exits with code 0 on
SIGTERMandSIGINTso that JSDB flushes its writes to disk. (JSDB writes its tables on the process’sexitevent, which these signals do not trigger by themselves.)
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:
In production, reads the pending update record, if there is one, and, if Kitten is starting after an update, starts the update’s start deadline (
startDeadline(); see Updates).Determines which main domain and port to run the server under and which domain aliases, if any, to also respond to.
Sets
kitten.domainandkitten.porton the globalkittenobject.Creates the Polka app, with the default export of src/ServerError.ts as its
onErrorhandler andnoMatchHandler()as itsonNoMatchhandler. ThenoMatchHandler()method passes a request that no route responds to on to the error handler as a 404, and responds with 404 to a WebSocket upgrade that no socket route responds to, writing the response to the socket itself and then destroying it.Adds Kitten’s middleware to the Polka app.
Populates the global
kittenobject with many other properties by initialising the globals helper (Globals.initialise(domain, port)). These includekitten.paths.APP_DATA_DIRECTORY(the app’s data directory, which depends on the app’s path, domain, and port) andkitten.uploadLimits(a copy ofDEFAULT_UPLOAD_LIMITS).The most common Kitten global is the
kitten.htmltagged template string that renders your Kitten markup. Other globals that are useful for authoring include:The
kitten.markdowntagged template string for rendering Markdown.kitten.md, Kitten’s MarkdownIt instance, for more advanced, dynamic use cases.The
kitten.eventsEventEmitter, for listening for and dispatching global events.The
kitten.safelyAddUntrustedHtml()function for allowing a subset of safe tags in untrusted HTML content.
Another important Kitten global is the
kitten.dbreference to your app’s database and thekitten._dbreference to Kitten’s internal database (which persists data related to things Kitten handles for you, like Sessions). These references, however, are added later in this method.The easiest way to see what’s available on the global
kittenobject is to use the.lscommand while running Kitten’s interactive shell (REPL).Creates the uploads directory, and creates the
routerobject that it passes to main.script.js (routerFor()in src/lib/router.ts; see Routes added through router).Initialises Kitten’s internal database (
kitten._db), creating any tables that don’t exist yet, and prepares it for the server (prepareForServer()): this loads the stats into memory, schedules their writes, and reduceskitten._db.sessionsto the unexpired signed-in sessions. If either step fails, Kitten logs the error and exits with code 1. The steps that follow readkitten._db.Starts populating the server’s
optionsproperty with thedomains,settingsPath(the path to Kitten’s TLS directory where certificates are automatically generated and stored), and, if provided, thedomainToken(from the--domain-tokencommand-line argument) andsmallWebHostDomain(from the--small-web-host-domaincommand-line argument). Thedomainslist also includes all domains inkitten._db.settings.domainRedirects, so that Kitten’s certificate includes them and Kitten can redirect HTTPS requests to them.The last two properties are set if the Kitten server is being set up by a Small Web Catalyst. They facilitate communication between the Small Web catalyst and the Small Web site/app running Kitten.
In production, initialises the app repository (
AppRepository.getInstance(), also available askitten.appRepository). This is a working copy of the git repository that the Kitten app was deployed from. It is used by Kitten to handle versioning and updates for deployed Kitten apps/sites (see Updates).In production, creates the
AutomaticUpdatessingleton (kitten.automaticUpdates), which updates both Kitten and the app. It only starts once the server is listening (see below and Updates).Checks to see if the person who owns this Kitten instance has created their cryptographic identity yet (i.e., whether
kitten._db.settings.id, which contains their public keys, is set). If there is no identity yet and no domain token is stored inkitten._db.settings.domainToken, it stores the domain token passed by Catalyst with the--domain-tokenoption or, if there isn’t one, generates a new one. (See Identity and sign-in.)The domain token is a cryptographically-secure random string that forms part of the path for generating a person’s cryptographic identity for a particular Kitten instance.
(A Kitten instance is defined by the unique combination of the app’s location on the local disk as well as the
<domain>:<port>that it is being run at.)If there is no identity yet, also stores the domain of the Small Web catalyst (from the
--small-web-host-domainoption) inkitten._db.settings.smallWebHostDomain, unless one is already stored. (This is used for communication with the Catalyst instance that set up a Kitten instance, if that’s how the Kitten instance was set up.)Initialises the
KittenPackagesingleton (kitten.package), which represents the installed Kitten package. Automatic updates (including updates you request from the Settings section at /🐱/settings/), thekitten updatecommand, and thekitten deploycommand use it (see Updates).The /🐱/settings/ section is, itself, part of an internal Kitten app that all Kitten instances serve alongside the primary app/site they are serving.
The /🐱/ namespace separates internal Kitten routes from those of the Small Web app that Kitten is serving.
Similarly, the /💕/ namespace is used to implement Small Web Protocol routes (💕).
(This is similar to how .well-known routes operate elsewhere but this is the Small Web and Kitten we’re talking about here so instead of a cryptic prefix, we use emoji. Because, why not?)
Warns if the app’s package.json declares a Kitten API version in the
engines.kittenfield that differs fromkitten.package.apiVersion, or sets that field to something other than a whole number.Installs Node modules, if necessary, for any app modules in the Kitten app/site being served and then for the app/site itself (
installNodeModulesIfNecessary()in src/lib/appDependencies.ts). For each folder that has a package.json, it runsnpm ciwhen node_modules is missing (and package.json has dependencies) or whenpackageLockIsInstalled()reports that package-lock.json differs from node_modules/.package-lock.json. If there is no package-lock.json, it runsnpm installinstead. Kitten uses its own version of npm from its runtime and waits for npm to finish. If npm fails, Kitten logs the error and continues.Initialises the App Database, the database for the Kitten app/site that Kitten is serving (
kitten.db; see Databases). If this fails, Kitten logs the error and exits with code 65 (systemExitCodes.dataError).Initialises the routes for Kitten’s own internal web app (
Routes.getRoutes()), keeps only those from files under web/💕/ and web/🐱/, and adds them to the Polka app, each through the route handler (see The route handler). IfRoutesfinds two routes that have the same method and pattern, or a .connect.js or .connect.ts file, Kitten logs the problem and exits with code 65 (systemExitCodes.dataError).Adds a route that serves uploaded files at
/uploads/:id/:download?(downloadHandler()in src/Uploads.ts), through the route handler.If there is a main.script.ts or main.script.js file in the project (the
.tsfile wins if both exist), imports it and awaits its default export, passing it{ router }. The routes and middleware it adds through therouterobject are added to the Polka app at this point. (kitten.app.router, the same object, isn’t set until the server is listening.) If the file has no default export, Kitten logs a warning and continues. If importing the file or running its default export throws, Kitten logs the error and exits with code 65 (systemExitCodes.dataError), as a restart would fail the same way.This optional script is used in Kitten projects to perform global setup tasks (e.g., setting
kitten.uploadLimits).Checks the
kitten.uploadLimitsobject (invalidLimit()in src/lib/body.ts, which uses kitten-busboy’sresolvedLimits()). If a limit’s value is invalid, Kitten logs a line that mentions the limit and its value. If a key isn’t a limit, it logs a line that mentions the key and lists the limits. Either way, it exits with code 65.Initialises the routes for the app/site being served (
Routes.getRoutes()), exiting with code 65 as above for routes that have the same method and pattern and for .connect.js and .connect.ts files, and adds them to the Polka app through the route handler.Serves the contents of any
__archive__1,__archive__2, and__archive__3folders in the project as static files, in that order and after all other routes (cascading archives).Checks the routes it has added (
routeProblems(), which callsreservedPathProblems()in src/lib/routeTable.ts for app routes). Kitten logs every problem and exits with code 65 if an app route, or a route added through therouterobject, is under/💕/or/🐱/, or below/uploads/(other than/uploads/itself), or if a route added through therouterobject has the same method and normalised pattern as an app route. (It doesn’t check regular expression patterns given to therouterobject.)The order is important: when two routes match a request, Polka runs the one that was added first. Kitten adds its own routes first, then
/uploads/:id/:download?, then the routes and middleware that main.script.js adds through therouterobject, then the app/site’s file routes, and then the archives. This ensures that neither a route file like[anything]_[anythingElse].get.jsnor a route added through therouterobject can lock you out of Kitten’s Settings app.Creates an https server (
https.createServer()) using Polka’s request handler, wrapped inpathRequestsOnly()and then indrainBeforeClose(), which waits for the request body before closing connections that the client asked to close. It passesoptionswithout the Kitten-specificdomainTokenandsmallWebHostDomainproperties. @small-tech/https uses Auto Encrypt Localhost ifdomainsincludeslocalhostor one of the localhost aliases, and Auto Encrypt (Let’s Encrypt) otherwise. Both only accept TLS 1.3 connections by default, and Kitten does not change that.Handles the server’s
checkContinueevents (requests that have anExpect: 100-continueheader) with the same request handler, and sends100 Continueonly once the request body starts flowing (i.e., once a route starts reading it).Creates a WebSocket server (using ws) that accepts messages of up to 1 MB (
MAXIMUM_WEBSOCKET_MESSAGE_SIZE), and starts handling upgrade events withupgradeHandler().The implementation mixes in a
wsclosure to incoming request objects, which, when invoked, returns a promise that resolves to an upgraded WebSocket connection using the Kitten Server’s web socket server instance. The upgrade handler then passes the request to Polka’s handler (wrapped inpathRequestsOnly()), so upgrade requests go through the same middleware as other requests. Only socket routes, page socket routes, and the development socket respond to them: the route handler of every other route passes an upgrade on (see The route handler), andnoMatchHandler()responds with 404 to an upgrade that nothing responded to. Socket routes and page socket routes callrequest.ws()to accept the connection. Kitten logs every WebSocket error.The WebSocket implementation in Kitten is based on express-websocket and tinyws.
It’s designed to keep some of the modern interface of tinyws (async/await syntax) while avoiding the client connection timeout issue in tinyws.
Exits with an error message (and code 1) if the address is already in use.
Starts listening at the specified port. Once the server is listening, it:
Sets
kitten.portto the port the server is listening at (which differs from the requested port when the port is random), records the hosts of the main domain and its aliases at that port (setPlaceDomains()in src/lib/placeDomains.ts, which page routes use in production to check theHostheader), and populates the globalkitten.appobject with references to therouterobject it passed to main.script.js (kitten.app.router) and the server instance itself (kitten.app.server).In production, records how long the start took (
writeStartSeconds()). It then confirms a pending update, if there is one, by requesting the app’s home page (see Updates). If the update fails this check, Kitten logs the error and exits with the restart request code. If there is no pending update, it removes leftovers from earlier updates instead (pruneAtStart()). It then starts automatic updates (kitten.automaticUpdates.start()).Displays information about the domain the server is running at (and any aliases and domain redirects), a link to the path where the source code of the app/site being served is on disk, as well as a link to the data folder for the app/site being served (where the databases as well as any uploads are kept).
If a cryptographic identity hasn’t been created for the person who owns this Kitten instance yet, displays the one-time link to
/💕/hello/<domain token>/where they can create one.If Kitten is running interactively in a terminal, displays instructions for how to launch the interactive shell (REPL).
Informs the person that the server is running (and whether it is running in production).
If an app repository exists for the app/site being run, displays its version.
If logging is active, lists the active log sections and the key to the symbols used in log prefixes.
If Kitten was launched with the
--openflag, opens the system browser at the address where the app/site is being served.Checks Kitten’s global internal database (
kitten.__db, which the main script opens) to see if Kitten is currently being deployed by Catalyst. If it is, it informs the Small Web catalyst that the server has successfully launched. It then unsets that flag so as not to impact future launches of the server.In production, schedules the daily maintenance restart. Every 25 minutes, it checks whether the server has already restarted today. If not, and the current hour is
kitten._db.scheduledRestart.restartHour(3, 4, or 5, picked at random when the internal database is created, so the restart happens between 3 and 6 AM), it exits with the restart request code. This ensures that JSDB compacts the tables (e.g., the sessions table) regularly.Finally, starts the Kitten REPL, which listens for the [s] key when Kitten is running in a terminal.
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:
If a domain is not explicitly specified using the
--domaincommand-line option, the default domain oflocalhostis used.If the domain is
localhostor one of the localhost aliases –place1.localhost,place2.localhost,place3.localhost, orplace4.localhost– the server is local. Its certificate, from Auto Encrypt Localhost, includeslocalhost, 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.If a port is not explicitly specified using the
--portcommand-line option, the default port of 443 is used.If the
--portoption is passed without a value, or, if its value is set to0(zero), the operating system assigns a random, available port. Kitten setskitten.portto 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.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
--aliasesoption, 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--aliasesoption for a local server.)If the shorthand domain alias
wwwis passed in the--aliaseslist, it is rewritten to its fullwww.<main domain>value.If the domain is
ipv4oripv6, Kitten detects the machine’s external IP address and uses it as the main domain (Web Numbers). Foripv6, it uses the first stable IPv6 address it finds and adds any others to the aliases. Ifipv4is requested and there is no external IPv4 address, thegetDomainsAndPort()function throws an error. An IP address is never local, so Kitten provisions a Let’s Encrypt certificate for it with Auto Encrypt.