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
7 changes: 7 additions & 0 deletions .changeset/autoconfig-cf-hono.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@cloudflare/autoconfig": minor
---

Set up Hono projects for cf

Previously, autoconfig refused every Hono project on cf. It now sets them up to build with Vite and the Cloudflare plugin, as in Hono's Workers + Vite starter: it adds Vite when the project doesn't use it, replaces Hono's own Vite dev server and build plugins, and uses the app's entry file as the Worker entry point. An entry file that doesn't export the app, such as one that starts a Node.js server, and HonoX projects are refused with a message. The Wrangler target is unchanged.
8 changes: 7 additions & 1 deletion packages/autoconfig/src/details/framework-detection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,15 @@ export async function detectFramework(
.get(maybeDetectedFramework.baseDirectory ?? "")
?.find(({ id }) => id === frameworkId)
: undefined;
const buildCommand = detectedFrameworkSettings?.build?.command;
maybeDetectedFramework.devCommand = detectedFrameworkSettings?.dev?.command;
// A framework without a build command of its own, such as Hono, gets the generic
// `<package manager> run build` script from @netlify/build-info, which cf must not run either
maybeDetectedFramework.buildCommand =
detectedFrameworkSettings?.build?.command;
buildCommand ===
`${project.packageManager?.runCommand ?? "npm run"} build`
? undefined
: buildCommand;
Comment thread
edmundhung marked this conversation as resolved.
Resolved
}

