Architecture ConceptsModules & Discovery

IV · Architecture Concepts

Modules & Discovery

  • @marmeon/core
On this page

Introduction

A Marmeon app is one program made of modules. A module is a feature in a folder of its own, modules/<name>/, and its index.ts says what the feature brings: its routes, its service providers, its configuration, its event listeners, its jobs, its migrations and its schedule. The installed framework packages join the app on their own, through discovery.

modules/notes/index.ts
import { SignedIn } from '@marmeon/auth';
import { defineModule, listen } from '@marmeon/core';
import apiRoutes from './api-routes.ts';
import { NotesConfig } from './config.ts';
import { PruneTrashJob } from './jobs/PruneTrashJob.ts';
import { RecordLastVisit } from './listeners/RecordLastVisit.ts';
import { NotesServiceProvider } from './NotesServiceProvider.ts';
import routes from './routes.ts';
import { schedule } from './schedule.ts';

export { NoteRepository } from './NoteRepository.ts';

export default defineModule({
  name: 'notes',
  providers: [NotesServiceProvider],
  config: [NotesConfig],
  listeners: [listen(SignedIn, RecordLastVisit)],
  jobs: [PruneTrashJob],
  migrations: new URL('./migrations/', import.meta.url),
  routes,
  apiRoutes,
  schedule,
});

The app lists its modules in bootstrap/app.ts. A module that is not listed is not loaded, however complete its folder is.

Why the list is explicit

The list is the one place that says what the app is made of, and it has three reasons to be a list:

  • The order. A scan of the folder could only give alphabetical order, and a module carries no dependency information to sort by. The list gives the order of modules explicitly.
  • Nothing runs by accident. The list holds static imports. A file that sits in modules/ runs no code until something imports it, so a half-finished folder or a leftover from another branch cannot add routes or providers to the app.
  • The list is a value. A test composes its own application from it, such as { ...application, modules: [...application.modules!, fixtures] } to add a module of fixtures, or a shorter list to boot a part of the app.

The installed packages are different: they are discovered (see Discovery), because a package opts in with a "marmeon" field in its package.json and its dependencies give it a place in the order. make:module keeps the cost of the explicit list low: it adds the new module to bootstrap/app.ts for you (see Creating a module).

The application

bootstrap/app.ts exports the app's definition, made with defineApplication(). It describes the app and boots nothing: the marmeon command boots it for the server or a command, and each test boots a fresh instance. The directory structure page shows a new app's file. The options:

OptionWhat it is
rootThe app's root folder, with package.json, .env and index.html. A new app sets it from import.meta.dirname.
modulesThe feature modules, in the order they register and boot.
configApp-level config definitions. See configuration.
middlewareThe app's middleware: global for every request, web and api for the routes of each group. See middleware.
clientRoutesWhich named routes the browser may learn: include and except, by pattern. See URL generation.
providersApp-level service providers. They boot after the packages' and before the modules'.
listenersApp-level event listeners: listen(Event, Listener).
healthApp-level checks for /up/ready. See health checks.
discoverfalse registers none of the installed packages. Default: true.
redactKey names and value patterns every redactor of the app masks besides the core's lists: { keys: ['iban'], patterns: [/\bacme_live_[A-Za-z0-9]{32}\b/] }. See patterns of your own.

