Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/subcommands-older-framework-test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Imports the built entries given as arguments against a framework that has no `runPreconditions`, and prints
// `loaded` once every entry has linked and run.
import { register } from "node:module";

register("./without-run-preconditions.hooks.mjs", import.meta.url);

const framework = await import("@wolfstar/http-framework");
if ("runPreconditions" in framework) throw new Error("The shim still exports runPreconditions.");

for (const entry of process.argv.slice(2)) await import(entry);
console.log("loaded");
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Module hooks that serve `@wolfstar/http-framework` without its `runPreconditions` export, the shape of a framework
// older than 6.3.0. The shim re-exports every other name of the installed framework, so a build that imports
// `runPreconditions` by name fails to link, as it would on such a framework.
const SHIM = "file:///wolfstar-shim/http-framework.mjs";
const MISSING = "runPreconditions";

export async function resolve(specifier, context, nextResolve) {
if (specifier !== "@wolfstar/http-framework") return nextResolve(specifier, context);

const real = await nextResolve(specifier, context);
return { url: `${SHIM}?real=${encodeURIComponent(real.url)}`, shortCircuit: true };
}

export async function load(url, context, nextLoad) {
if (!url.startsWith(SHIM)) return nextLoad(url, context);

const real = new URL(url).searchParams.get("real");
const names = Object.keys(await import(real)).filter(
(name) => name !== MISSING && name !== "default",
);
const source = [
`import * as real from ${JSON.stringify(real)};`,
`export const { ${names.join(", ")} } = real;`,
].join("\n");

return { format: "module", source, shortCircuit: true };
}
119 changes: 119 additions & 0 deletions packages/plugin-subcommands-advanced/tests/older-framework.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { execFile } from "node:child_process";
import { mkdirSync } from "node:fs";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { err } from "@sapphire/result";
import { ApplicationCommandOptionType } from "discord-api-types/v10";
import { container, PreconditionError, RegisterCommand } from "@wolfstar/http-framework";
import {
ChatInputApplicationCommandInteractionData,
createTestHarness,
makeCommand,
} from "@wolfstar/http-framework-test-utils";
import { build } from "tsdown";
import {
clearSubcommandRegistries,
Command,
RegisterAsSubcommand,
Subcommand,
wireParentSubcommands,
} from "../src/index.js";
import "../src/register.js";

// `runPreconditions` exists since @wolfstar/http-framework 6.3.0, while the peer range still accepts ^3.1.0 and ^5.0.0.
// The plugin's own code sees a framework without it; the test harness keeps the real one.
vi.mock("@wolfstar/http-framework", async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
runPreconditions: undefined,
}));

const packageDirectory = fileURLToPath(new URL("../", import.meta.url));
// Inside the package, so the bare specifiers of the build resolve from its `node_modules`.
const outDir = fileURLToPath(
new URL("../node_modules/.cache/older-framework-test/", import.meta.url),
);
const loader = fileURLToPath(
new URL("fixtures/load-without-run-preconditions.mjs", import.meta.url),
);

describe("on a framework without runPreconditions", () => {
afterEach(async () => {
clearSubcommandRegistries();
await container.stores.get("commands").unloadAll();
});

// The CI unit job runs vitest without a build, so the entries are built here. A named import of `runPreconditions`
// would make Node refuse to link the build against an older framework, which no test of the sources can show.
it("loads the built plugin", async () => {
mkdirSync(outDir, { recursive: true });
await build({
config: false,
cwd: packageDirectory,
entry: { index: "src/index.ts", register: "src/register.ts" },
outDir,
format: "esm",
platform: "node",
dts: false,
clean: true,
deps: { neverBundle: true },
tsconfig: fileURLToPath(new URL("../../../tsconfig.build.json", import.meta.url)),
logLevel: "silent",
});

const entries = ["index.mjs", "register.mjs"].map(
(name) => pathToFileURL(`${outDir}${name}`).href,
);
const { stdout } = await promisify(execFile)(process.execPath, [loader, ...entries]);

expect(stdout.trim()).toBe("loaded");
}, 60_000);

it("runs a modular subcommand, without its preconditions option", async () => {
@RegisterCommand({ name: "settings", description: "Settings" })
class SettingsCommand extends Subcommand {}

@RegisterAsSubcommand("settings", (builder) =>
builder.setName("server").setDescription("Server settings"),
)
class ServerCommand extends Command {
public constructor(context: Command.LoaderContext, options: Command.Options) {
super(context, {
...options,
preconditions: [
() => err(new PreconditionError({ precondition: "administrator", message: "denied" })),
],
});
}

public override chatInputRun(interaction: Command.ChatInputInteraction) {
return interaction.reply({ content: "server" });
}
}

const { runner } = createTestHarness({
subcommandsAdvanced: { nameCommandsAutogenerated: true },
});
const child = makeCommand(ServerCommand);
const parent = makeCommand(SettingsCommand);

const store = container.stores.get("commands");
await store.unloadAll();
wireParentSubcommands(parent);
store.set(child.name, child);
store.set(parent.name, parent);
store.router.addChatInputMapping("settings", parent);

const result = await runner.run({
...ChatInputApplicationCommandInteractionData,
data: {
id: "0",
name: "settings",
type: 1,
options: [{ type: ApplicationCommandOptionType.Subcommand, name: "server", options: [] }],
},
});

expect(result.statusCode).toBe(200);
expect(result.json()).toMatchObject({ data: { content: "server" } });
});
});
Loading