fix(init): revert init template to make init work again (#3530)

https://github.com/denoland/fresh/pull/3524 unfortunately introduced a
regression in the init script which breaks it. This was caused by two
independent problems:

1. Only files reachable in the module graph are published, meaning the
templates itself weren't published to JSR
2. When publishing to JSR all specifiers become `https://` internally
which breaks doing path operations like `path.resolve()`,
`path.relative()` and all others. This is something that cannot be
tested locally in advance

Addressing these is going to require a bit of work. The quickest way to
get init working again is to revert it.
This commit is contained in:
Marvin Hagemeister
2025-10-06 17:48:25 +02:00
committed by GitHub
parent b3c91bd008
commit 41fba500de
96 changed files with 1243 additions and 4053 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+850 -269
View File
File diff suppressed because it is too large Load Diff
+363
View File
@@ -0,0 +1,363 @@
import { expect } from "@std/expect";
import {
CONFIRM_TAILWIND_MESSAGE,
CONFIRM_VITE_MESSAGE,
CONFIRM_VSCODE_MESSAGE,
HELP_TEXT,
initProject,
} from "./init.ts";
import * as path from "@std/path";
import { getStdOutput, withBrowser } from "../../fresh/tests/test_utils.tsx";
import { waitForText } from "../../fresh/tests/test_utils.tsx";
import { withChildProcessServer } from "../../fresh/tests/test_utils.tsx";
import { withTmpDir as withTmpDirBase } from "../../fresh/src/test_utils.ts";
import { stub } from "@std/testing/mock";
// deno-lint-ignore no-explicit-any
(globalThis as any).INIT_TEST = true;
function stubPrompt(result: string) {
return stub(globalThis, "prompt", () => result);
}
function stubConfirm(steps: Record<string, boolean> = {}) {
return stub(
globalThis,
"confirm",
(message) => message ? steps[message] : false,
);
}
function stubLogs() {
return stub(
console,
"log",
() => undefined,
);
}
function withTmpDir(): Promise<{ dir: string } & AsyncDisposable> {
// Windows need temporary files in the repository root
if (Deno.build.os === "windows") {
const dir = path.join(import.meta.dirname!, "..", "..", "..", "..");
return withTmpDirBase({ dir, prefix: "tmp_" });
}
return withTmpDirBase();
}
async function patchProject(dir: string): Promise<void> {
const jsonPath = path.join(dir, "deno.json");
const json = JSON.parse(await Deno.readTextFile(jsonPath));
json.workspace = [];
// See https://github.com/denoland/deno/issues/27313
// json.links = [path.fromFileURL(new URL("../..", import.meta.url))];
json.links = [new URL("../../fresh", import.meta.url).href];
// assert with this stricter rule, before adding it to initialized projects
json.lint.rules.include = ["verbatim-module-syntax"];
await Deno.writeTextFile(jsonPath, JSON.stringify(json, null, 2) + "\n");
}
async function expectProjectFile(dir: string, pathname: string) {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
const stat = await Deno.stat(filePath);
if (!stat.isFile) {
throw new Error(`Not a project file: ${filePath}`);
}
}
async function expectNotProjectFile(dir: string, pathname: string) {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
try {
const stat = await Deno.stat(filePath);
if (stat.isFile) {
throw new Error(`A project file but expected it not to be: ${filePath}`);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
async function readProjectFile(dir: string, pathname: string): Promise<string> {
const filePath = path.join(dir, ...pathname.split("/").filter(Boolean));
const content = await Deno.readTextFile(filePath);
return content;
}
Deno.test("init - show help", async () => {
using logs = stubLogs();
await initProject("", [], { help: true });
const args = logs.calls.flatMap((c) => c.args);
const out = args.join("\n");
await initProject("", [], { h: true });
expect(out).toBe(HELP_TEXT);
expect(args).toEqual(logs.calls.flatMap((c) => c.args).slice(args.length));
});
Deno.test("init - new project", async () => {
await using tmp = await withTmpDir();
using _promptStub = stubPrompt("fresh-init");
using _confirmStub = stubConfirm();
await initProject(tmp.dir, [], { builder: true });
});
Deno.test("init - create project dir", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt("fresh-init");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
const root = path.join(dir, "fresh-init");
await expectProjectFile(root, "deno.json");
await expectProjectFile(root, "main.ts");
await expectProjectFile(root, "dev.ts");
await expectProjectFile(root, ".gitignore");
await expectProjectFile(root, "static/styles.css");
});
Deno.test("init - with tailwind", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_TAILWIND_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
const css = await readProjectFile(dir, "static/styles.css");
expect(css).toMatch(/@import "tailwindcss"/);
const main = await readProjectFile(dir, "main.ts");
const dev = await readProjectFile(dir, "dev.ts");
expect(main).not.toMatch(/tailwind/);
expect(dev).toMatch(/tailwind/);
});
Deno.test("init - with vscode", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_VSCODE_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, ".vscode/settings.json");
await expectProjectFile(dir, ".vscode/extensions.json");
});
Deno.test({
name: "init - fmt, lint, and type check project",
// Ignore this test on canary due to different formatting
// behaviours when the formatter changes.
ignore: Deno.version.deno.includes("+"),
fn: async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
},
});
Deno.test(
"init with tailwind - fmt, lint, and type check project",
async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_TAILWIND_MESSAGE]: true,
});
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const check = await new Deno.Command(Deno.execPath(), {
args: ["task", "check"],
cwd: dir,
stderr: "inherit",
stdout: "inherit",
}).output();
expect(check.code).toEqual(0);
},
);
Deno.test({
// TODO: For some reason this test is flaky in GitHub CI. It works when
// testing locally on windows though. Not sure what's going on.
ignore: Deno.build.os === "windows" && Deno.env.get("CI") !== undefined,
name: "init - can start dev server",
fn: async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
await withChildProcessServer(
{ cwd: dir, args: ["task", "dev"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("#decrement").click();
await waitForText(page, "button + p", "2");
});
},
);
},
});
Deno.test("init - can start built project", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
// Build
await new Deno.Command(Deno.execPath(), {
args: ["task", "build"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
await withChildProcessServer(
{ cwd: dir, env: { PORT: "0" }, args: ["task", "start"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("button").click();
await waitForText(page, "button + p", "2");
});
},
);
});
Deno.test("init - errors on missing build cache in prod", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], { builder: true });
await expectProjectFile(dir, "main.ts");
await expectProjectFile(dir, "dev.ts");
await patchProject(dir);
const cp = await new Deno.Command(Deno.execPath(), {
args: ["task", "start"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
const { stderr } = getStdOutput(cp);
expect(cp.code).toEqual(1);
expect(stderr).toMatch(/Module not found/);
});
// There is a peerDependency issue with links
Deno.test.ignore("init - vite dev server", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await expectNotProjectFile(dir, "dev.ts");
await patchProject(dir);
await withChildProcessServer(
{ cwd: dir, args: ["task", "dev"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("#decrement").click();
await waitForText(page, "button + p", "2");
});
},
);
});
// There is a peerDependency issue with links
Deno.test.ignore("init - vite build", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm();
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await patchProject(dir);
// Build
await new Deno.Command(Deno.execPath(), {
args: ["task", "build"],
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
}).output();
await withChildProcessServer(
{ cwd: dir, env: { PORT: "0" }, args: ["task", "start"] },
async (address) => {
await withBrowser(async (page) => {
await page.goto(address);
await page.locator("button").click();
await waitForText(page, "button + p", "2");
});
},
);
});
Deno.test("init - with vite", async () => {
await using tmp = await withTmpDir();
const dir = tmp.dir;
using _promptStub = stubPrompt(".");
using _confirmStub = stubConfirm({
[CONFIRM_VITE_MESSAGE]: true,
});
await initProject(dir, [], {});
await expectProjectFile(dir, "vite.config.ts");
await expectNotProjectFile(dir, "dev.ts");
});
+23 -217
View File
@@ -1,220 +1,26 @@
#!/usr/bin/env -S deno run -A
/**
* CLI entry point for @fresh/init
*
* This module serves two purposes:
* 1. CLI execution: Parses command-line arguments and runs the init script
* 2. Programmatic API: Exports initProject and resolveVersions for library use
*
* When run directly (deno run -Ar jsr:@fresh/init), this serves as
* the CLI entry point, providing interactive and non-interactive modes
* for creating new Fresh projects.
*/
import { parseArgs } from "@std/cli/parse-args";
import * as colors from "@std/fmt/colors";
import { initProject as initProjectImpl, resolveVersions } from "./init.ts";
import type { InitOptions } from "./types.ts";
import initConfig from "../deno.json" with { type: "json" };
import { initProject } from "./init.ts";
import { InitError } from "./init.ts";
const HELP_TEXT = `
${
colors.bgRgb8(
colors.rgb8(
` 🍋 @fresh/init${colors.rgb8(`@${initConfig.version}`, 248)} `,
0,
),
121,
)
}
Initialize a new Fresh project. This will create all the necessary files
for a new project.
To generate a project in the './foobar' subdirectory:
${colors.rgb8("deno run -Ar jsr:@fresh/init ./foobar", 245)}
To generate a project in the current directory:
${colors.rgb8("deno run -Ar jsr:@fresh/init .", 245)}
${colors.rgb8("USAGE:", 3)}
${colors.rgb8("deno run -Ar jsr:@fresh/init [DIRECTORY]", 245)}
${colors.rgb8("OPTIONS:", 3)}
${colors.rgb8("--force", 2)} Overwrite existing files
${colors.rgb8("--tailwind", 2)} Use Tailwind for styling
${colors.rgb8("--vscode", 2)} Setup project for VS Code
${colors.rgb8("--docker", 2)} Setup project to use Docker
${colors.rgb8("--builder", 2)} Setup with builder instead of vite
${colors.rgb8("--help, -h", 2)} Show this help message
`;
const CONFIRM_EMPTY_MESSAGE =
"The target directory is not empty (files could get overwritten). Do you want to continue anyway?";
const CONFIRM_TAILWIND_MESSAGE = `Set up ${
colors.cyan("Tailwind CSS")
} for styling?`;
const CONFIRM_VSCODE_MESSAGE = `Do you use ${colors.cyan("VS Code")}?`;
export class InitError extends Error {}
function error(message: string): never {
console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", "");
throw new InitError();
}
/**
* Initialize a Fresh project.
*
* This is the main CLI entry point that accepts command-line arguments
* and flags to create a new Fresh project.
*
* @param cwd - Current working directory
* @param input - Directory arguments from command line
* @param flags - CLI flags (force, tailwind, vscode, docker, builder, help)
*/
export async function initProject(
cwd: string = Deno.cwd(),
input: (string | number)[],
flags: {
docker?: boolean | null;
force?: boolean | null;
tailwind?: boolean | null;
vscode?: boolean | null;
builder?: boolean | null;
help?: boolean | null;
h?: boolean | null;
} = {},
): Promise<void> {
// Show help if requested
if (flags.help || flags.h) {
console.log(HELP_TEXT);
return;
}
// Display banner
console.log();
console.log(
colors.bgRgb8(
colors.rgb8(" 🍋 Fresh: The next-gen web framework. ", 0),
121,
),
);
console.log();
// Get project directory
let directory: string;
if (input.length === 0) {
const userInput = prompt("Project Name:", "fresh-project");
if (!userInput) {
error(HELP_TEXT);
}
directory = userInput;
} else if (input.length === 1) {
directory = String(input[0]);
} else {
error("Too many arguments. Expected at most one directory argument.");
}
// Build options from CLI flags (with prompts for missing values)
const tailwind = flags.tailwind ?? confirm(CONFIRM_TAILWIND_MESSAGE);
const vscode = flags.vscode ?? confirm(CONFIRM_VSCODE_MESSAGE);
let force = flags.force ?? false;
// Check if directory is empty (if not forced)
if (!force) {
try {
const projectDir = new URL(directory, `file://${cwd}/`).pathname;
const entries = [...Deno.readDirSync(projectDir)];
const isEmpty = entries.length === 0 ||
(entries.length === 1 && entries[0].name === ".git");
if (!isEmpty) {
const shouldContinue = confirm(CONFIRM_EMPTY_MESSAGE);
if (!shouldContinue) {
error("Directory is not empty. Use --force to overwrite.");
}
force = true;
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
// Directory doesn't exist - that's fine
}
}
// Build fully resolved options
const options: Required<InitOptions> = {
directory,
builder: flags.builder ?? false,
tailwind,
vscode,
docker: flags.docker ?? false,
force,
};
// Resolve versions
const versions = await resolveVersions();
console.log(` version ${colors.rgb8(versions.FRESH_VERSION, 4)}`);
console.log();
// Call the template engine (pure processing, no output)
await initProjectImpl(cwd, options, versions);
// Display success messages
console.log(
"\n%cProject initialized!\n",
"color: green; font-weight: bold",
);
if (directory !== ".") {
console.log(
`Enter your project directory using %ccd ${directory}%c.`,
"color: cyan",
"",
);
}
console.log(
"Run %cdeno task dev%c to start the project. %cCTRL-C%c to stop.",
"color: cyan",
"",
"color: cyan",
"",
);
console.log();
console.log(
"Stuck? Join our Discord %chttps://discord.gg/deno",
"color: cyan",
"",
);
console.log();
console.log("%cHappy hacking! 🦕", "color: gray");
}
// When run as CLI
if (import.meta.main) {
const flags = parseArgs(Deno.args, {
boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"],
default: {
force: null,
tailwind: null,
vscode: null,
docker: null,
builder: null,
},
alias: {
help: "h",
},
});
try {
await initProject(Deno.cwd(), flags._, flags);
} catch (err) {
if (err instanceof InitError) {
Deno.exit(1);
}
throw err;
}
const flags = parseArgs(Deno.args, {
boolean: ["force", "tailwind", "vscode", "docker", "help", "builder"],
default: {
force: null,
tailwind: null,
vscode: null,
docker: null,
builder: null,
},
alias: {
help: "h",
},
});
try {
await initProject(Deno.cwd(), flags._, flags);
} catch (err) {
if (err instanceof InitError) {
Deno.exit(1);
}
throw err;
}
-211
View File
@@ -1,211 +0,0 @@
#!/usr/bin/env -S deno run -A
/**
* Sync script for template maintenance.
*
* This script copies common files from base templates to their corresponding
* template variants, making it easier to maintain shared files across templates.
*
* Structure:
* - assets/base/vite/ -> Copied to assets/template/vite/ and vite-tailwind/
* - assets/base/builder/ -> Copied to assets/template/builder/ and builder-tailwind/
*
* Template-specific files (like deno.json.tmpl, styles.css) are never overwritten.
*
* Usage:
* deno run -A sync_templates.ts
* deno run -A sync_templates.ts --dry-run
*/
import * as path from "@std/path";
import * as fs from "@std/fs";
import * as colors from "@std/fmt/colors";
/**
* Files that should NOT be copied from base to templates.
* These are template-specific and should be maintained separately.
*/
const TEMPLATE_SPECIFIC_FILES = [
// Dependency files - different for each template variant
"deno.json.tmpl",
"deno.json",
// Build config - tailwind variants override these
"vite.config.ts",
// Styles - different content for tailwind vs regular
"assets/styles.css",
"static/styles.css",
];
/**
* Template configurations.
*/
const TEMPLATE_CONFIG = {
vite: {
base: "assets/base/vite",
targets: ["assets/template/vite", "assets/template/vite-tailwind"],
},
builder: {
base: "assets/base/builder",
targets: ["assets/template/builder", "assets/template/builder-tailwind"],
},
};
interface SyncResult {
copied: string[];
skipped: string[];
errors: string[];
}
/**
* Check if a file path should be skipped (template-specific).
*/
function isTemplateSpecific(relPath: string): boolean {
return TEMPLATE_SPECIFIC_FILES.some((specific) =>
relPath === specific || relPath.endsWith(`/${specific}`)
);
}
/**
* Recursively copy files from source to destination, skipping template-specific files.
*/
async function syncDirectory(
srcDir: string,
destDir: string,
baseDir: string,
dryRun: boolean,
): Promise<SyncResult> {
const result: SyncResult = { copied: [], skipped: [], errors: [] };
try {
for await (const entry of Deno.readDir(srcDir)) {
const srcPath = path.join(srcDir, entry.name);
const destPath = path.join(destDir, entry.name);
const relPath = path.relative(baseDir, srcPath);
if (entry.isDirectory) {
// Recursively sync directories
if (!dryRun) {
await fs.ensureDir(destPath);
}
const subResult = await syncDirectory(
srcPath,
destPath,
baseDir,
dryRun,
);
result.copied.push(...subResult.copied);
result.skipped.push(...subResult.skipped);
result.errors.push(...subResult.errors);
} else {
// Check if file is template-specific
if (isTemplateSpecific(relPath)) {
result.skipped.push(relPath);
continue;
}
// Copy file
try {
if (!dryRun) {
await fs.copy(srcPath, destPath, { overwrite: true });
}
result.copied.push(relPath);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
result.errors.push(`${relPath}: ${message}`);
}
}
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
result.errors.push(`Error reading ${srcDir}: ${message}`);
}
return result;
}
/**
* Sync base template to all its target templates.
*/
async function syncTemplate(
name: string,
config: { base: string; targets: string[] },
dryRun: boolean,
): Promise<void> {
console.log(colors.bold(colors.cyan(`\n📦 Syncing ${name} templates...`)));
console.log(colors.dim(` Base: ${config.base}`));
for (const target of config.targets) {
const targetName = path.basename(target);
console.log(colors.dim(` → ${targetName}`));
const result = await syncDirectory(
config.base,
target,
config.base,
dryRun,
);
if (result.copied.length > 0) {
console.log(
colors.green(
` ✓ ${result.copied.length} file(s) ${
dryRun ? "would be copied" : "copied"
}`,
),
);
}
if (result.skipped.length > 0) {
console.log(
colors.yellow(
` ⊘ ${result.skipped.length} file(s) skipped (template-specific)`,
),
);
}
if (result.errors.length > 0) {
console.log(colors.red(` ✗ ${result.errors.length} error(s):`));
for (const error of result.errors) {
console.log(colors.red(` ${error}`));
}
}
}
}
/**
* Main sync function.
*/
async function main() {
const args = Deno.args;
const dryRun = args.includes("--dry-run");
console.log(colors.bold("\n🔄 Template Sync Tool\n"));
if (dryRun) {
console.log(colors.yellow("🔍 DRY RUN MODE - No files will be modified\n"));
}
// Sync all template groups
for (const [name, config] of Object.entries(TEMPLATE_CONFIG)) {
await syncTemplate(name, config, dryRun);
}
console.log(colors.bold(colors.green("\n✅ Sync complete!")));
if (dryRun) {
console.log(
colors.dim("\nRun without --dry-run to actually copy files."),
);
} else {
console.log(
colors.dim(
"\nReview changes with git diff before committing.",
),
);
}
}
if (import.meta.main) {
await main();
}
-82
View File
@@ -1,82 +0,0 @@
/**
* Options for initializing a Fresh project.
* Optional fields will use defaults or prompt the user.
*
* @example
* ```ts
* const options: InitOptions = {
* directory: "./my-app",
* tailwind: true,
* vscode: false,
* docker: false,
* builder: false,
* force: false,
* };
* ```
*/
export interface InitOptions {
/** Target directory for the project */
directory: string;
/** Use legacy builder instead of Vite (default: false) */
builder?: boolean;
/** Include Tailwind CSS setup (default: prompt user) */
tailwind?: boolean;
/** Include VS Code configuration (default: prompt user) */
vscode?: boolean;
/** Include Docker setup (default: false) */
docker?: boolean;
/** Force overwrite existing files (default: false) */
force?: boolean;
}
/**
* Version overrides for testing or pinning specific versions.
* All fields are optional and use camelCase naming.
*/
export type VersionOverrides = Partial<{
fresh: string;
freshTailwind: string;
freshVitePlugin: string;
preact: string;
preactSignals: string;
tailwindcss: string;
tailwindcssPostcss: string;
tailwindcssVite: string;
postcss: string;
vite: string;
}>;
/**
* Variables available for template substitution using __VARIABLE__ syntax.
* All fields represent actual template placeholders in template files.
*
* @example
* ```ts
* const variables: TemplateVariables = {
* PROJECT_NAME: "my-app",
* FRESH_VERSION: "2.1.1",
* PREACT_VERSION: "10.27.2",
* // ... other version strings
* };
* // In templates: __PROJECT_NAME__, __FRESH_VERSION__, etc.
* ```
*/
export interface TemplateVariables {
PROJECT_NAME: string;
FRESH_VERSION: string;
FRESH_TAILWIND_VERSION: string;
FRESH_VITE_PLUGIN_VERSION: string;
PREACT_VERSION: string;
PREACT_SIGNALS_VERSION: string;
TAILWINDCSS_VERSION: string;
TAILWINDCSS_POSTCSS_VERSION: string;
TAILWINDCSS_VITE_VERSION: string;
POSTCSS_VERSION: string;
VITE_VERSION: string;
DENO_VERSION: string;
}
-186
View File
@@ -1,186 +0,0 @@
import * as path from "@std/path";
import * as fs from "@std/fs";
import * as semver from "@std/semver";
/**
* Fetch the latest version of a package from JSR or npm.
*/
export async function getLatestVersion(
pkg: string,
fallback: string,
): Promise<string> {
// In test mode, always use fallback to avoid network calls
// deno-lint-ignore no-explicit-any
if ((globalThis as any).INIT_TEST) {
return fallback;
}
try {
// Check if it's an npm package
if (pkg.startsWith("npm:")) {
const npmPkg = pkg.slice(4); // Remove "npm:" prefix
const res = await fetch(`https://registry.npmjs.org/${npmPkg}/latest`);
if (!res.ok) {
await res.body?.cancel();
throw new Error(`HTTP ${res.status}`);
}
const json = await res.json() as { version: string };
return json.version;
}
// JSR package
const res = await fetch(`https://jsr.io/${pkg}/meta.json`);
if (!res.ok) {
await res.body?.cancel(); // Consume the body to avoid leaks
throw new Error(`HTTP ${res.status}`);
}
const json = await res.json() as {
latest: string | null;
versions: Record<string, unknown>;
};
if (json.latest !== null) {
return json.latest;
}
const versions = Object.keys(json.versions);
if (versions.length === 0) {
throw new Error("No versions available");
}
versions.sort((a, b) => {
const s1 = semver.parse(a);
const s2 = semver.parse(b);
return semver.compare(s1, s2);
});
return versions.at(-1)!;
} catch (err) {
// Silent fallback for network or API errors
const message = err instanceof Error ? err.message : String(err);
console.error(
`Could not fetch latest ${pkg} version: ${message}. Using fallback: ${fallback}`,
);
return fallback;
}
}
/**
* Check if a directory exists and is empty (or only contains .git).
*/
export async function isDirectoryEmpty(dir: string): Promise<boolean> {
try {
const entries = [];
for await (const entry of Deno.readDir(dir)) {
entries.push(entry);
}
return entries.length === 0 ||
(entries.length === 1 && entries[0].name === ".git");
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return true; // Directory doesn't exist, so it's "empty"
}
throw err;
}
}
/**
* Recursively copy a directory.
*/
export async function copyDir(src: string, dest: string): Promise<void> {
await fs.ensureDir(dest);
for await (const entry of Deno.readDir(src)) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory) {
await copyDir(srcPath, destPath);
} else {
await fs.copy(srcPath, destPath, { overwrite: true });
}
}
}
/**
* Substitute variables in a template string.
* Replaces __VAR__ patterns with values.
*/
export function substituteVariables(
content: string,
variables: Record<string, string | boolean | number>,
): string {
let result = content;
for (const [key, value] of Object.entries(variables)) {
const regex = new RegExp(`__${key}__`, "g");
result = result.replace(regex, String(value));
}
return result;
}
/**
* Convert double-underscore-prefixed filename to dot-prefixed.
* Only converts files/dirs that start with double underscore (__).
* Files with single underscore (like _app.tsx) are NOT converted.
* Examples:
* - "__gitignore" -> ".gitignore"
* - "__vscode" -> ".vscode"
* - "_app.tsx" -> "_app.tsx" (unchanged)
*/
export function processFilename(filename: string): string {
if (filename.startsWith("__")) {
return "." + filename.slice(2);
}
return filename;
}
/**
* Get the template directory path.
*/
export function getTemplateDir(): string {
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
return path.join(moduleDir, "..", "assets", "template");
}
/**
* Get the variants directory path.
*/
export function getVariantsDir(): string {
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
return path.join(moduleDir, "..", "assets", "variants");
}
/**
* Prompt user for confirmation (or use provided value).
*/
export function confirmOrValue(
message: string,
providedValue: boolean | undefined,
): boolean {
if (providedValue !== undefined) {
return providedValue;
}
return confirm(message);
}
/**
* Prompt user for input (or use provided value).
*/
export function promptOrValue(
message: string,
defaultValue: string,
providedValue: string | undefined,
): string {
if (providedValue !== undefined) {
return providedValue;
}
const result = prompt(message, defaultValue);
if (!result) {
throw new Error("Input required");
}
return result;
}