The definition is what ships. What only one boot decides is not part of it: defineApplication({ root, env: {} }) and defineApplication({ root, override: … }) are type errors, so a test double or a foreign environment cannot end up in the app that runs in production. A definition that carries one anyway, through a variable or a spread the types cannot see, is refused when createApplication() boots it. A package that adds an option to the definition declares it on ApplicationDefinition (see extending the app's types).

createApplication(definition, options) boots an app from its definition and returns it. The marmeon command and createTestApp() call it for you. The options are the ones a boot decides:

OptionWhat it is
envThe environment to check the configuration against, instead of .env and the real environment. For tests and scripts.
phase'build' registers the providers and boots none (what marmeon build needs). Default: 'run'.
overrideA function that replaces bindings after every provider registered and before any boots. For tests.

app.shutdown() stops the app again: every provider's shutdown() runs and closes its pools and connections. Code that needs the booted app outside of a request, such as a maintenance script, belongs in a console command: marmeon boots the app for it and shuts it down afterwards.

Defining a module

defineModule() takes the module's name and whatever the module contributes. The core knows a few keys, and each package adds its own:

KeyWhat it isFrom
nameThe module's name, in kebab case.core
providersIts service providers.core
configIts config definitions.core
listenersIts event listeners: listen(Event, Listener).core
healthIts health checks.core
routesIts route file, loaded into the web group. See routing.@marmeon/http
apiRoutesIts route file for the api group, under /api.@marmeon/http
commandsIts console commands.marmeon
checksIts checks for marmeon check.marmeon
migrationsThe folder of its migrations: new URL('./migrations/', import.meta.url).@marmeon/database
seedersIts seeders.@marmeon/database
exposesThe tables other modules may read and join. See repositories.@marmeon/database
jobsIts queued jobs. A worker runs only registered jobs: a module's jobs or a provider's static [providerJobs].@marmeon/queue
notifications, recipientsIts notifications and who may receive them.@marmeon/notifications
liveAuthorizersWho may follow its live channels.@marmeon/live
scheduleIts scheduled work.@marmeon/scheduler
csrfExceptPaths that skip the CSRF check.@marmeon/session

Controllers, views and other classes need no list: a route names its controller, and the container builds it when a request needs it.

Creating a module

make:module writes a module with an empty route file:

pnpm marmeon make:module billing

It writes modules/billing/index.ts and modules/billing/routes.ts (--no-routes writes index.ts without routes, for a module that serves no pages), and adds the module last in modules of bootstrap/app.ts (routes match in module order). When that file has another shape, or with --no-register, it prints the two lines to add instead. In an app with @marmeon/database it then runs marmeon db:types, so Database<'billing'> compiles at once; a module you create or register by hand needs that command too. The directory structure page walks through a first module from there.

The order of modules

The modules register and boot in the order of modules: [...], and their routes load in that order too. When two routes match the same path, the one loaded first answers. The order rarely matters otherwise: every provider registers before any boots, so a module can use what a later module binds once the app has booted.

A module's public API

A module's index.ts is also its public face. What it exports is what the rest of the app may use, and other modules import it from #modules/<name>:

modules/dashboard/controllers/ShowDashboardController.ts
import { Controller } from '@marmeon/http';
import { NoteRepository } from '#modules/notes';

export class ShowDashboardController extends Controller {
  readonly #notes: NoteRepository;

  constructor(notes: NoteRepository) {
    super();
    this.#notes = notes;
  }

  async handle() {
    return this.view('dashboard/Show', { notes: await this.#notes.query().selectAll().limit(5).execute() });
  }
}

#modules/<name> is an import map entry of the app's package.json: "#modules/*": "./modules/*/index.ts". Node, Vite and TypeScript all resolve it.

Nothing stops a module from importing a file inside another module, until you ask for it. marmeon make:lint-config --boundaries writes the lint preset with one more rule: a module imports another module only through its entry. The lint then refuses import { NoteRepository } from '../../notes/NoteRepository.ts'.

The preset also forbids @marmeon/<package>/internal in every file of the app, tests included. Those subpaths are the framework's own code, not API, and can change in any release. Use the package's entry; if you need something only an internal subpath has, open an issue. To add the rule to an existing preset, run marmeon make:lint-config --force (with --boundaries if you use it; it rewrites the file, so carry your own changes over) or add the pattern by hand.

Two modules must not import each other's classes. If they do, one class is not defined yet when the other is, and the container reports a constructor parameter that is undefined (K16, naming the class and the parameter). Under Node (marmeon dev, start, commands) the import itself fails with "Cannot access 'X' before initialization"; in tests (Vite's module runner) the container reports K16 instead. Break the cycle by letting one module read what the other exposes (its table), or by depending on an abstract class that lives in a third place.

Listing the modules

marmeon modules:list shows what the app defines: the packages it found, the providers of the app, and for each module its providers, commands, jobs, notifications, seeders and migrations folder. The jobs are the module's own; below the modules come the jobs of providers (static [providerJobs]), each with its provider, and then the events with the listeners of each one. A part a module does not have is left out. The document of --json also names the environment variables the configuration reads and has the jobs of providers as providerJobs, empty when no provider lists any.

pnpm marmeon modules:list
Packages: @marmeon/http, @marmeon/database
App providers: AppServiceProvider

notes
  providers: NotesServiceProvider
  commands: notes:prune
  jobs: ExportNotes (notes.export)
  notifications: NoteShared (notes.shared)
  seeders: NoteSeeder
  migrations: modules/notes/migrations

Provider jobs
  MediaProvider: ProcessMediaJob (media.process)

Events
  NoteCreated → IndexNote (queued)

The command registers the providers and boots none of them: it needs no .env, no database connection and runs no boot() of yours. It reads only the fields it prints. A configuration value, a default, a value of .env and everything else a module carries are never read out; of an environment variable only the name and whether it is set are.

--json prints the same as a document, always with the format first (see machine-readable output):

{
  "format": 1,
  "packages": ["@marmeon/http", "@marmeon/database"],
  "app": { "providers": ["AppServiceProvider"] },
  "modules": [
    {
      "name": "notes",
      "providers": ["NotesServiceProvider"],
      "commands": ["notes:prune"],
      "jobs": [{ "class": "ExportNotes", "job": "notes.export" }],
      "notifications": [{ "class": "NoteShared", "notification": "notes.shared" }],
      "seeders": ["NoteSeeder"],
      "migrations": "modules/notes/migrations"
    }
  ],
  "providerJobs": [
    {
      "provider": "MediaProvider",
      "modules": [],
      "jobs": [{ "class": "ProcessMediaJob", "job": "media.process" }]
    }
  ],
  "events": [
    {
      "event": "NoteCreated",
      "name": "notes.created",
      "listeners": [{ "listener": "IndexNote", "queued": true, "defined": "module", "module": "notes" }]
    }
  ],
  "environment": [
    { "name": "NOTES_API_KEY", "config": "notes", "modules": ["notes"], "set": true, "required": true, "hasDefault": false }
  ],
  "warnings": []
}
  • packages are the installed packages whose providers were discovered, in the order they register. Their providers are not listed one by one.

  • modules keep the order of modules: [...]. Every list is there, empty when the module has nothing. migrations is the folder relative to the app root, or null. With a warning in warnings, the folder is elsewhere, in a monorepo for one, and null stands for it: <module>: its migrations folder lies outside the app root (also when a link inside the app leads out of it), or <module>: its migrations folder is not a path on this machine (a URL that is no file: URL). Without a warning, the module has no folder.

  • providerJobs has one entry per provider class that lists jobs in its static [providerJobs], the ones discovery adds included, in registration order. jobs are its classes; a job is null without a string static job. modules names the modules that list the provider in their providers, empty for one only the app or discovery lists. The array is empty when no provider lists jobs.

  • events are sorted by event, the class name; name is its static event when that is a string, else null. The listeners keep the order they were registered in. defined says where a listener comes from: app (the listeners of defineApplication), module (the listeners of a module, module names it) or provider (a provider registered it in register(), module is null).

  • A class without a name is (anonymous), a static job, static notification or static event that is no string is null, and no string from your code is longer than 200 characters.

  • environment has an entry per variable of every configuration the app validates (the framework's, the app's, its modules' and its providers'), sorted by name. config is the name of the configuration, modules the names of the modules whose config lists it (several when they share the definition), empty for the app's, a provider's and the framework's. set is true when the variable is in the environment or in .env and is not empty. required is true for a variable without a default that must be set, hasDefault for one that has a default; a variable that is neither is optional. The value, and the value of a default, is never read into the document. A configuration whose env is not made by env({ … }) has its own schema: its variables are not listed, and config <name> validates its environment with its own schema; its variables are not listed is in warnings. The text output does not list them.

A listener a provider adds in boot() is not in the list, because nothing boots.

Discovery

The framework's packages register themselves. A package that opts in with a "marmeon" field in its package.json has its service providers registered by every app that installs it, so an app has no list of packages to maintain. This is the field in the package.json of @marmeon/http:

{
  "name": "@marmeon/http",
  "marmeon": {
    "providers": ["HttpServiceProvider"],
    "browser": ["src/client/**", "src/page.ts", "src/protocol.ts", "src/upload-header.ts", "src/live-protocol.ts", "src/tab-sync-protocol.ts"]
  }
}

providers names classes the package's entry exports. They register in the order of the dependencies: a package after the packages it depends on. browser names the package's files that run only in the browser. The constructor injection leaves them alone, so no injection code reaches a client bundle.

marmeon discover

marmeon discover walks the app's dependencies and writes what it found to .marmeon/manifest.json: the providers of each package, and the injection lists of the classes the packages export. You rarely run it yourself. The app writes the file again by itself when package.json, the lockfile or the resolution conditions change, so pnpm marmeon add redis (or pnpm add -E @marmeon/redis@<version of your app>) needs no extra step. It also does so when the package.json of a package in your workspace changes. The app also writes it again when a folder from your app up to your workspace gains or loses a workspace marker or a lockfile, or starts or stops being trusted. An app without a workspace counts the folders above it up to the first untrusted one. Your workspace is the first folder, from your app upwards, that has a pnpm-workspace.yaml (or a package.json with workspaces) or a lockfile, else your app's folder. An app with a lockfile of its own is therefore its own workspace: a pnpm workspace with one lockfile per project does not watch the packages beside the app. The search for your workspace stops below the first folder above your app that everyone can write to or that a user other than you, root or the owner of your app owns; on a mount where every folder is writable by everyone (WSL /mnt/c, some bind mounts), discovery then sees only what your app's node_modules and the install trees of the packages linked there hold. There, run marmeon discover after an install. That check does not run on Windows, and it lets a folder pass that only a group can write to. Discovery looks for a package in the node_modules of the package that needs it and of each folder above it, up to your workspace. A package linked from outside your workspace is looked up only in its own install tree and is not watched; a name that is not installed there stays absent. A package in a dependencies list that is installed but out of that reach is named in a warning when the app starts, once per process. The app also writes the file again when a listed package is gone, such as after a production install without the dev dependencies. It also writes it once more when a listed provider is no longer a class, which can mean the list is out of date; only if the fresh list still names it does the app stop with K7. marmeon build writes the production list.

The file is data and is never imported, so rewriting it restarts no development server. Git ignores .marmeon/.

A read-only .marmeon/

On a server whose app folder is read-only, the app cannot rewrite an outdated list. It discovers the packages in memory instead, logs one warning and starts. Run marmeon build or marmeon discover where the folder is writable, such as in the build stage of an image, and the warning goes away.

Without discovery

defineApplication({ discover: false }) registers none of the installed packages. The app then lists every provider it needs in providers, in the right order. This is for tests and special setups. A normal app keeps discovery on. The package development page explains how a package of your own opts in.

Testing

createTestApp() boots the app from the same definition, with its modules and the discovered packages:

modules/notes/notes.test.ts
import { createTestApp } from '@marmeon/testing';
import { expect, it } from 'vitest';
import application from '../../bootstrap/app.ts';

it('loads the notes module', async () => {
  await using app = await createTestApp(application);
  expect(app.application.modules.map((module) => module.name)).toContain('notes');
});

The testing page explains how a test boots the app.