if (
Expand Down
11 changes: 10 additions & 1 deletion packages/autoconfig/src/frameworks/all-frameworks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import assert from "node:assert";
import { Analog } from "./analog";
import { Angular } from "./angular";
import { Astro } from "./astro";
import { Hono } from "./hono";
import { Hugo } from "./hugo";
import { NextJs } from "./next";
import { Nuxt } from "./nuxt";
Expand Down Expand Up @@ -77,7 +78,15 @@ export function getAllKnownFrameworks(target: AutoConfigTarget) {
{
id: "hono",
name: "Hono",
supported: false,
class: Hono,
frameworkPackageInfo: {
name: "hono",
minimumVersion: "4.0.0",
Comment thread
edmundhung marked this conversation as resolved.
Resolved
maximumKnownMajorVersion: "4",
},
supportsCf: true,
// Only cf sets up Hono, by keeping the Worker that Wrangler already deploys
supported: target === "cf",
},
// Hugo builds a static site and has no npm package. Wrangler sets it up as a static site
// without listing it.
Expand Down
245 changes: 245 additions & 0 deletions packages/autoconfig/src/frameworks/hono.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
import { existsSync } from "node:fs";
import { dirname, posix, relative, resolve, sep } from "node:path";
import { parseFile } from "@cloudflare/shared-ast-primitives";
import * as recast from "recast";
import { AutoConfigFrameworkConfigurationError } from "../errors";
import { Framework } from "./framework-class";
import { readPackageJson } from "./utils/packages";
import {
assertViteConfigCanBeTransformed,
getStaticPropertyName,
getViteConfigPath,
hasViteConfig,
transformViteConfig,
} from "./utils/vite-config";
import { installCloudflareVitePlugin } from "./utils/vite-plugin";
import { CF_VITE_PLUGIN_VERSION_RANGE } from "./utils/vite-plugin-version";
import { createViteConfig } from "./vite";
import type { WranglerConfig } from "../types";
import type {
ConfigurationOptions,
ConfigurationResults,
} from "./framework-class";

const t = recast.types.namedTypes;

/** The app's entry files that Hono's own Vite plugins use when none is configured */
const DEFAULT_ENTRIES = ["src/index.ts", "src/index.tsx"];

/**
* Sets a Hono app up to build with Vite and the Cloudflare plugin, as in Hono's Workers + Vite
* starter. Hono's own dev server and build plugins are replaced, since the Cloudflare plugin
* runs and builds the app itself.
*/
export class Hono extends Framework {
async configure({
Comment thread
edmundhung marked this conversation as resolved.
Resolved
dryRun,
projectPath,
packageManager,
isWorkspaceRoot,
target,
wranglerConfig,
}: ConfigurationOptions): Promise<ConfigurationResults> {
const packageJson = readPackageJson(projectPath);
const dependencies = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
};
if ("honox" in dependencies) {
throw new AutoConfigFrameworkConfigurationError(
"cf can't set up HonoX projects automatically yet.",
{ telemetryMessage: "autoconfig honox setup unsupported" }
);
}

const viteConfigExists = hasViteConfig(projectPath);
if (viteConfigExists) {
assertViteConfigCanBeTransformed(projectPath);
}
const honoVitePlugins = viteConfigExists
? readHonoVitePlugins(projectPath)
: { names: [], buildEntries: [], devServerEntries: [] };
// Hono's build plugin combines the handlers of every entry file into one Worker, which a
// single entry point can't do
if (honoVitePlugins.buildEntries.length > 1) {
throw new AutoConfigFrameworkConfigurationError(
`cf can't set up a Hono build that combines several entry files automatically yet: ${honoVitePlugins.buildEntries
.map((file) => `\`${file}\``)
.join(", ")}.`,
{ telemetryMessage: "autoconfig hono multiple build entries" }
);
}
const entrypoint = findEntrypoint(projectPath, wranglerConfig, [
...honoVitePlugins.buildEntries,
...honoVitePlugins.devServerEntries,
]);

if (!dryRun) {
await installCloudflareVitePlugin({
packageManager: packageManager.type,
isWorkspaceRoot,
projectPath,
version: CF_VITE_PLUGIN_VERSION_RANGE,
});

if (viteConfigExists) {
transformViteConfig(projectPath, {
target,
incompatibleVitePlugins: honoVitePlugins.names,
});
Comment thread
edmundhung marked this conversation as resolved.
Resolved
Comment thread
edmundhung marked this conversation as resolved.
Resolved
} else {
createViteConfig(projectPath, target);
}
}

return {
buildTool: "vite",
workerConfig: { entrypoint: `./${entrypoint}` },
};
Comment thread
edmundhung marked this conversation as resolved.
Resolved
}
}

/**
* Reads the plugins from Hono's `@hono/vite-dev-server` and `@hono/vite-build` packages in the
* project's Vite config.
*
* @param projectPath The project's path
* @returns The plugins' local names, and the app entries given to each
*/
function readHonoVitePlugins(projectPath: string): {
names: string[];
buildEntries: string[];
devServerEntries: string[];
} {
const ast = parseFile(getViteConfigPath(projectPath));
const devServerNames = new Set<string>();
const buildNames = new Set<string>();
const devServerEntries: string[] = [];
const buildEntries: string[] = [];
if (!ast) {
return { names: [], buildEntries: [], devServerEntries: [] };
}

for (const statement of ast.body) {
if (!t.ImportDeclaration.check(statement)) {
continue;
}
const source = String(statement.source.value);
const names =
source === "@hono/vite-dev-server"
Comment thread
edmundhung marked this conversation as resolved.
Resolved
? devServerNames
: source === "@hono/vite-build" ||
source.startsWith("@hono/vite-build/")
? buildNames
: undefined;
for (const specifier of statement.specifiers ?? []) {
if (
names &&
t.ImportDefaultSpecifier.check(specifier) &&
specifier.local
) {
names.add(String(specifier.local.name));
}
}
}

recast.visit(ast, {
visitCallExpression(path) {
const { callee, arguments: [options] = [] } = path.node;
const entries = !t.Identifier.check(callee)
? undefined
: devServerNames.has(callee.name)
? devServerEntries
: buildNames.has(callee.name)
? buildEntries
: undefined;
if (entries && t.ObjectExpression.check(options)) {
const entry = options.properties.find(
(property) => getStaticPropertyName(property) === "entry"
);
if (t.Property.check(entry) || t.ObjectProperty.check(entry)) {
const values = t.ArrayExpression.check(entry.value)
? entry.value.elements
: [entry.value];
for (const value of values) {
if (
(t.StringLiteral.check(value) || t.Literal.check(value)) &&
typeof value.value === "string"
) {
entries.push(value.value);
}
}
}
}
this.traverse(path);
},
});

return {
names: [...devServerNames, ...buildNames],
buildEntries,
devServerEntries,
};
}

/**
* Finds the file that exports the Hono app: the Worker entry point in the project's Wrangler
* config, else the entry given to Hono's Vite plugins, else one of their default entries.
*
* @param projectPath The project's path
* @param wranglerConfig The project's Wrangler config, if any
* @param vitePluginEntries The entries given to Hono's Vite plugins
* @returns The entry file, relative to the project
* @throws {AutoConfigFrameworkConfigurationError} If there is no such file, or it doesn't export the app
*/
function findEntrypoint(
projectPath: string,
wranglerConfig: WranglerConfig | undefined,
vitePluginEntries: string[]
): string {
const wranglerEntries =
wranglerConfig?.main === undefined
? []
: [
resolve(
wranglerConfig.configPath
? dirname(wranglerConfig.configPath)
: projectPath,
wranglerConfig.main
),
];
const entry = [...wranglerEntries, ...vitePluginEntries, ...DEFAULT_ENTRIES]
.map((file) => resolve(projectPath, file))
.find((file) => existsSync(file));
Comment thread
edmundhung marked this conversation as resolved.
Resolved
if (entry === undefined) {
throw new AutoConfigFrameworkConfigurationError(
`Could not find the Hono app's entry file. cf looks for the \`entry\` given to Hono's Vite plugins, or else ${DEFAULT_ENTRIES.map((file) => `\`${file}\``).join(" or ")}.`,
{ telemetryMessage: "autoconfig hono entry missing" }
);
}

const entrypoint = relative(projectPath, entry).split(sep).join(posix.sep);
if (!hasDefaultExport(entry)) {
throw new AutoConfigFrameworkConfigurationError(
`\`${entrypoint}\` doesn't export the Hono app, so it can't run as a Worker. Export the app with \`export default app\`, and start any Node.js server from a separate file.`,
{ telemetryMessage: "autoconfig hono entry without default export" }
);
}

return entrypoint;
}

