Skip to content

Reloading in dev

Reload the files your plugin loads when you save them under seedcord dev, and ask for a restart for the ones it reads once.

Under seedcord dev, a save swaps the file into the running bot. A plugin that loaded the file itself, like a service class from its folder, keeps the old copy, because seedcord has no record that the plugin read that file. Restarting for every edit costs the connection you were trying to keep.

What reaches onHmr when a file is saved

Every save sends your plugin an HmrUpdateEvent through onHmr. file is the saved path, and type is create, createDir, update, delete, or deleteDir. affectedModules lists the file and every file that imports it, and rollback says whether a failed reload keeps the last working version. The default onHmr does nothing, and it never runs outside seedcord dev. If your onHmr throws, seedcord logs the error and the bot's other reloaders still run.

Reloading files the plugin loaded

FolderExports registers what a folder's files export at startup, then reloads a file's exports each time you save it. Import it from your transport package, or from @seedcord/core on the @seedcord/core/plugin base. You give it the folder, a check for which exports count, and how to register and unregister one.

src/plugins/Jobs.ts
import { FolderExports, Plugin } from '@seedcord/gateway';

import type { CoreBase, HmrUpdateEvent } from '@seedcord/gateway';

type JobClass = new () => { run(): Promise<void> };

const isJob = (value: unknown): value is JobClass =>
    typeof value === 'function' &&
    typeof value.prototype?.run === 'function';

export class Jobs extends Plugin {
    private readonly jobs = new Map<string, JobClass>();
    private readonly jobFiles: FolderExports<JobClass>;

    public constructor(host: CoreBase, dir: string) {
        super(host);
        this.jobFiles = new FolderExports({
            dir,
            is: isJob,
            register: (job) => this.jobs.set(job.name, job),
            unregister: (job) => this.jobs.delete(job.name),
            logger: this.logger
        });
    }

    public async init(): Promise<void> {
        await this.jobFiles.load();
    }

    public override async onHmr(
        event: HmrUpdateEvent
    ): Promise<void> {
        await this.jobFiles.handle(event);
    }
}

init() calls load(), which imports every file under dir and passes each export that isJob accepts to register. It runs the same way in production, so the bot registers its jobs through one path whether dev is running or not. isJob receives every value a file exports, helpers and constants included, so it has to pick out your classes.

If jobs/index.ts re-exports a job, load() still only registers it once. handle() unregisters it only after neither file exports it, so deleting the barrel leaves the job running.

What each save does

onHmr passes each save to handle(), which ignores files outside dir and reads the event's type:

typewhat handle() does
create, updatere-imports the saved file and every file in affectedModules that sits under dir, unregisters what each one exported before, and registers what it exports now
delete, deleteDirunregisters what that path exported, apart from a value that another file still exports, then re-imports the files in affectedModules that import it
createDirnothing. Each file in the new folder arrives as its own create event

If a file throws while it imports, handle() has already unregistered its old exports. With rollback on, the default, it registers them again and logs a warning. If you set hmr.rollback to false, handle() leaves them unregistered until a save that imports cleanly. A save that throws on import walks through the same case for your own handlers.

If your register throws, handle() unregisters whatever that file registered before the throw. It tries the file again on the next save that unloads something. That covers moving a job to a new file, since the new file often loads before the old one unloads. If your register rejects a name that's already taken, the first try fails, and the retry succeeds after handle() unregisters the old file's job.

Each reload logs one line at debug level on your plugin's logger, in the hmr channel, like "Reloaded ResetStreaks from jobs/ResetStreaks.ts in 4ms".

Undoing what a registration made

unregister gets the old value and nothing else. That's enough for Jobs, since registering only stored the class in a map. If registering creates something you have to undo later, keep it in a map keyed by the class and look it up in unregister. Here schedule() starts a timer for each job:

src/plugins/Jobs.ts
this.jobFiles = new FolderExports({
    dir,
    is: isJob,
    register: (job) => this.schedule(job),
    unregister: (job) => {
        clearInterval(this.timers.get(job));
        this.timers.delete(job);
    },
    logger: this.logger
});

A save to a job file clears the old class's timer before the new class starts its own. Without clearInterval in unregister, every save would leave one more timer running the old code.

More than one folder

A FolderExports covers one folder and one kind of value. For a second kind, like hooks that run around each job, make a second FolderExports with its own is, register, and unregister. Call load() on both in init() and handle() on both in onHmr(), since each one ignores saves outside its own folder.

If the hooks folder is a subfolder of the jobs folder, pass it to the jobs instance as exclude: [hooksDir]. Without it, a hook file that throws on import logs its error once from each instance. The dir should be relative to the root of your project, or an absolute path.

Files read once

A reload only helps with files your plugin reads again. A locale folder that init() read at startup stays as it was, because swapping the file doesn't repeat the read. Pass glob patterns for files like that to registerCriticalFiles. When one of them changes, the dev terminal shows a Restart required card telling you to press r, which the Tooling tab describes.

src/plugins/Locales.ts
import { Plugin, readFiles } from '@seedcord/gateway';

import type { CoreBase } from '@seedcord/gateway';

export class Locales extends Plugin {
    public constructor(
        host: CoreBase,
        private readonly dir: string
    ) {
        super(host);
    }

    public async init(): Promise<void> {
        this.registerCriticalFiles([`${this.dir}/**`]);
        for await (const { bytes } of readFiles(this.dir)) {
            this.logger.debug(`read ${bytes.length} bytes`);
        }
    }
}

Saving anything under dir now asks for a restart. A relative pattern resolves against root, and the call does nothing outside seedcord dev. Register only the files your plugin reads, because seedcord already asks for a restart on its own startup files.

Saving the plugin's own source

A plugin you keep in src/plugins asks for a restart when you save it, and no hook changes that. Your bot file imports the plugin and attaches it once at startup, and seedcord dev asks for a restart on a save to any file the bot file imports. A hot reload would leave the attached instance running the old code. Testing it in a bot covers a plugin that lives in another package.