function hasDefaultExport(file: string): boolean {
return (
parseFile(file)?.body.some(
(statement) =>
t.ExportDefaultDeclaration.check(statement) ||
(t.ExportNamedDeclaration.check(statement) &&
(statement.specifiers ?? []).some(
(specifier) =>
t.Identifier.check(specifier.exported) &&
specifier.exported.name === "default"
))
) ?? false
);
}
3 changes: 2 additions & 1 deletion packages/autoconfig/src/frameworks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ export type FrameworkInfo = {
} & (
| { supported: false }
| {
supported: true;
/** Whether autoconfig can set the framework up for the configuration target */
supported: boolean;
supportsCf: boolean;
class: typeof Framework;
/** `undefined` for a framework without an npm package, such as Hugo */
Expand Down
19 changes: 19 additions & 0 deletions packages/autoconfig/src/frameworks/utils/packages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
import { join } from "node:path";
import { parsePackageJSON, readFileSync } from "@cloudflare/workers-utils";
import type { PackageJSON } from "@cloudflare/workers-utils";

export {
isPackageInstalled,
getInstalledPackageVersion,
} from "@cloudflare/workers-utils";

/**
* Reads a project's `package.json`.
*
* @param projectPath The project's path
* @returns The project's `package.json`, or undefined if it has none
*/
export function readPackageJson(projectPath: string): PackageJSON | undefined {
const path = join(projectPath, "package.json");
try {
return parsePackageJSON(readFileSync(path), path);
} catch {
return undefined;
}
}
9 changes: 6 additions & 3 deletions packages/autoconfig/src/frameworks/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,16 @@ export class Vite extends Framework {

/**
* Creates a minimal `vite.config` file with the Cloudflare plugin already
* configured. Used when a Vite project has no config file (e.g. projects
* scaffolded with `npm create vite@latest --template vanilla`).
* configured. Used when a project that builds with Vite has no config file (e.g. projects
* scaffolded with `npm create vite@latest --template vanilla`, or a Hono app).
*
* Use an explicit ESM extension for cf so the config can load the ESM-only
* plugin without changing the project's package.json module type.
*/
function createViteConfig(projectPath: string, target: AutoConfigTarget): void {
export function createViteConfig(
projectPath: string,
target: AutoConfigTarget
): void {
const ext =
target === "cf" ? "mts" : usesTypescript(projectPath) ? "ts" : "js";
const filePath = join(projectPath, `vite.config.${ext}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,26 @@ describe("detectFramework() / basic framework detection", () => {
});
});

it("does not run the build script of a framework without a build command when targeting cf", async ({
expect,
}) => {
await seed({
"package.json": JSON.stringify({
scripts: { build: "cf build", dev: "cf dev" },
dependencies: { hono: "4" },
}),
"package-lock.json": JSON.stringify({ lockfileVersion: 3 }),
});

const result = await detectFramework(process.cwd(), context);

expect(result.detectedFramework).toMatchObject({
framework: { id: "hono" },
buildCommand: undefined,
devCommand: undefined,
});
});

it("preserves command inference for an unsupported framework when targeting Wrangler", async ({
expect,
}) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ describe("autoconfig details - getDetailsForAutoConfig()", () => {
"cloudflare.config.ts": "export default {};",
"package.json": JSON.stringify({
scripts: { build: "cf build", dev: "cf dev" },
dependencies: { hono: "4", vite: "8" },
dependencies: { "@shopify/hydrogen": "2026.1.0", vite: "8" },
}),
"package-lock.json": JSON.stringify({ lockfileVersion: 3 }),
});
Expand All @@ -359,7 +359,7 @@ describe("autoconfig details - getDetailsForAutoConfig()", () => {
details.getDetailsForAutoConfig({ context })
).resolves.toMatchObject({
configured: true,
framework: { id: "hono" },
framework: { id: "hydrogen" },
buildCommand: undefined,
devCommand: undefined,
packageManager: { type: "npm" },
Expand Down
Loading
Loading