@cellajs/create-cella 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["packageJson.description","packageJson.version","packageJson.homepage","fs"],"sources":["../package.json","../src/constants.ts","../src/utils/git/command.ts","../src/add-remote.ts","../src/utils/detect-used-ports.ts","../src/utils/is-email.ts","../src/utils/validate-project-name.ts","../src/modules/cli/commands.ts","../src/modules/cli/display.ts","../src/utils/clean-template.ts","../src/utils/download-template.ts","../src/utils/list-template-files.ts","../src/utils/progress.ts","../src/create.ts","../src/utils/busy-ports.ts","../src/utils/fetch-template-metadata.ts","../src/utils/is-empty-directory.ts","../src/create-cella-cli.ts"],"sourcesContent":["","import pc from 'picocolors';\nimport packageJson from '../package.json' with { type: 'json' };\n\n/** Name of this CLI tool */\nexport const NAME = 'create cella';\n\n/** Thin line divider for console output (60 chars wide) */\nexport const DIVIDER = '─'.repeat(60);\n\n/** URL of the template repository */\nexport const TEMPLATE_URL = 'github:cellajs/cella';\n\n/** Canonical owner/repo for template metadata fetched from the GitHub API. */\nexport const TEMPLATE_REPOSITORY = 'cellajs/cella';\n\n/** HTTPS git URL of the template, for reading its release tags without the GitHub API. */\nexport const TEMPLATE_GIT_URL = `https://github.com/${TEMPLATE_REPOSITORY}.git`;\n\n/** The app's sync config, which the template ships with its own settings. */\nexport const SYNC_CONFIG = 'cella/cella.config.ts';\n\n/** Upstream remote of a new app: HTTPS, so reading a public template needs no SSH key. */\nexport const CELLA_REMOTE_URL = TEMPLATE_GIT_URL;\n\n/**\n * Git remote name pointing at upstream cella. Matches the name the sync CLI\n * (`pnpm cella`) expects, so scaffolds don't end up with a duplicate remote.\n */\nexport const CELLA_REMOTE_NAME = 'cella-upstream';\n\n/** Export details from package.json */\nexport const DESCRIPTION: string = packageJson.description;\nexport const VERSION: string = packageJson.version;\nexport const WEBSITE: string = packageJson.homepage;\n\nexport function getHeaderLine(): string {\n const leftText = `⧈ ${NAME} · ${VERSION}`;\n const left = `${pc.cyan(`⧈ ${NAME}`)} ${pc.dim(`· ${VERSION}`)}`;\n const right = pc.cyan(WEBSITE);\n const padding = Math.max(1, 60 - leftText.length - WEBSITE.length);\n return `${left}${' '.repeat(padding)}${right}`;\n}\n\n// Files or folders to be removed from the template after downloading.\n// The Pulumi stack files carry cella's own bootstrap markers and encryption\n// salt; a fresh app bootstraps its own. Removing them also keeps the deploy\n// workflow's staging gate false until the app bootstraps, so a fresh scaffold\n// never auto-deploys staging on its first push to main.\nexport const TO_REMOVE: string[] = ['./infra/Pulumi.production.yaml', './infra/Pulumi.staging.yaml'];\n\n// Specific folder contents to be cleaned out from the template\nexport const TO_CLEAN: string[] = ['./backend/drizzle'];\n\n// Files to copy/paste after downloading\nexport const TO_COPY: Record<string, string> = {\n './frontend/.env.example': './frontend/.env',\n};\n\n/** The template's quickstart, which becomes the new app's README. */\nexport const QUICKSTART = './cella/QUICKSTART.md';\n\n/** Entry points a coding agent reads from the repo root; the rules and skills live in the template's `cella/` folder. */\nexport const AGENT_FILES: Record<string, string> = {\n 'AGENTS.md':\n '# Agent guidelines\\n\\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\\n',\n 'CLAUDE.md': '@cella/AGENTS.md\\n',\n};\n\n/** Frontend dev port of an app number. */\nexport const frontendPort = (appIndex: number): number => 3000 + appIndex;\n\n/**\n * The quickstart as the README of a new app: at the repo root, with this app's port and without the step that just ran.\n * Its links are relative to `cella/` in the template, so `./x` becomes `./cella/x` and `../x` becomes `./x`.\n */\nexport function quickstartToReadme(source: string, displayName: string, appIndex: number): string {\n return source\n .replace(/^# .*$/m, `# ${displayName}`)\n .replace(/^## Create\\n[\\s\\S]*?(?=^## )/m, '')\n .replaceAll('](./', '](./cella/')\n .replaceAll('](../', '](./')\n .replaceAll('http://localhost:3000', `http://localhost:${frontendPort(appIndex)}`);\n}\n\n/**\n * Fork config template that replaces `shared/config/config.default.ts` in new forks.\n */\nexport const PLACEHOLDER_CONFIG = 'shared/config/config.template.ts';\n\n/**\n * Starting version for a fresh fork. Resets the upstream cella version so\n * release-please cuts the fork's first release from a clean slate.\n */\nexport const INITIAL_VERSION = '0.0.0';\n\n/**\n * Read a `.env.example` file and apply key=value replacements.\n * Comments and unmatched keys are preserved as-is.\n * Returns null if the file doesn't exist (caller should generate from scratch).\n */\nexport async function generateEnvFromExample(\n examplePath: string,\n replacements: Record<string, string>,\n): Promise<string | null> {\n const { readFile } = await import('node:fs/promises');\n let content: string;\n try {\n content = await readFile(examplePath, 'utf8');\n } catch {\n return null;\n }\n\n return content.replace(/^([A-Z_][A-Z0-9_]*)=(.*)$/gm, (match, key, _value) => {\n if (key in replacements) return `${key}=${replacements[key]}`;\n return match;\n });\n}\n\n/**\n * Replacement map for the app's `.env`: the seed admin alone. The database ports and URLs follow `devAppIndex` in the\n * shared config, and the service ports come from `services` there, so no port lives in the env file.\n */\nexport function getBackendEnvReplacements(adminEmail: string): Record<string, string> {\n return { ADMIN_EMAIL: adminEmail };\n}\n\n/** Set the app's number in the source of `config.default.ts`; a template without the key can only give index 0. */\nexport function setDevAppIndex(source: string, appIndex: number): string {\n const pattern = /^(\\s*devAppIndex:\\s*)\\d+/m;\n if (appIndex !== 0 && !pattern.test(source)) {\n throw new Error('This template has no devAppIndex in its config: use app index 0, or a newer template.');\n }\n return source.replace(pattern, (_, head: string) => `${head}${appIndex}`);\n}\n","import fs from 'node:fs';\nimport git from 'isomorphic-git';\n\n/**\n * Git helpers backed by isomorphic-git (pure JS) instead of shelling out to the\n * `git` binary. This keeps `create-cella` free of `child_process` (no shell access)\n * and removes any dependency on the user's global git config — the initial commit\n * uses an explicit author, so scaffolding never fails with \"Author identity unknown\".\n */\n\n/** Author used for the scaffold's initial commit (users re-author their own commits later). */\nconst INITIAL_AUTHOR = { name: 'cella', email: 'info@cellajs.com' } as const;\n\n/**\n * Initializes a new Git repository in the specified directory.\n */\nexport async function gitInit(repoPath: string): Promise<void> {\n await git.init({ fs, dir: repoPath, defaultBranch: 'main' });\n}\n\n/**\n * Stages all files in the repository (respects `.gitignore`).\n */\nexport async function gitAddAll(repoPath: string): Promise<void> {\n await git.add({ fs, dir: repoPath, filepath: '.' });\n}\n\n/**\n * Creates a commit with the specified message and returns the commit SHA.\n */\nexport async function gitCommit(repoPath: string, message: string): Promise<string> {\n return git.commit({ fs, dir: repoPath, message, author: INITIAL_AUTHOR });\n}\n\n/**\n * Gets the URL of a remote. Throws when the remote does not exist (mirrors\n * `git remote get-url` failing) so callers can detect a missing remote.\n */\nexport async function gitRemoteGetUrl(repoPath: string, remoteName: string): Promise<string> {\n const remotes = await git.listRemotes({ fs, dir: repoPath });\n const match = remotes.find((r) => r.remote === remoteName);\n if (!match) throw new Error(`No such remote '${remoteName}'`);\n return match.url;\n}\n\n/**\n * Adds a new remote.\n */\nexport async function gitRemoteAdd(repoPath: string, remoteName: string, remoteUrl: string): Promise<void> {\n await git.addRemote({ fs, dir: repoPath, remote: remoteName, url: remoteUrl });\n}\n\n/**\n * Removes a remote.\n */\nexport async function gitRemoteRemove(repoPath: string, remoteName: string): Promise<void> {\n await git.deleteRemote({ fs, dir: repoPath, remote: remoteName });\n}\n","import { CELLA_REMOTE_NAME, CELLA_REMOTE_URL } from '#/constants';\nimport type { AddRemoteOptions } from '#/modules/cli';\nimport { gitRemoteAdd, gitRemoteGetUrl, gitRemoteRemove } from '#/utils/git';\n\n/**\n * Adds or updates the upstream remote for the Cella template.\n * @param options - Configuration options\n * @param options.silent - If true, don't throw on failure (used when called from progress tracker)\n */\nexport async function addRemote({\n targetFolder,\n remoteUrl = CELLA_REMOTE_URL,\n remoteName = CELLA_REMOTE_NAME,\n silent = false,\n}: AddRemoteOptions): Promise<void> {\n try {\n // Check if the remote exists\n let remote: string | null = null;\n\n try {\n remote = await gitRemoteGetUrl(targetFolder, remoteName);\n } catch {\n // If the remote doesn't exist, it throws a fatal error\n remote = null;\n }\n\n // Add or update the remote if it doesn't exist or differs from `remoteUrl`\n if (!remote) {\n await gitRemoteAdd(targetFolder, remoteName, remoteUrl);\n } else if (remote !== remoteUrl) {\n // Remove existing remote and set the new URL\n await gitRemoteRemove(targetFolder, remoteName);\n await gitRemoteAdd(targetFolder, remoteName, remoteUrl);\n }\n } catch (error) {\n if (!silent) {\n throw error;\n }\n }\n}\n","import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\n\ninterface UsedPorts {\n project: string;\n frontend: number;\n backend: number;\n}\n\n/**\n * Scan sibling directories for existing cella apps and extract their dev ports.\n * Looks for `shared/config/config.development.ts` to identify cella-based projects. The frontend port sits in that\n * file's `origin`, or `frontendUrl` in older apps; the backend port in `services.backend.port` of `config.default.ts`,\n * or `devPorts` in either file before that; `devAppIndex` in the default config moves whatever ports the files carry.\n * Handles legacy configs with backendUrl on its own port.\n */\nexport async function detectUsedPorts(targetFolder: string): Promise<UsedPorts[]> {\n const parentDir = dirname(targetFolder);\n const used: UsedPorts[] = [];\n\n let siblings: string[];\n try {\n siblings = await readdir(parentDir);\n } catch {\n return used;\n }\n\n for (const name of siblings) {\n const configDir = join(parentDir, name, 'shared/config');\n try {\n const development = await readFile(join(configDir, 'config.development.ts'), 'utf8');\n const defaults = await readFile(join(configDir, 'config.default.ts'), 'utf8').catch(() => '');\n const feMatch = development.match(/(?:origin|frontendUrl):\\s*'http:\\/\\/localhost:(\\d+)/);\n if (!feMatch) continue;\n const frontend = Number(feMatch[1]);\n const index = Number(defaults.match(/devAppIndex:\\s*(\\d+)/)?.[1] ?? 0);\n // Oldest forks predate devPorts and a backendUrl port; assume the paired port then.\n const servicePattern = /backend:\\s*\\{[^}]*?\\bport:\\s*(\\d+)/;\n const apiPattern = /devPorts:\\s*\\{[^}]*?\\bapi:\\s*(\\d+)/;\n const portMatch = defaults.match(servicePattern) ?? development.match(apiPattern) ?? defaults.match(apiPattern);\n const legacyBeMatch = development.match(/backendUrl:\\s*'http:\\/\\/localhost:(\\d+)'/);\n const backend = portMatch ? Number(portMatch[1]) : legacyBeMatch ? Number(legacyBeMatch[1]) : frontend + 1000;\n used.push({ project: name, frontend: frontend + index, backend: backend + index * 10 });\n } catch {\n // Not a cella app, skip\n }\n }\n\n return used;\n}\n\n/** Index 4 is never offered: its internal listener would sit on 4045, which fetch refuses. */\nexport const isAppIndex = (index: number): boolean =>\n Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;\n\n/** Find the first app index whose frontend port and service block no sibling uses and that `isBusy` leaves free. */\nexport function findNextAppIndex(usedPorts: UsedPorts[], isBusy: (index: number) => boolean = () => false): number {\n for (let index = 0; index <= 9; index += 1) {\n if (!isAppIndex(index) || isBusy(index)) continue;\n const api = 4000 + index * 10;\n const taken = usedPorts.some((p) => p.frontend === 3000 + index || (p.backend >= api && p.backend < api + 10));\n if (!taken) return index;\n }\n return 0;\n}\n","/** A plain shape check: the value lands on one line of the app's `.env` and is the seed user's sign-in address. */\nexport const isEmail = (value: string): boolean => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value);\n","import validate from 'validate-npm-package-name';\n\ninterface ValidationResult {\n valid: boolean;\n problems?: string[];\n}\n\nexport function validateProjectName(name: string): ValidationResult {\n const nameValidation = validate(name);\n\n if (nameValidation.validForNewPackages) {\n return { valid: true };\n }\n\n return {\n valid: false,\n problems: [...(nameValidation.errors || []), ...(nameValidation.warnings || [])],\n };\n}\n","import { basename, resolve } from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { NAME, VERSION } from '#/constants';\nimport { isAppIndex } from '#/utils/detect-used-ports';\nimport { isEmail } from '#/utils/is-email';\nimport { validateProjectName } from '#/utils/validate-project-name';\nimport type { CLIConfig, CLIOptions } from './types';\n\nfunction parseAppIndex(value: string): number {\n const parsed = Number(value);\n\n if (!isAppIndex(parsed)) {\n throw new InvalidArgumentError('App index must be a whole number from 0 to 9, not 4');\n }\n\n return parsed;\n}\n\nfunction parseAdminEmail(value: string): string {\n if (!isEmail(value)) throw new InvalidArgumentError('Admin email must be an address such as admin@example.com');\n return value;\n}\n\n// Initialize CLI variables\nlet directory: string | null = null;\nconst packageManager = 'pnpm';\n\n/**\n * Defines the root CLI command using Commander.\n * This command accepts CLI options and validates user input.\n */\nexport const command = new Command(NAME)\n .version(VERSION, '-v, --version', `output the current version of ${NAME}`)\n .argument('[directory]', 'the directory name for the new project')\n .usage('[directory] [options]')\n .helpOption('-h, --help', 'display this help message')\n .option('--template <path>', 'use a custom template (local path or github:user/repo)')\n .option('--app-index <number>', \"set this app's number for its dev ports (0-9, not 4)\", parseAppIndex)\n .option('--admin-email <email>', 'set the admin email for the initial seed user', parseAdminEmail)\n .action((name: string, _options: CLIOptions, self: Command) => {\n const trimmedName = typeof name === 'string' ? name.trim() : name;\n\n if (trimmedName) {\n const validation = validateProjectName(basename(resolve(trimmedName)));\n\n if (!validation.valid) {\n self.error(\n `error: invalid project name \"${trimmedName}\": ${validation.problems?.[0] ?? 'unknown error'}. Use lowercase letters, digits and dashes, such as my-app.`,\n );\n }\n\n directory = trimmedName;\n }\n })\n .parse();\n\n// Gather the CLI options and arguments\nconst options: CLIOptions = command.opts<CLIOptions>();\n\n/**\n * Runs the CLI and returns the parsed configuration.\n * This function parses command line arguments and returns the CLI config.\n */\nexport function runCli(): CLIConfig {\n return {\n options,\n args: command.args,\n directory,\n packageManager,\n };\n}\n\n// Export CLI configuration for direct import\nexport const cli: CLIConfig = runCli();\n","import pc from 'picocolors';\nimport { DESCRIPTION, DIVIDER, frontendPort, getHeaderLine } from '#/constants';\n\n/** ASCII art logo for the CLI welcome screen. */\nfunction showAscii(): void {\n console.info(pc.cyan(' _ _ '));\n console.info(pc.cyan('▒▓█████▓▒ ___ ___| | | __ _ '));\n console.info(pc.cyan('▒▓█ █▓▒ / __/ _ \\\\ | |/ _` | '));\n console.info(pc.cyan('▒▓█ █▓▒ | (_| __/ | | (_| | '));\n console.info(pc.cyan('▒▓█████▓▒ \\\\___\\\\___|_|_|\\\\__,_| '));\n}\n\n/**\n * Displays the compact CLI welcome header.\n */\nexport function showWelcome(): void {\n console.info();\n showAscii();\n console.info();\n console.info(pc.dim(DESCRIPTION));\n console.info();\n console.info(getHeaderLine());\n console.info(DIVIDER);\n}\n\n/**\n * Print a cleared prompt's outcome as a persistent confirmation line:\n * `✓ <label> · <value>`, followed by a blank separator line. Used after prompts\n * that clear themselves on done so the chosen value stays visible.\n */\nexport function confirmChoice(label: string, value: string): void {\n console.info(`${pc.green('✓')} ${label} · ${value}`);\n console.info();\n}\n\n/**\n * Displays the final success message after project creation.\n */\nexport function showSuccess(\n projectName: string,\n _targetFolder: string,\n relativePath: string,\n needsCd: boolean,\n packageManager: string,\n appIndex: number,\n adminEmail: string,\n): void {\n console.info();\n\n console.info(pc.bold('Next steps'));\n console.info(DIVIDER);\n console.info();\n\n if (needsCd) {\n console.info(`${pc.dim('$')} cd ${pc.cyan(relativePath)}`);\n }\n console.info(`${pc.dim('$')} ${pc.cyan(`${packageManager} install`)}`);\n console.info(`${pc.dim('$')} ${pc.cyan(`${packageManager} generate`)}`);\n console.info(\n `${pc.dim('$')} ${pc.cyan(`${packageManager} docker`)} ${pc.dim('&&')} ${pc.cyan(`${packageManager} seed`)} ${pc.dim('&&')} ${pc.cyan(`${packageManager} dev`)}`,\n );\n console.info();\n console.info(\n `${pc.gray('Then open')} ${pc.cyan(`http://localhost:${frontendPort(appIndex)}`)} ${pc.gray('and sign in as')} ${pc.cyan(adminEmail)}${pc.gray(`: the magic link is printed in the ${packageManager} dev output.`)}`,\n );\n console.info();\n\n // Point to the generated README for first-run details and sign-in credentials. Use the\n // path relative to the new project so the terminal linkifies the right file (not this CLI's).\n const readmePath = relativePath ? `${relativePath}/README.md` : 'README.md';\n console.info(`${pc.gray('To get started building, please read:')} ${pc.cyan(readmePath)}`);\n console.info();\n console.info(`🥳 enjoy building ${pc.green(projectName)} with cella!`);\n console.info();\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport pc from 'picocolors';\nimport {\n AGENT_FILES,\n generateEnvFromExample,\n getBackendEnvReplacements,\n INITIAL_VERSION,\n PLACEHOLDER_CONFIG,\n QUICKSTART,\n quickstartToReadme,\n SYNC_CONFIG,\n setDevAppIndex,\n TO_CLEAN,\n TO_COPY,\n TO_REMOVE,\n} from '#/constants';\n\nconst warningMark = pc.yellow('⚠');\n\n/**\n * Cleans the specified template by removing designated folders and files.\n * @param params - Parameters containing the target folder, project name, and optional extra edits.\n */\nexport async function cleanTemplate({\n targetFolder,\n projectName,\n displayName,\n appIndex = 0,\n adminEmail = `admin@${projectName}.example.com`,\n}: {\n targetFolder: string;\n projectName: string;\n displayName: string;\n appIndex?: number;\n adminEmail?: string;\n}): Promise<void> {\n // Change the current working directory to targetFolder if not already set\n if (process.cwd() !== targetFolder) {\n process.chdir(targetFolder);\n }\n\n return new Promise<void>((resolve, reject) => {\n (async () => {\n try {\n // Copy specified files\n for (const [src, dest] of Object.entries(TO_COPY)) {\n const srcAbsolutePath = path.resolve(targetFolder, src);\n const destAbsolutePath = path.resolve(targetFolder, dest);\n await copyFile(srcAbsolutePath, destAbsolutePath);\n }\n\n await writeReadme(targetFolder, displayName, appIndex);\n await writeAgentEntry(targetFolder);\n\n // Replace config.default.ts with interpolated placeholder config\n await applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex);\n\n // Reset release/versioning state so the fork starts under its own identity\n await resetReleaseState(targetFolder, projectName);\n\n // Drop the template's own list of downstream repos from the sync config\n await removeTemplateForks(targetFolder);\n\n // Generate the app's .env from the template's .env.example: at the repo root, or in backend/ for a template from\n // before that move. The mode configs (config.development.ts and its siblings) derive from config.default.ts and\n // stay as the template ships them.\n const replacements = getBackendEnvReplacements(adminEmail);\n const rootEnv = await generateEnvFromExample(path.resolve(targetFolder, '.env.example'), replacements);\n const appEnv =\n rootEnv ?? (await generateEnvFromExample(path.resolve(targetFolder, 'backend/.env.example'), replacements));\n if (appEnv) {\n await fs.writeFile(path.resolve(targetFolder, rootEnv ? '.env' : 'backend/.env'), appEnv, 'utf8');\n }\n\n // Clean specified folder contents\n await Promise.all(\n TO_CLEAN.map((folderPath) => {\n const absolutePath = path.resolve(targetFolder, folderPath);\n return removeFolderContents(absolutePath);\n }),\n );\n\n // Remove specified files and folders\n await Promise.all(\n TO_REMOVE.map((filePath) => {\n const absolutePath = path.resolve(targetFolder, filePath);\n return removeFileOrFolder(absolutePath);\n }),\n );\n\n resolve();\n } catch (err) {\n reject(`Error during the cleaning process: ${err}`);\n }\n })();\n });\n}\n\n/** Write the app's README from the template's quickstart. A template without one keeps its own README. */\nasync function writeReadme(targetFolder: string, displayName: string, appIndex: number): Promise<void> {\n try {\n const quickstart = await fs.readFile(path.resolve(targetFolder, QUICKSTART), 'utf8');\n const readme = quickstartToReadme(quickstart, displayName, appIndex);\n await fs.writeFile(path.resolve(targetFolder, 'README.md'), readme, 'utf8');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n console.info(`\\n${warningMark} \"${QUICKSTART}\" not found > Skip README`);\n }\n}\n\n/** Point coding agents at the template's rules and skills, which sit in `cella/`, out of a root they would not search. */\nasync function writeAgentEntry(targetFolder: string): Promise<void> {\n await Promise.all(\n Object.entries(AGENT_FILES).map(([file, content]) =>\n fs.writeFile(path.resolve(targetFolder, file), content, 'utf8'),\n ),\n );\n\n // Local to this clone: `.claude` is gitignored, and the check scripts read tracked paths as files. AGENTS.md names the folder for a new clone.\n try {\n await fs.mkdir(path.resolve(targetFolder, '.claude'), { recursive: true });\n await fs.symlink('../cella/skills', path.resolve(targetFolder, '.claude/skills'));\n } catch (err: unknown) {\n // Windows refuses a symlink without developer mode; the skills stay readable under cella/skills\n console.info(`\\n${warningMark} skipped .claude/skills: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/**\n * Removes all contents within a specified folder.\n * @param folderPath - The path of the folder to clean.\n */\nasync function removeFolderContents(folderPath: string): Promise<void> {\n // List all files in the folder. Skip silently if the folder doesn't exist —\n // the template may not include every optional folder (e.g. backend/drizzle).\n let files: string[];\n try {\n files = await fs.readdir(folderPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw err;\n }\n\n // `recursive: true` handles nested folders; `force: true` ignores races/missing entries.\n await Promise.all(files.map((file) => fs.rm(path.join(folderPath, file), { recursive: true, force: true })));\n}\n\n/**\n * Removes a specified file or folder.\n * @param pathToRemove - The path to the file or folder to remove.\n */\nasync function removeFileOrFolder(pathToRemove: string): Promise<void> {\n await fs.rm(pathToRemove, { recursive: true, force: true });\n}\n\n/**\n * Helper function to copy files if the source exists.\n * @param src - The source file path.\n * @param dest - The destination file path.\n */\nasync function copyFile(src: string, dest: string): Promise<void> {\n try {\n // Check if the source file exists\n await fs.access(src);\n\n // Ensure the destination directory exists\n await fs.mkdir(path.dirname(dest), { recursive: true });\n\n // Copy the file\n await fs.copyFile(src, dest);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.info(`\\n${warningMark} Source file \"${src}\" does not exist > Skip copy`);\n } else {\n throw err;\n }\n }\n}\n\n/**\n * Read the fork config template shipped inside the cloned Cella template\n * (`shared/config/config.template.ts`), interpolate project tokens, write the\n * result as `shared/config/config.default.ts` — replacing the original — and\n * delete the now-consumed template from the fork.\n */\nasync function applyPlaceholderConfig(\n targetFolder: string,\n projectName: string,\n displayName: string,\n appIndex: number,\n): Promise<void> {\n const src = path.resolve(targetFolder, PLACEHOLDER_CONFIG);\n const dest = path.resolve(targetFolder, './shared/config/config.default.ts');\n\n try {\n let content = await fs.readFile(src, 'utf8');\n content = content.replaceAll('__project_name__', displayName);\n content = content.replaceAll('__project_slug__', projectName);\n content = setDevAppIndex(content, appIndex);\n await fs.writeFile(dest, content, 'utf8');\n await fs.rm(src, { force: true });\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.info(`\\n${warningMark} Fork config template \"${src}\" not found > Skip`);\n } else {\n throw err;\n }\n }\n}\n\n/**\n * Remove the `forks` property, and a comment line directly above it, from the source of a sync\n * config. Returns the source unchanged when it has no such property.\n */\nexport function stripForks(source: string): string {\n // The closing bracket sits at the property's own indent, or on the same line for a short list\n return source.replace(\n /^(?:[ \\t]*\\/\\/[^\\n]*\\n)?([ \\t]*)forks:\\s*\\[(?:[^\\n]*|[\\s\\S]*?\\n\\1)\\],?[ \\t]*\\n(?:[ \\t]*\\n)?/m,\n '',\n );\n}\n\n/**\n * The template's sync config lists the repos the template itself syncs to. A new app has none,\n * and the sync CLI never merges this file, so the list is removed once here.\n */\nasync function removeTemplateForks(targetFolder: string): Promise<void> {\n const configPath = path.resolve(targetFolder, SYNC_CONFIG);\n try {\n const source = await fs.readFile(configPath, 'utf8');\n const stripped = stripForks(source);\n if (stripped !== source) await fs.writeFile(configPath, stripped, 'utf8');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.info(`\\n${warningMark} \"${SYNC_CONFIG}\" not found > Skip forks removal`);\n } else {\n throw err;\n }\n }\n}\n\n/**\n * Reset the upstream cella release identity so the new fork starts clean:\n * - root `package.json`: `name` → project slug, `version` → INITIAL_VERSION,\n * and blank out `license`/`repository`/`description`/`keywords`/`author`/`homepage`\n * (keys kept visible so the fork can fill in its own metadata)\n * - `.github/release-please-manifest.json` → `{ \".\": INITIAL_VERSION }`\n * - `.github/release-please-config.json`: `changelog-path` → root `CHANGELOG.md`\n * (cella tracks its own changelog in the template docs folder, which the fork\n * keeps as upstream reference; the fork's own releases write to a fresh root changelog)\n * - `CHANGELOG.md` → fresh stub\n */\nasync function resetReleaseState(targetFolder: string, projectName: string): Promise<void> {\n // Root package.json: rewrite only the top-level fields in place to avoid reformatting\n // the whole file. Set name/version to the fork's identity, then blank out the upstream\n // cella metadata (license, repository, description, keywords, author, homepage) while\n // keeping the keys visible so the fork can fill them in.\n const pkgPath = path.resolve(targetFolder, 'package.json');\n try {\n let pkg = await fs.readFile(pkgPath, 'utf8');\n pkg = pkg.replace(/^(\\s*\"name\":\\s*)\"[^\"]*\"/m, `$1\"${projectName}\"`);\n pkg = pkg.replace(/^(\\s*\"version\":\\s*)\"[^\"]*\"/m, `$1\"${INITIAL_VERSION}\"`);\n // Empty each string field, keeping the key so the fork sees the shape.\n for (const field of ['license', 'repository', 'description', 'author', 'homepage']) {\n pkg = pkg.replace(new RegExp(`^(\\\\s*\"${field}\":\\\\s*)\"[^\"]*\"`, 'm'), '$1\"\"');\n }\n // Collapse the multi-line keywords array to an empty one.\n pkg = pkg.replace(/^(\\s*\"keywords\":\\s*)\\[[^\\]]*\\]/m, '$1[]');\n await fs.writeFile(pkgPath, pkg, 'utf8');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.info(`\\n${warningMark} \"package.json\" not found > Skip version reset`);\n } else {\n throw err;\n }\n }\n\n // Point release-please at a root CHANGELOG.md for the fork. The upstream Cella\n // changelog stays wherever the template keeps it; the fork's own releases live at root.\n const configPath = path.resolve(targetFolder, '.github/release-please-config.json');\n try {\n const config = JSON.parse(await fs.readFile(configPath, 'utf8')) as {\n packages?: Record<string, Record<string, unknown>>;\n };\n config.packages ??= {};\n config.packages['.'] ??= {};\n config.packages['.']['changelog-path'] = 'CHANGELOG.md';\n await fs.writeFile(configPath, `${JSON.stringify(config, null, 2)}\\n`, 'utf8');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n console.info(`\\n${warningMark} \"release-please-config.json\" not found > Skip changelog path reset`);\n } else {\n throw err;\n }\n }\n\n // Reset the release-please manifest and changelog. `force: true` writes even if absent.\n await fs.writeFile(\n path.resolve(targetFolder, '.github/release-please-manifest.json'),\n `{\\n \".\": \"${INITIAL_VERSION}\"\\n}\\n`,\n 'utf8',\n );\n await fs.writeFile(path.resolve(targetFolder, 'CHANGELOG.md'), '# Changelog\\n', 'utf8');\n}\n","import fs from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\n\n/** Parse `github:owner/repo` or `owner/repo` into its owner and repo parts. */\nfunction parseGithubRepo(template: string): { owner: string; repo: string } {\n const [owner, repo] = template.replace(/^github:/, '').split('/');\n if (!owner || !repo) {\n throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);\n }\n return { owner, repo };\n}\n\n/**\n * Clones a GitHub template into `targetFolder` using isomorphic-git (pure JS).\n *\n * A shallow, single-branch clone over HTTPS — no `git` binary, no `child_process`,\n * so `create-cella` keeps a clean supply-chain profile (no shell access). Unlike a\n * raw tarball parse, isomorphic-git reconstructs the tree itself, so file modes and\n * long paths are always correct. The cloned `.git` history is discarded afterwards;\n * scaffolding re-initialises the repo with a fresh initial commit.\n *\n * @param template - `github:owner/repo` (or `owner/repo`).\n * @param ref - Branch or tag to check out (e.g. `main` or a release tag).\n * @param targetFolder - Directory to clone the template into.\n * @returns The exact upstream commit SHA the template was scaffolded from.\n */\nexport async function downloadGithubTemplate(template: string, ref: string, targetFolder: string): Promise<string> {\n const { owner, repo } = parseGithubRepo(template);\n const url = `https://github.com/${owner}/${repo}.git`;\n\n await git.clone({ fs, http, dir: targetFolder, url, ref, singleBranch: true, depth: 1 });\n\n // Capture the exact commit the scaffold is based on before discarding history. It is\n // stamped as a `Cella-Base:` trailer on the initial commit, where the sync CLI reads it\n // to bootstrap the first merge-base (the fork shares no git history with upstream).\n const baseSha = await git.resolveRef({ fs, dir: targetFolder, ref: 'HEAD' });\n\n // Drop the cloned history — the scaffold gets its own fresh initial commit.\n await rm(join(targetFolder, '.git'), { recursive: true, force: true });\n\n return baseSha;\n}\n","import { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport ignore from 'ignore';\n\n/**\n * Lists the files under `root` that git would track, without shelling out to git.\n *\n * Honors the root `.gitignore` (via the `ignore` package) and always skips `.git`\n * and `node_modules`. Used for the local-template dev flow (`--template ./local`)\n * so build output and local `.env` secrets aren't copied into the new project.\n *\n * Paths are returned relative to `root` using POSIX separators.\n */\nexport async function listTemplateFiles(root: string): Promise<string[]> {\n const ig = ignore().add(['.git', 'node_modules']);\n try {\n ig.add(await readFile(join(root, '.gitignore'), 'utf8'));\n } catch {\n // No .gitignore at the template root — only the defaults above apply.\n }\n\n const files: string[] = [];\n\n async function walk(relDir: string): Promise<void> {\n const entries = await readdir(relDir ? join(root, relDir) : root, { withFileTypes: true });\n for (const entry of entries) {\n const rel = relDir ? `${relDir}/${entry.name}` : entry.name;\n // `ignore` matches directory rules when the path ends with a slash.\n if (ig.ignores(entry.isDirectory() ? `${rel}/` : rel)) continue;\n if (entry.isDirectory()) await walk(rel);\n else if (entry.isFile()) files.push(rel);\n }\n }\n\n await walk('');\n return files;\n}\n","/**\n * Progress Tracker Utility\n *\n * Provides compact progress tracking for CLI operations.\n * Uses a single spinner that updates in place.\n */\n\nimport ora, { type Ora } from 'ora';\nimport pc from 'picocolors';\n\n/** Global reference to the currently active spinner */\nlet activeSpinner: Ora | null = null;\n\n/** Pause the active spinner (for interactive prompts) */\nexport function pauseSpinner(): void {\n if (activeSpinner) {\n activeSpinner.stop();\n }\n}\n\n/** Resume the active spinner after a prompt */\nexport function resumeSpinner(): void {\n if (activeSpinner) {\n activeSpinner.start();\n }\n}\n\nexport interface ProgressTracker {\n /** Update the current step (shown as spinner text) */\n step: (message: string) => void;\n /** Mark the tracker as complete with final message */\n done: (message: string) => void;\n /** Mark the tracker as failed with error message */\n fail: (message: string) => void;\n}\n\n/**\n * Creates a progress tracker for a multi-step operation.\n * Shows a single spinner that updates in place.\n *\n * @param title - The initial title for the spinner\n * @returns A ProgressTracker instance\n *\n * @example\n * const progress = createProgress('creating project');\n * progress.step('downloading template');\n * progress.step('installing dependencies');\n * progress.done('project created');\n */\nexport function createProgress(title: string, silent = false): ProgressTracker {\n const completedSteps: string[] = [];\n\n const spinner = ora({\n text: title,\n isSilent: silent,\n });\n\n activeSpinner = spinner;\n spinner.start();\n\n // Helper to log (respects silent mode)\n const log = (msg: string) => {\n if (!silent) console.info(msg);\n };\n\n return {\n step: (message: string) => {\n // Complete previous step with green check if there was one\n if (completedSteps.length > 0) {\n spinner.stop();\n log(`${pc.green('✓')} ${completedSteps[completedSteps.length - 1]}`);\n }\n completedSteps.push(message);\n spinner.text = message;\n spinner.start();\n },\n\n done: (message: string) => {\n // Complete the last step with green check\n if (completedSteps.length > 0) {\n spinner.stop();\n log(`${pc.green('✓')} ${completedSteps[completedSteps.length - 1]}`);\n } else {\n spinner.stop();\n }\n activeSpinner = null;\n if (message) {\n log('');\n log(`${pc.green('✓')} ${message}`);\n }\n },\n\n fail: (message: string) => {\n spinner.stop();\n activeSpinner = null;\n log(`${pc.red('✗')} ${pc.red(message)}`);\n },\n };\n}\n","import { existsSync } from 'node:fs';\nimport { cp, mkdir } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport pc from 'picocolors';\nimport { addRemote } from '#/add-remote';\nimport { TEMPLATE_URL } from '#/constants';\nimport { type CreateOptions, showSuccess } from '#/modules/cli';\nimport { cleanTemplate } from '#/utils/clean-template';\nimport { downloadGithubTemplate } from '#/utils/download-template';\nimport { gitAddAll, gitCommit, gitInit } from '#/utils/git';\nimport { listTemplateFiles } from '#/utils/list-template-files';\nimport { createProgress, pauseSpinner, resumeSpinner } from '#/utils/progress';\n\n/** Check if a path is a local directory */\nfunction isLocalPath(path: string): boolean {\n return path.startsWith('/') || path.startsWith('./') || path.startsWith('../');\n}\n\nexport async function create({\n projectName,\n targetFolder,\n packageManager,\n templateUrl,\n templateRef,\n appIndex,\n adminEmail,\n silent = false,\n}: CreateOptions): Promise<void> {\n // Save the original working directory\n const originalCwd = process.cwd();\n\n // Use custom template or default\n const template = templateUrl || TEMPLATE_URL;\n const isLocalTemplate = templateUrl && isLocalPath(templateUrl);\n\n const progress = createProgress('creating project', silent);\n\n try {\n // Create the target folder\n progress.step('creating project folder');\n await mkdir(targetFolder, { recursive: true });\n process.chdir(targetFolder);\n\n // Upstream commit the scaffold is based on (only known for remote templates). Stamped\n // as a trailer on the initial commit so the sync CLI can bootstrap the first merge-base.\n let baseSha: string | null = null;\n\n // Download or copy the template\n if (isLocalTemplate) {\n progress.step('copying local template');\n const sourcePath = resolve(originalCwd, templateUrl);\n\n // Check if target is inside source (would cause EINVAL). Use a path-boundary check\n // (not a string prefix) so siblings like `cella-try-app` next to `cella` aren't\n // misdetected as being inside the template.\n const rel = relative(sourcePath, targetFolder);\n const targetInsideTemplate = rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n if (targetInsideTemplate) {\n throw new Error(\n 'Cannot create project inside the template directory.\\n' +\n ` Run from outside: cd ~ && pnpm create @cellajs/cella ${projectName} --template ${templateUrl}`,\n );\n }\n\n // Copy only what git would track (respects .gitignore: no build output, no local .env secrets).\n const tracked = await listTemplateFiles(sourcePath);\n for (const rel of tracked) {\n const src = join(sourcePath, rel);\n if (!existsSync(src)) continue; // listed but deleted in the working tree\n const dest = join(targetFolder, rel);\n await mkdir(dirname(dest), { recursive: true });\n await cp(src, dest);\n }\n } else {\n // Pin to the chosen ref (release tag or commit SHA), else the default branch.\n const ref = templateRef ?? 'main';\n progress.step(`downloading cella template${templateRef ? ` (${templateRef})` : ''}`);\n baseSha = await downloadGithubTemplate(template, ref, targetFolder);\n }\n\n // Clean the template, generate configs\n progress.step('cleaning template');\n const displayName = projectName.replace(/[-_]/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n await cleanTemplate({ targetFolder, projectName, displayName, appIndex, adminEmail });\n\n // Initialize git repository. Git runs offline via isomorphic-git with an explicit\n // author, so it can't fail on missing user config — but if it fails for any other\n // reason (permissions, disk) the project files are already written and usable, so\n // warn and continue rather than aborting the whole scaffold.\n const gitFolderPath = join(targetFolder, '.git');\n if (!existsSync(gitFolderPath)) {\n try {\n progress.step('initializing git');\n await gitInit(targetFolder);\n await gitAddAll(targetFolder);\n // The `Cella-Base:` trailer records the upstream commit this scaffold snapshot was\n // taken from. The sync CLI reads it from the root commit to bootstrap the first\n // merge-base — the fork's fresh history otherwise shares no ancestor with upstream.\n const message = baseSha ? `Initial commit\\n\\nCella-Base: ${baseSha}` : 'Initial commit';\n await gitCommit(targetFolder, message);\n } catch (error) {\n if (!silent) {\n pauseSpinner();\n console.warn(`${pc.yellow('⚠')} skipped git init: ${error instanceof Error ? error.message : String(error)}`);\n resumeSpinner();\n }\n }\n }\n\n // Add upstream remote (best-effort: addRemote swallows its own failures via `silent`).\n progress.step('adding upstream remote');\n await addRemote({ targetFolder, silent: true });\n\n // Done\n progress.done(pc.bold(`created ${projectName}`));\n } catch (error) {\n progress.fail(error instanceof Error ? error.message : String(error));\n // Rethrow so callers (CLI entry, tests) see the real failure. The CLI entry\n // turns this into a non-zero exit; swallowing it here with process.exit hid\n // the underlying error from CI and vitest.\n throw error;\n }\n\n // Check if the working directory needs to be changed\n const needsCd = originalCwd !== targetFolder;\n const relativePath = relative(originalCwd, targetFolder);\n\n // Display final success message\n showSuccess(\n projectName,\n targetFolder,\n relativePath,\n needsCd,\n packageManager,\n appIndex,\n adminEmail ?? `admin@${projectName}.example.com`,\n );\n}\n","import { connect } from 'node:net';\n\nconst SERVICE_PORTS = 7;\n\n/** Every local port an app number takes: the frontend, its service block, and the dev and test databases. */\nconst appPorts = (appIndex: number): number[] => [\n 3000 + appIndex,\n ...Array.from({ length: SERVICE_PORTS }, (_, i) => 4000 + appIndex * 10 + i),\n 5432 + appIndex * 10,\n 5434 + appIndex * 10,\n];\n\n/** Whether something on this machine accepts a connection on the port. */\nconst isListening = (port: number): Promise<boolean> =>\n new Promise((resolve) => {\n const socket = connect({ port, host: '127.0.0.1', timeout: 300 });\n const finish = (listening: boolean) => {\n socket.destroy();\n resolve(listening);\n };\n socket.once('connect', () => finish(true));\n socket.once('timeout', () => finish(false));\n socket.once('error', () => finish(false));\n });\n\n/** The ports of an app number that are already taken, lowest first. */\nexport async function findBusyPorts(appIndex: number): Promise<number[]> {\n const ports = appPorts(appIndex);\n const listening = await Promise.all(ports.map(isListening));\n return ports.filter((_, i) => listening[i]);\n}\n","/**\n * Fetch lightweight metadata about the cella template so the scaffolder can offer\n * \"latest release\" vs \"latest commit\" as a starting point.\n *\n * The release tag is read from the template's git tags, over the transport the clone uses, so\n * it does not depend on the GitHub API and its limit for callers without a token. Dates and the\n * commit subject come from that API. Every helper fails soft; the caller falls back to the\n * default branch when no release is known.\n */\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport { TEMPLATE_GIT_URL, TEMPLATE_REPOSITORY } from '#/constants';\n\nconst TEMPLATE_METADATA_API_BASE = `https://api.github.com/repos/${TEMPLATE_REPOSITORY}`;\n\n/** Format an ISO timestamp as a locale-independent YYYY-MM-DD date. */\nfunction toDate(iso?: string): string {\n return iso ? iso.slice(0, 10) : 'unknown';\n}\n\nconst GITHUB_HEADERS = { Accept: 'application/vnd.github+json' } as const;\n\nexport interface ReleaseInfo {\n /** Release tag, e.g. '0.18.1' */\n tag: string;\n /** Publication date, YYYY-MM-DD; absent when the GitHub API did not answer */\n date?: string;\n}\n\nexport interface CommitInfo {\n /** Full commit SHA (used for a reproducible checkout) */\n sha: string;\n /** Short 7-char SHA for display */\n shortSha: string;\n /** First line of the commit message */\n message: string;\n /** Commit date, YYYY-MM-DD */\n date: string;\n}\n\n/**\n * Pick the latest template release from tag names: the highest plain version, with or without\n * the `v` prefix. Tags of another series (`create-cella-0.2.3`, `archive/pre-release`) and\n * pre-releases are no template release.\n */\nexport function pickLatestReleaseTag(tags: string[]): string | null {\n let latest: { tag: string; version: number[] } | null = null;\n for (const tag of tags) {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(tag);\n if (!match) continue;\n const version = match.slice(1).map(Number);\n if (!latest || isNewer(version, latest.version)) latest = { tag, version };\n }\n return latest?.tag ?? null;\n}\n\n/** Whether version `a` is higher than `b`, both as [major, minor, patch]. */\nfunction isNewer(a: number[], b: number[]): boolean {\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return a[i] > b[i];\n }\n return false;\n}\n\n/** Fetch the latest template release: its tag from the git tags, its date from the GitHub API. */\nexport async function fetchLatestRelease(): Promise<ReleaseInfo | null> {\n let tag: string | null;\n try {\n const refs = await git.listServerRefs({ http, url: TEMPLATE_GIT_URL, prefix: 'refs/tags/' });\n tag = pickLatestReleaseTag(refs.map(({ ref }) => ref.slice('refs/tags/'.length)));\n } catch {\n return null;\n }\n if (!tag) return null;\n\n return { tag, date: await fetchReleaseDate(tag) };\n}\n\n/** Publication date of a release, undefined when the GitHub API does not answer. */\nasync function fetchReleaseDate(tag: string): Promise<string | undefined> {\n try {\n const response = await fetch(`${TEMPLATE_METADATA_API_BASE}/releases/tags/${tag}`, { headers: GITHUB_HEADERS });\n if (!response.ok) return undefined;\n\n const release = (await response.json()) as { published_at?: string };\n return release.published_at ? toDate(release.published_at) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Fetch the latest commit on a branch (defaults to 'main'). */\nexport async function fetchLatestCommit(branch = 'main'): Promise<CommitInfo | null> {\n const apiUrl = `${TEMPLATE_METADATA_API_BASE}/commits/${branch}`;\n\n try {\n const response = await fetch(apiUrl, { headers: GITHUB_HEADERS });\n if (!response.ok) return null;\n\n const data = (await response.json()) as {\n sha?: string;\n commit?: { message?: string; author?: { date?: string } };\n };\n if (!data.sha) return null;\n\n const message = (data.commit?.message ?? '').split('\\n')[0];\n return { sha: data.sha, shortSha: data.sha.slice(0, 7), message, date: toDate(data.commit?.author?.date) };\n } catch {\n return null;\n }\n}\n","import { readdir } from 'node:fs/promises';\n\n/**\n * Checks if a directory is empty or only contains a .git directory.\n *\n * @param path - The path of the directory to check.\n * @returns Resolves to true if the directory is empty or contains only a .git folder, false otherwise.\n * @throws Throws an error if the path is not a directory or if there's an issue reading the directory.\n */\nexport async function isEmptyDirectory(path: string): Promise<boolean> {\n const files = await readdir(path);\n\n // Check if directory is empty or contains only the .git directory\n return files.length === 0 || (files.length === 1 && files[0] === '.git');\n}\n","#!/usr/bin/env tsx\n\nimport { existsSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport { input, select } from '@inquirer/prompts';\nimport pc from 'picocolors';\nimport { TEMPLATE_URL } from '#/constants';\nimport { create } from '#/create';\nimport { type CreateOptions, cli, confirmChoice, showWelcome } from '#/modules/cli';\nimport { findBusyPorts } from '#/utils/busy-ports';\nimport { detectUsedPorts, findNextAppIndex, isAppIndex } from '#/utils/detect-used-ports';\nimport { fetchLatestCommit, fetchLatestRelease } from '#/utils/fetch-template-metadata';\nimport { isEmail } from '#/utils/is-email';\nimport { isEmptyDirectory } from '#/utils/is-empty-directory';\nimport { validateProjectName } from '#/utils/validate-project-name';\n\nasync function main(): Promise<void> {\n // Display CLI welcome banner\n showWelcome();\n\n // Shared theme to clear prompts after answering\n const promptTheme = { prefix: '', style: { answer: (text: string) => text } };\n const promptContext = { clearPromptOnDone: true };\n\n // Choose which template snapshot to scaffold from: a stable release or the\n // latest commit. Skipped when a custom --template is provided (ref doesn't apply).\n const templateRef = cli.options.template ? undefined : await promptTemplateRef(promptTheme, promptContext);\n\n // Prompt for project name if not provided\n if (!cli.directory) {\n cli.directory = await input(\n {\n message: 'Enter your project name',\n default: 'my-cella-app',\n theme: promptTheme,\n validate: (name) => {\n const validation = validateProjectName(basename(resolve(name)));\n return validation.valid ? true : `Invalid project name: ${validation.problems?.[0] ?? 'unknown error'}`;\n },\n },\n promptContext,\n );\n }\n\n const targetFolder = resolve(cli.directory);\n const projectName = basename(targetFolder)?.toLowerCase() || 'project';\n\n // Check if the target folder exists and is not empty\n if (existsSync(targetFolder) && !(await isEmptyDirectory(targetFolder))) {\n const dirName = cli.directory === '.' ? 'Current directory' : `Target directory \"${targetFolder}\"`;\n const message = `${dirName} is not empty. Please choose how you would like to proceed:`;\n\n const action = await select(\n {\n message,\n theme: promptTheme,\n choices: [\n { name: 'Cancel and exit', value: 'cancel' },\n { name: 'Remove existing files and continue', value: 'remove' },\n ],\n },\n promptContext,\n );\n\n if (action === 'cancel') {\n process.exit(1);\n }\n\n // Wipe the folder so the template clone starts from a clean slate. Leaving stale\n // files behind makes the git checkout fail with conflicts on overlapping paths.\n if (action === 'remove') {\n await rm(targetFolder, { recursive: true, force: true });\n }\n }\n\n // Scan sibling directories and prompt for the app index\n const appIndex = cli.options.appIndex ?? (await promptAppIndex(targetFolder, promptTheme, promptContext));\n confirmChoice('App index', formatAppIndex(appIndex));\n const busyPorts = await findBusyPorts(appIndex);\n if (busyPorts.length > 0) {\n console.info(\n `${pc.yellow('⚠')} In use on this machine: ${busyPorts.join(', ')}. Stop what holds them before pnpm docker and pnpm dev.`,\n );\n console.info();\n }\n\n // Prompt for admin email. Default uses the reserved `example.com` domain (RFC 2606) so the\n // seed address can never resolve or route real mail — it's a placeholder, not a real inbox.\n const adminEmail =\n cli.options.adminEmail ??\n (await input(\n {\n message: 'Admin email for initial seed user',\n default: 'admin@example.com',\n theme: promptTheme,\n validate: (email) => (isEmail(email) ? true : 'Enter an address such as admin@example.com'),\n },\n promptContext,\n ));\n confirmChoice('Admin email', adminEmail);\n\n // Proceed with the project creation\n const createOptions: CreateOptions = {\n projectName,\n targetFolder,\n packageManager: cli.packageManager,\n templateUrl: cli.options.template,\n templateRef,\n appIndex,\n adminEmail,\n };\n\n await create(createOptions);\n}\n\nmain().catch((error) => {\n console.error(error);\n process.exit(1);\n});\n\n/**\n * Show a short intro with the two starting points (latest release and latest\n * commit, each with its date) and let the user choose which template snapshot to\n * scaffold from. Returns the template ref to check out (release tag or `main`), or\n * undefined to use the default branch (when metadata is unavailable).\n */\nasync function promptTemplateRef(theme: object, context: object): Promise<string | undefined> {\n const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);\n\n // One-sentence intro followed by the data points that are known.\n console.info(pc.dim('This create CLI allows you to get started with cella quickly.'));\n console.info();\n\n if (release)\n console.info(` Latest release: ${release.tag}${release.date ? ` ${pc.dim(`· ${release.date}`)}` : ''}`);\n if (commit) {\n console.info(` Latest commit: ${commit.shortSha} ${pc.dim(`· ${commit.message} · ${commit.date}`)}`);\n // Clickable link to the exact commit on GitHub, in grey below the summary line.\n const repo = TEMPLATE_URL.replace('github:', '');\n console.info(` ${pc.gray(`https://github.com/${repo}/commit/${commit.sha}`)}`);\n }\n if (release || commit) console.info();\n\n // No release known (offline, or the template's tags did not answer): the app starts from the\n // default branch, and the output says so.\n if (!release) {\n console.info(`${pc.yellow('⚠')} Latest release not found · using the latest commit on main`);\n console.info();\n return commit ? 'main' : undefined;\n }\n\n // No commit to offer, or no TTY to render the select on (CI, piped stdin): take the latest\n // release, the stable and reproducible starting point.\n if (!commit || !process.stdin.isTTY) {\n confirmChoice('Latest release', release.tag);\n return release.tag;\n }\n\n const choice = await select(\n {\n message: 'Choose which cella version to start from:',\n theme,\n choices: [\n { name: 'Latest release', value: 'release' },\n { name: 'Latest commit', value: 'commit' },\n ],\n },\n context,\n );\n\n // The prompt clears itself on done, so keep the choice visible with a checkmark.\n if (choice === 'release') {\n confirmChoice('Latest release', release.tag);\n return release.tag;\n }\n // \"Latest commit\" is the tip of main; check out the branch (shallow clones can't\n // reliably fetch an arbitrary SHA over GitHub's smart-HTTP protocol).\n confirmChoice('Latest commit', commit.shortSha);\n return 'main';\n}\n\n/** Format an app index as a port overview string, e.g. \"1 → :3001 / :4010 / :5442\" */\nfunction formatAppIndex(i: number, suffix = ''): string {\n return `${i} → :${3000 + i} / :${4000 + i * 10} / :${5432 + i * 10}${suffix}`;\n}\n\n/** Scan sibling apps and prompt the user to pick an app index */\nasync function promptAppIndex(targetFolder: string, theme: object, context: object): Promise<number> {\n const usedPorts = await detectUsedPorts(targetFolder);\n const presets = [1, 2, 3];\n const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)] as const)));\n const isBusy = (i: number) => (busy.get(i)?.length ?? 0) > 0;\n const suggested = findNextAppIndex(usedPorts, isBusy);\n const label = (i: number, note = '') => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);\n\n // Fold a compact hint into the prompt message itself so it's wiped by clearPromptOnDone\n // once an index is chosen — no leftover \"Detected forks\" trail. Override the default\n // message style (which bolds everything) so only the \"App index\" title is bold.\n let message = `${pc.bold('App index')} ${pc.dim('· to avoid port conflicts with other apps on this machine')}`;\n if (usedPorts.length > 0) {\n const count = usedPorts.length;\n message += pc.dim(`\\nDetected ${count} sibling app${count === 1 ? '' : 's'} · suggested index ${suggested}`);\n }\n const portTheme = {\n ...(theme as Record<string, unknown>),\n style: { ...((theme as { style?: object }).style ?? {}), message: (text: string) => text },\n };\n\n // Presets exclude 0 (always offered as the explicit default below) and the suggested\n // value (offered first) to avoid duplicate choices.\n const choice = await select(\n {\n message,\n theme: portTheme,\n choices: [\n ...(suggested > 0 ? [{ name: formatAppIndex(suggested, ' (suggested)'), value: suggested }] : []),\n { name: label(0, ' (default)'), value: 0 },\n ...presets.filter((i) => i !== suggested).map((i) => ({ name: label(i), value: i })),\n { name: 'Custom index', value: -1 },\n ],\n },\n context,\n );\n\n if (choice !== -1) return choice;\n\n const custom = await input(\n {\n message: 'Enter custom index (0-9, not 4)',\n default: String(suggested),\n theme,\n validate: (val) => (isAppIndex(Number(val)) ? true : 'Must be a whole number from 0 to 9, not 4'),\n },\n context,\n );\n return Number(custom);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;ACIA,MAAa,OAAO;;AAGpB,MAAa,UAAU,IAAI,OAAO,EAAE;;AAGpC,MAAa,eAAe;;AAG5B,MAAa,sBAAsB;;AAGnC,MAAa,mBAAmB,sBAAsB,oBAAoB;;AAG1E,MAAa,cAAc;;AAG3B,MAAa,mBAAmB;;;;;AAMhC,MAAa,oBAAoB;;AAGjC,MAAa,cAAsBA;AACnC,MAAa,UAAkBC;AAC/B,MAAa,UAAkBC;AAE/B,SAAgB,gBAAwB;CACtC,MAAM,WAAW,KAAK,KAA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YAAY,IAAI;CAKjH,IAAI,UAAU,GAAG,GAAG,KAAK,WAAW,EAAE,GAAG,GAAG,IAAI,2DAA2D;CAC3G,IAAI,UAAU,SAAS,GAAG;EACxB,MAAM,QAAQ,UAAU;EACxB,WAAW,GAAG,IAAI,cAAc,MAAM,cAAc,UAAU,IAAI,KAAK,IAAI,qBAAqB,WAAW;CAC7G;CACA,MAAM,YAAY;EAChB,GAAI;EACJ,OAAO;GAAE,GAAK,MAA6B,SAAS,CAAC;GAAI,UAAU,SAAiB;EAAK;CAC3F;CAIA,MAAM,SAAS,MAAM,OACnB;EACE;EACA,OAAO;EACP,SAAS;GACP,GAAI,YAAY,IAAI,CAAC;IAAE,MAAM,eAAe,WAAW,cAAc;IAAG,OAAO;GAAU,CAAC,IAAI,CAAC;GAC/F;IAAE,MAAM,MAAM,GAAG,YAAY;IAAG,OAAO;GAAE;GACzC,GAAG,QAAQ,QAAQ,MAAM,MAAM,SAAS,CAAC,CAAC,KAAK,OAAO;IAAE,MAAM,MAAM,CAAC;IAAG,OAAO;GAAE,EAAE;GACnF;IAAE,MAAM;IAAgB,OAAO;GAAG;EACpC;CACF,GACA,OACF;CAEA,IAAI,WAAW,IAAI,OAAO;CAE1B,MAAM,SAAS,MAAM,MACnB;EACE,SAAS;EACT,SAAS,OAAO,SAAS;EACzB;EACA,WAAW,QAAS,WAAW,OAAO,GAAG,CAAC,IAAI,OAAO;CACvD,GACA,OACF;CACA,OAAO,OAAO,MAAM;AACtB"}
1
+ {"version":3,"file":"index.js","names":["packageJson.version","packageJson.description","packageJson.homepage","fs","fs"],"sources":["../src/colors.ts","../src/dev-ports.ts","../package.json","../src/display.ts","../src/template.ts","../src/answers.ts","../src/app-files.ts","../src/app-repo.ts","../src/create-cella-cli.ts"],"sourcesContent":["import { styleText } from 'node:util';\n\ntype ColorStyle = 'bold' | 'cyan' | 'dim' | 'gray' | 'green' | 'red' | 'yellow';\n\nfunction colorsEnabled(): boolean {\n // biome-ignore lint/style/noProcessEnv: the color switches are the only environment this package reads.\n const { NO_COLOR, FORCE_COLOR } = process.env;\n if (NO_COLOR !== undefined) return false;\n if (FORCE_COLOR !== undefined) return FORCE_COLOR !== '0' && FORCE_COLOR !== 'false';\n return !!process.stdout.isTTY;\n}\n\nfunction applyStyle(style: ColorStyle, text: string): string {\n if (!colorsEnabled()) return text;\n return styleText(style, text, { validateStream: false });\n}\n\nconst pc = {\n bold: (text: string) => applyStyle('bold', text),\n cyan: (text: string) => applyStyle('cyan', text),\n dim: (text: string) => applyStyle('dim', text),\n gray: (text: string) => applyStyle('gray', text),\n green: (text: string) => applyStyle('green', text),\n red: (text: string) => applyStyle('red', text),\n yellow: (text: string) => applyStyle('yellow', text),\n};\n\nexport default pc;\n","import { readdir, readFile } from 'node:fs/promises';\nimport { connect } from 'node:net';\nimport { dirname, join } from 'node:path';\n\n/**\n * The local ports the template's dev stack takes for an app index, as its config shifts them: the index is added to\n * the frontend's and Drizzle Studio's, ten times the index to the seven services' and the dev and test databases'.\n */\nexport const appPorts = (index: number) => ({\n frontend: 3000 + index,\n drizzleStudio: 3983 + index,\n services: Array.from({ length: 7 }, (_, i) => 4000 + index * 10 + i),\n databases: [5432 + index * 10, 5434 + index * 10],\n});\n\n/** Index 4 is never offered: its internal listener would sit on 4045, which fetch refuses. */\nexport const isAppIndex = (index: number): boolean =>\n Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;\n\n/** The rule `isAppIndex` checks, worded for a refusal. */\nexport const appIndexRule = 'a whole number from 0 to 9, not 4';\n\ninterface SiblingApp {\n project: string;\n frontend: number;\n backend: number;\n}\n\n/**\n * The dev ports of the cella apps beside `targetFolder`, found by their `shared/config/config.development.ts`. The\n * frontend port sits in that file's `origin`, or `frontendUrl` in older apps; the backend port in\n * `services.backend.port` of `config.default.ts`, or `devPorts` in either file before that, or `backendUrl` on a port\n * of its own before that; `devAppIndex` in the default config moves whatever ports the files carry.\n */\nexport async function detectUsedPorts(targetFolder: string): Promise<SiblingApp[]> {\n const parentDir = dirname(targetFolder);\n const siblings = await readdir(parentDir).catch(() => []);\n const used: SiblingApp[] = [];\n\n for (const name of siblings) {\n const configDir = join(parentDir, name, 'shared/config');\n const development = await readFile(join(configDir, 'config.development.ts'), 'utf8').catch(() => null);\n const frontendMatch = development?.match(/(?:origin|frontendUrl):\\s*'http:\\/\\/localhost:(\\d+)/);\n if (!development || !frontendMatch) continue;\n const defaults = await readFile(join(configDir, 'config.default.ts'), 'utf8').catch(() => '');\n const frontend = Number(frontendMatch[1]);\n const index = Number(defaults.match(/devAppIndex:\\s*(\\d+)/)?.[1] ?? 0);\n const servicePattern = /backend:\\s*\\{[^}]*?\\bport:\\s*(\\d+)/;\n const apiPattern = /devPorts:\\s*\\{[^}]*?\\bapi:\\s*(\\d+)/;\n const portMatch =\n defaults.match(servicePattern) ??\n development.match(apiPattern) ??\n defaults.match(apiPattern) ??\n development.match(/backendUrl:\\s*'http:\\/\\/localhost:(\\d+)'/);\n // The oldest apps carry no backend port at all: assume the paired one\n const backend = portMatch ? Number(portMatch[1]) : frontend + 1000;\n used.push({ project: name, frontend: frontend + index, backend: backend + index * 10 });\n }\n\n return used;\n}\n\n/** The first app index whose frontend port and service block no sibling uses and that `isBusy` leaves free, else 0. */\nexport function findNextAppIndex(siblings: SiblingApp[], isBusy: (index: number) => boolean = () => false): number {\n for (let index = 0; index <= 9; index += 1) {\n if (!isAppIndex(index) || isBusy(index)) continue;\n const { frontend, services } = appPorts(index);\n const api = services[0];\n const taken = siblings.some((p) => p.frontend === frontend || (p.backend >= api && p.backend < api + 10));\n if (!taken) return index;\n }\n return 0;\n}\n\n/** Whether something on this machine accepts a connection on the port. */\nconst isListening = (port: number): Promise<boolean> =>\n new Promise((resolve) => {\n const socket = connect({ port, host: '127.0.0.1', timeout: 300 });\n const finish = (listening: boolean) => {\n socket.destroy();\n resolve(listening);\n };\n socket.once('connect', () => finish(true));\n socket.once('timeout', () => finish(false));\n socket.once('error', () => finish(false));\n });\n\n/** The ports of an app index that are already taken, lowest first. */\nexport async function findBusyPorts(index: number): Promise<number[]> {\n const ports = Object.values(appPorts(index)).flat();\n const listening = await Promise.all(ports.map(isListening));\n return ports.filter((_, i) => listening[i]);\n}\n","","import { relative } from 'node:path';\nimport packageJson from '../package.json' with { type: 'json' };\nimport type { Answers } from './answers';\nimport pc from './colors';\nimport { appPorts } from './dev-ports';\n\nexport const cliName = 'create cella';\nexport const cliVersion = packageJson.version;\n\nconst divider = '─'.repeat(60);\nconst checkMark = pc.green('✓');\n\nexport function showBanner(): void {\n console.info();\n console.info(pc.cyan(' _ _ '));\n console.info(pc.cyan('▒▓█████▓▒ ___ ___| | | __ _ '));\n console.info(pc.cyan('▒▓█ █▓▒ / __/ _ \\\\ | |/ _` | '));\n console.info(pc.cyan('▒▓█ █▓▒ | (_| __/ | | (_| | '));\n console.info(pc.cyan('▒▓█████▓▒ \\\\___\\\\___|_|_|\\\\__,_| '));\n console.info();\n console.info(pc.dim(packageJson.description));\n console.info();\n const left = `⧈ ${cliName}`;\n const right = packageJson.homepage;\n // Padding counts the visible characters only, not the ANSI codes\n const padding = Math.max(1, divider.length - `${left} · ${cliVersion}${right}`.length);\n console.info(`${pc.cyan(left)} ${pc.dim(`· ${cliVersion}`)}${' '.repeat(padding)}${pc.cyan(right)}`);\n console.info(divider);\n}\n\n/** Keep the answer of a prompt that clears itself on screen. */\nexport function confirmChoice(label: string, value: string): void {\n console.info(`${checkMark} ${label} · ${value}`);\n console.info();\n}\n\nlet stepText: string | undefined;\nlet timer: ReturnType<typeof setInterval> | undefined;\n\n/** Animate the running step on a terminal only: a log gets the finished steps. Stdin stays untouched, so ctrl-c reaches the run. */\nfunction spin(): void {\n if (!stepText || !process.stdout.isTTY) return;\n const frames = ['-', '\\\\', '|', '/'];\n let frame = 0;\n const render = () => process.stdout.write(`\\r${pc.cyan(frames[frame++ % frames.length])} ${stepText}`);\n render();\n timer = setInterval(render, 80);\n}\n\nfunction clearSpinner(): void {\n if (!timer) return;\n clearInterval(timer);\n timer = undefined;\n process.stdout.write('\\r\\x1b[2K');\n}\n\n/** Mark the running step done and start `text`; without text the steps end. */\nexport function step(text?: string): void {\n clearSpinner();\n if (stepText) console.info(`${checkMark} ${stepText}`);\n stepText = text;\n spin();\n}\n\n/** End the steps without marking the running one done. */\nexport function stopSpinner(): void {\n clearSpinner();\n stepText = undefined;\n}\n\n/** Print a warning above the running step. */\nexport function warn(message: string): void {\n clearSpinner();\n console.warn(`${pc.yellow('⚠')} ${message}`);\n spin();\n}\n\nexport function showNextSteps({ name, targetFolder, appIndex, adminEmail }: Answers): void {\n const path = relative(process.cwd(), targetFolder);\n const and = pc.dim('&&');\n\n console.info();\n console.info(`${checkMark} ${pc.bold(`created ${name}`)}`);\n console.info();\n console.info(pc.bold('Next steps'));\n console.info(divider);\n console.info();\n if (path) console.info(`${pc.dim('$')} cd ${pc.cyan(path)}`);\n console.info(`${pc.dim('$')} ${pc.cyan('pnpm install')}`);\n console.info(`${pc.dim('$')} ${pc.cyan('pnpm generate')}`);\n console.info(`${pc.dim('$')} ${pc.cyan('pnpm docker')} ${and} ${pc.cyan('pnpm seed')} ${and} ${pc.cyan('pnpm dev')}`);\n console.info();\n console.info(\n `${pc.gray('Then open')} ${pc.cyan(`http://localhost:${appPorts(appIndex).frontend}`)} ${pc.gray('and sign in as')} ${pc.cyan(adminEmail)}${pc.gray(': the magic link is printed in the pnpm dev output.')}`,\n );\n console.info();\n // Relative to the new app, so the terminal links the app's README, not this package's\n console.info(\n `${pc.gray('To get started building, please read:')} ${pc.cyan(path ? `${path}/README.md` : 'README.md')}`,\n );\n console.info();\n console.info(`🥳 enjoy building ${pc.green(name)} with cella!`);\n console.info();\n}\n","import fs, { existsSync } from 'node:fs';\nimport { cp, mkdir, rm } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport type { Answers } from './answers';\nimport { step } from './display';\n\nexport const templateRepository = 'cellajs/cella';\n\n/** The HTTPS git URL of `github:owner/repo` or `owner/repo`: reading a public repository needs no SSH key. */\nexport function githubGitUrl(template: string): string {\n const [owner, repo] = template.replace(/^github:/, '').split('/');\n if (!owner || !repo) throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);\n return `https://github.com/${owner}/${repo}.git`;\n}\n\n/** A version, with or without the `v` prefix; `create-cella-0.2.3` and `archive/pre-release` start with a name. */\nconst releaseTagPattern = /^v?\\d[\\w.+-]*$/;\n\n/** The highest release tag, in git's `version:refname` order as `pnpm cella upgrade` sorts them, or null. */\nexport function pickLatestReleaseTag(tags: string[]): string | null {\n const releases = tags.filter((tag) => releaseTagPattern.test(tag));\n return releases.sort((a, b) => a.localeCompare(b, 'en', { numeric: true })).at(-1) ?? null;\n}\n\n/**\n * The latest template release: its tag from the git tags, over the transport the clone uses, so the GitHub API limit\n * for callers without a token cannot hide it; its date (YYYY-MM-DD) from that API when it answers. Null offline.\n */\nexport async function fetchLatestRelease(): Promise<{ tag: string; date?: string } | null> {\n const refs = await git\n .listServerRefs({ http, url: githubGitUrl(templateRepository), prefix: 'refs/tags/' })\n .catch(() => []);\n const tag = pickLatestReleaseTag(refs.map(({ ref }) => ref.slice('refs/tags/'.length)));\n if (!tag) return null;\n\n const release = await fetchGithub<{ published_at?: string }>(`releases/tags/${tag}`);\n return { tag, date: release?.published_at?.slice(0, 10) };\n}\n\n/** The latest commit on the template's main branch, with its subject and date (YYYY-MM-DD), or null. */\nexport async function fetchLatestCommit(): Promise<{ sha: string; message: string; date: string } | null> {\n const data = await fetchGithub<{ sha?: string; commit?: { message?: string; author?: { date?: string } } }>(\n 'commits/main',\n );\n if (!data?.sha) return null;\n const message = (data.commit?.message ?? '').split('\\n')[0];\n return { sha: data.sha, message, date: data.commit?.author?.date?.slice(0, 10) ?? 'unknown' };\n}\n\n/** A GitHub API answer about the template, or null: callers without a token have a low limit. */\nasync function fetchGithub<T>(path: string): Promise<T | null> {\n try {\n const url = `https://api.github.com/repos/${templateRepository}/${path}`;\n const response = await fetch(url, { headers: { Accept: 'application/vnd.github+json' } });\n return response.ok ? ((await response.json()) as T) : null;\n } catch {\n return null;\n }\n}\n\nconst isLocalPath = (path: string): boolean => path.startsWith('/') || path.startsWith('./') || path.startsWith('../');\n\n/**\n * Put the template's files in `targetFolder`: a shallow clone of a GitHub template, or the tracked files of a local\n * checkout from its working tree, so build output and local `.env` secrets stay behind.\n * @returns The template commit the files come from; null when isomorphic-git cannot resolve a local checkout's `HEAD`,\n * as in a linked worktree.\n */\nexport async function getTemplate({ template, templateRef, targetFolder, name }: Answers): Promise<string | null> {\n if (!template || !isLocalPath(template)) {\n step(`downloading cella template${templateRef ? ` (${templateRef})` : ''}`);\n const url = githubGitUrl(template ?? templateRepository);\n // Isomorphic-git needs no git binary and no shell; the clone's history goes, since the app starts its own\n await git.clone({ fs, http, dir: targetFolder, url, ref: templateRef ?? 'main', singleBranch: true, depth: 1 });\n const baseCommit = await git.resolveRef({ fs, dir: targetFolder, ref: 'HEAD' });\n await rm(join(targetFolder, '.git'), { recursive: true, force: true });\n return baseCommit;\n }\n\n step('copying local template');\n const source = resolve(template);\n const rel = relative(source, targetFolder);\n if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) {\n throw new Error(\n 'Cannot create the app inside the template directory.\\n' +\n ` Run from outside: cd ~ && pnpm create @cellajs/cella ${name} --template ${template}`,\n );\n }\n\n const files = await git.listFiles({ fs, dir: source });\n if (files.length === 0) throw new Error(`${source} is no git checkout: a local template must be one.`);\n for (const file of files) {\n const from = join(source, file);\n // Tracked, but deleted in the working tree\n if (!existsSync(from)) continue;\n const to = join(targetFolder, file);\n await mkdir(dirname(to), { recursive: true });\n await cp(from, to);\n }\n return git.resolveRef({ fs, dir: source, ref: 'HEAD' }).catch(() => null);\n}\n","import { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { basename, resolve } from 'node:path';\nimport { input, select } from '@inquirer/prompts';\nimport pc from './colors';\nimport { appIndexRule, appPorts, detectUsedPorts, findBusyPorts, findNextAppIndex, isAppIndex } from './dev-ports';\nimport { confirmChoice, warn } from './display';\nimport { fetchLatestCommit, fetchLatestRelease, templateRepository } from './template';\n\n/** The template's config refuses any other `slug` at its first load (cella `shared/src/config-builder/app-config.ts`). */\nexport const isAppSlug = (name: string): boolean =>\n /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) && name.replaceAll('-', '').length >= 4;\n\n/** The rule `isAppSlug` checks, worded for a refusal. */\nexport const appSlugRule =\n 'the name becomes the app slug: lowercase letters and digits, starting with a letter, single hyphens between parts and at least 4 characters besides hyphens, such as my-app';\n\n/** A plain shape check: the value lands on one line of the app's `.env` and is the seed user's sign-in address. */\nexport const isEmail = (value: string): boolean => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value);\n\n/** What the command line answered already. */\nexport interface Flags {\n directory?: string;\n /** A local git checkout or `github:owner/repo`. */\n template?: string;\n appIndex?: number;\n adminEmail?: string;\n}\n\nexport interface Answers {\n template?: string;\n /** The release tag or branch to clone; the default branch when absent, and unused for a local template. */\n templateRef?: string;\n targetFolder: string;\n /** The app's slug: the name of its folder. */\n name: string;\n appIndex: number;\n adminEmail: string;\n}\n\n// A prompt clears itself once answered, and `confirmChoice` keeps the answer on screen\nconst theme = { prefix: '', style: { answer: (text: string) => text } };\nconst context = { clearPromptOnDone: true };\n\n/** Ask what the flags leave open, and refuse a folder that is not empty. */\nexport async function askAnswers({ directory, template, ...flags }: Flags): Promise<Answers> {\n // A custom template is taken as it is\n const templateRef = template ? undefined : await askTemplateRef();\n\n const targetFolder = resolve(\n directory ??\n (await input(\n {\n message: 'Enter your app name',\n default: 'my-cella-app',\n theme,\n validate: (name) => (isAppSlug(basename(resolve(name))) ? true : `Invalid app name: ${appSlugRule}`),\n },\n context,\n )),\n );\n if (existsSync(targetFolder) && (await readdir(targetFolder)).length > 0) {\n throw new Error(`${targetFolder} is not empty: choose a new folder, or empty this one first.`);\n }\n\n const appIndex = flags.appIndex ?? (await askAppIndex(targetFolder));\n confirmChoice('App index', formatAppIndex(appIndex));\n const busyPorts = await findBusyPorts(appIndex);\n if (busyPorts.length > 0) {\n warn(`In use on this machine: ${busyPorts.join(', ')}. Stop what holds them before pnpm docker and pnpm dev.`);\n console.info();\n }\n\n // The reserved example.com domain (RFC 2606) can never route real mail\n const adminEmail =\n flags.adminEmail ??\n (await input(\n {\n message: 'Admin email for initial seed user',\n default: 'admin@example.com',\n theme,\n validate: (email) => (isEmail(email) ? true : 'Enter an address such as admin@example.com'),\n },\n context,\n ));\n confirmChoice('Admin email', adminEmail);\n\n return { template, templateRef, targetFolder, name: basename(targetFolder), appIndex, adminEmail };\n}\n\n/**\n * Offer the latest release and the latest commit, each with its date, as the template to start from.\n * @returns The release tag, or `main` for the latest commit; undefined when neither is known (offline).\n */\nasync function askTemplateRef(): Promise<string | undefined> {\n const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);\n\n console.info(pc.dim('This create CLI allows you to get started with cella quickly.'));\n console.info();\n if (release)\n console.info(` Latest release: ${release.tag}${release.date ? ` ${pc.dim(`· ${release.date}`)}` : ''}`);\n if (commit) {\n console.info(` Latest commit: ${commit.sha.slice(0, 7)} ${pc.dim(`· ${commit.message} · ${commit.date}`)}`);\n console.info(` ${pc.gray(`https://github.com/${templateRepository}/commit/${commit.sha}`)}`);\n }\n if (release || commit) console.info();\n\n if (!release) {\n warn('Latest release not found · using the latest commit on main');\n console.info();\n return commit ? 'main' : undefined;\n }\n\n // Without a commit to offer or a terminal to choose on (CI, piped stdin), the release is the reproducible start\n const choices = [\n { name: 'Latest release', value: 'release' },\n { name: 'Latest commit', value: 'commit' },\n ];\n if (\n !commit ||\n !process.stdin.isTTY ||\n (await select({ message: 'Choose which cella version to start from:', theme, choices }, context)) === 'release'\n ) {\n confirmChoice('Latest release', release.tag);\n return release.tag;\n }\n // The tip of main: a shallow clone over GitHub's smart HTTP cannot reliably fetch an arbitrary sha\n confirmChoice('Latest commit', commit.sha.slice(0, 7));\n return 'main';\n}\n\n/** An app index with its frontend, backend and database ports, such as \"1 → :3001 / :4010 / :5442\". */\nfunction formatAppIndex(index: number, note = ''): string {\n const { frontend, services, databases } = appPorts(index);\n return `${index} → :${frontend} / :${services[0]} / :${databases[0]}${note}`;\n}\n\n/** Suggest an app index no sibling app and no listener on this machine takes, and ask for one. */\nasync function askAppIndex(targetFolder: string): Promise<number> {\n const siblings = await detectUsedPorts(targetFolder);\n const presets = [1, 2, 3];\n const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)] as const)));\n const isBusy = (i: number) => (busy.get(i)?.length ?? 0) > 0;\n const suggested = findNextAppIndex(siblings, isBusy);\n const label = (i: number, note = '') => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);\n\n // The hint sits in the message, so clearPromptOnDone wipes it; a plain message style keeps the title alone bold\n let message = `${pc.bold('App index')} ${pc.dim('· to avoid port conflicts with other apps on this machine')}`;\n if (siblings.length > 0) {\n const count = siblings.length;\n message += pc.dim(`\\nDetected ${count} sibling app${count === 1 ? '' : 's'} · suggested index ${suggested}`);\n }\n\n // 0 is the default and the suggestion comes first, so neither repeats among the presets\n const choice = await select(\n {\n message,\n theme: { ...theme, style: { ...theme.style, message: (text: string) => text } },\n choices: [\n ...(suggested > 0 ? [{ name: formatAppIndex(suggested, ' (suggested)'), value: suggested }] : []),\n { name: label(0, ' (default)'), value: 0 },\n ...presets.filter((i) => i !== suggested).map((i) => ({ name: label(i), value: i })),\n { name: 'Custom index', value: -1 },\n ],\n },\n context,\n );\n if (choice !== -1) return choice;\n\n const custom = await input(\n {\n message: `Enter custom index, ${appIndexRule}`,\n default: String(suggested),\n theme,\n validate: (value) => (isAppIndex(Number(value)) ? true : `Must be ${appIndexRule}`),\n },\n context,\n );\n return Number(custom);\n}\n","import fs from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport type { Answers } from './answers';\nimport { appPorts } from './dev-ports';\nimport { warn } from './display';\n\n/** The version an app starts from, so release-please cuts its first release from a clean slate. */\nconst initialVersion = '0.0.0';\n\n/** Entry points a coding agent reads from the repo root; the rules and skills live in the template's `cella/` folder. */\nconst agentFiles: Record<string, string> = {\n 'AGENTS.md':\n '# Agent guidelines\\n\\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\\n',\n 'CLAUDE.md': '@cella/AGENTS.md\\n',\n};\n\nconst manifestPath = 'cella/create-cella.json';\nconst editNames = [\n 'quickstart',\n 'configTemplate',\n 'config',\n 'cliConfig',\n 'envExample',\n 'releaseConfig',\n 'releaseManifest',\n] as const;\n\n/** The template paths a new app changes, as the template itself names them in `cella/create-cella.json`. */\ninterface Manifest {\n remove: string[];\n empty: string[];\n /** Template path to the copy's path in the app. */\n copy: Record<string, string>;\n /** Template path to the symlink's path in the app. */\n link: Record<string, string>;\n edit: Record<(typeof editNames)[number], string>;\n}\n\n/** @throws When the template has no manifest, or its manifest names no path for an edit this version makes. */\nasync function readManifest(targetFolder: string): Promise<Manifest> {\n const source = await fs.readFile(join(targetFolder, manifestPath), 'utf8').catch(() => null);\n if (source === null) throw new Error(`This template has no ${manifestPath}: use a newer template.`);\n const manifest: Manifest = JSON.parse(source);\n const unnamed = editNames.filter((name) => typeof manifest.edit?.[name] !== 'string');\n if (unnamed.length > 0) {\n throw new Error(`${manifestPath} names no path for ${unnamed.join(', ')}: use a newer template.`);\n }\n return manifest;\n}\n\n/**\n * Turn the template's files in `targetFolder` into the app's: its name, index and admin email in the config and the\n * `.env`, its own release state, the quickstart as README, and none of the template's own repos, migrations or stack.\n * @returns The template paths it expected and did not find; a template without one skips that edit.\n */\nexport async function writeAppFiles({ targetFolder, name, appIndex, adminEmail }: Answers): Promise<string[]> {\n const missing: string[] = [];\n const at = (path: string) => join(targetFolder, path);\n // A template path that is not there goes into `missing`, and its edit is skipped\n const edit = async (path: string, change: (file: string) => Promise<unknown>) => {\n try {\n await change(at(path));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n missing.push(path);\n }\n };\n const rewrite = (path: string, change: (source: string) => string) =>\n edit(path, async (file) => fs.writeFile(file, change(await fs.readFile(file, 'utf8')), 'utf8'));\n const displayName = name.replace(/-/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase());\n const { remove, empty, copy, link, edit: paths } = await readManifest(targetFolder);\n\n try {\n for (const [from, to] of Object.entries(copy)) await edit(from, (file) => fs.copyFile(file, at(to)));\n await edit(paths.quickstart, async (file) =>\n fs.writeFile(at('README.md'), quickstartToReadme(await fs.readFile(file, 'utf8'), displayName, appIndex), 'utf8'),\n );\n await writeAgentEntry(targetFolder, link);\n\n // The placeholder config becomes the app's default config, and goes\n await edit(paths.configTemplate, async (file) => {\n const source = await fs.readFile(file, 'utf8');\n const config = source\n .replaceAll('__project_name__', displayName)\n .replaceAll('__project_slug__', name)\n .replace(/^(\\s*devAppIndex:\\s*)\\d+/m, (_, head: string) => `${head}${appIndex}`);\n await fs.writeFile(at(paths.config), config, 'utf8');\n await fs.rm(file);\n });\n\n // The app's own identity: the template's metadata keys stay, emptied, for the app to fill in\n await rewrite('package.json', (source) => {\n let pkg = source\n .replace(/^(\\s*\"name\":\\s*)\"[^\"]*\"/m, `$1\"${name}\"`)\n .replace(/^(\\s*\"version\":\\s*)\"[^\"]*\"/m, `$1\"${initialVersion}\"`)\n .replace(/^(\\s*\"keywords\":\\s*)\\[[^\\]]*\\]/m, '$1[]');\n for (const field of ['license', 'repository', 'description', 'author', 'homepage']) {\n pkg = pkg.replace(new RegExp(`^(\\\\s*\"${field}\":\\\\s*)\"[^\"]*\"`, 'm'), '$1\"\"');\n }\n return pkg;\n });\n // The template keeps its changelog in its docs folder, which the app keeps as upstream reference\n await rewrite(paths.releaseConfig, (source) => {\n const config = JSON.parse(source) as { packages?: Record<string, Record<string, unknown>> };\n config.packages ??= {};\n config.packages['.'] ??= {};\n config.packages['.']['changelog-path'] = 'CHANGELOG.md';\n return `${JSON.stringify(config, null, 2)}\\n`;\n });\n await edit(paths.releaseManifest, (file) => fs.writeFile(file, `{\\n \".\": \"${initialVersion}\"\\n}\\n`, 'utf8'));\n await fs.writeFile(at('CHANGELOG.md'), '# Changelog\\n', 'utf8');\n\n // `pnpm cella upgrade` never merges this file, so the list goes once here\n await rewrite(paths.cliConfig, stripForks);\n // Every port follows `devAppIndex` in the config, so the admin is the one value the app's `.env` changes\n await edit(paths.envExample, async (file) => {\n const env = (await fs.readFile(file, 'utf8')).replace(/^ADMIN_EMAIL=.*$/gm, () => `ADMIN_EMAIL=${adminEmail}`);\n await fs.writeFile(file.replace(/\\.example$/, ''), env, 'utf8');\n });\n\n // What an app starts without: the template's own migrations, and its stack file with the template's encryption salt\n for (const folder of empty) {\n await edit(folder, async (dir) => {\n const entries = await fs.readdir(dir);\n await Promise.all(entries.map((entry) => fs.rm(join(dir, entry), { recursive: true, force: true })));\n });\n }\n for (const path of remove) await edit(path, (file) => fs.rm(file, { recursive: true }));\n } catch (error) {\n throw new Error(`Error during the cleaning process: ${error instanceof Error ? error.message : error}`);\n }\n return missing;\n}\n\n/**\n * The quickstart as the README of a new app: at the repo root, with this app's port and without the step that just ran.\n * Its links are relative to `cella/` in the template, so `./x` becomes `./cella/x` and `../x` becomes `./x`.\n */\nfunction quickstartToReadme(source: string, displayName: string, appIndex: number): string {\n return source\n .replace(/^# .*$/m, `# ${displayName}`)\n .replace(/^## Create\\n[\\s\\S]*?(?=^## )/m, '')\n .replaceAll('](./', '](./cella/')\n .replaceAll('](../', '](./')\n .replaceAll('http://localhost:3000', `http://localhost:${appPorts(appIndex).frontend}`);\n}\n\n/** Point coding agents at the template's rules and skills, which sit in `cella/`, out of a root they would not search. */\nasync function writeAgentEntry(targetFolder: string, link: Manifest['link']): Promise<void> {\n await Promise.all(\n Object.entries(agentFiles).map(([file, content]) => fs.writeFile(join(targetFolder, file), content, 'utf8')),\n );\n\n // Local to this clone: `.claude` is gitignored, and the check scripts read tracked paths as files. AGENTS.md names the folder for a new clone.\n for (const [target, path] of Object.entries(link)) {\n const file = join(targetFolder, path);\n try {\n await fs.mkdir(dirname(file), { recursive: true });\n await fs.symlink(relative(dirname(file), join(targetFolder, target)), file);\n } catch (error) {\n // Windows refuses a symlink without developer mode; the skills stay readable in their own folder\n warn(`skipped ${path}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n}\n\n/** The source of an upgrade config (`cella/cella.config.ts`) without its `forks` property and a comment line directly above it. */\nexport function stripForks(source: string): string {\n // The closing bracket sits at the property's own indent, or on the same line for a short list\n return source.replace(\n /^(?:[ \\t]*\\/\\/[^\\n]*\\n)?([ \\t]*)forks:\\s*\\[(?:[^\\n]*|[\\s\\S]*?\\n\\1)\\],?[ \\t]*\\n(?:[ \\t]*\\n)?/m,\n '',\n );\n}\n","import fs from 'node:fs';\nimport git from 'isomorphic-git';\nimport { warn } from './display';\nimport { githubGitUrl, templateRepository } from './template';\n\n/**\n * Make the app's repository: one commit of its files, and the template as remote `cella-upstream`, the name\n * `pnpm cella upgrade` looks for. The commit's `Cella-Base:` trailer names the template commit the files come from,\n * which the upgrade reads from the root commit to find its first merge base: the app shares no history with the template.\n * A failure only warns: the app's files stay usable without git.\n */\nexport async function makeRepository(dir: string, baseCommit: string | null): Promise<void> {\n try {\n await git.init({ fs, dir, defaultBranch: 'main' });\n await git.add({ fs, dir, filepath: '.' });\n const message = baseCommit ? `Initial commit\\n\\nCella-Base: ${baseCommit}` : 'Initial commit';\n // An explicit author, so the commit needs no git config on this machine\n await git.commit({ fs, dir, message, author: { name: 'cella', email: 'info@cellajs.com' } });\n await git.addRemote({ fs, dir, remote: 'cella-upstream', url: githubGitUrl(templateRepository), force: true });\n } catch (error) {\n warn(`skipped git init: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n","#!/usr/bin/env tsx\n\nimport { mkdir, readdir, rm } from 'node:fs/promises';\nimport { basename, join, resolve } from 'node:path';\nimport { Command, InvalidArgumentError } from 'commander';\nimport { appSlugRule, askAnswers, type Flags, isAppSlug, isEmail } from './answers';\nimport { writeAppFiles } from './app-files';\nimport { makeRepository } from './app-repo';\nimport pc from './colors';\nimport { appIndexRule, isAppIndex } from './dev-ports';\nimport { cliName, cliVersion, showBanner, showNextSteps, step, stopSpinner, warn } from './display';\nimport { getTemplate } from './template';\n\nfunction parseFlags(): Flags {\n const program = new Command(cliName)\n .version(cliVersion, '-v, --version', `output the current version of ${cliName}`)\n .argument('[directory]', 'the directory name for the new app')\n .usage('[directory] [options]')\n .helpOption('-h, --help', 'display this help message')\n .option('--template <path>', 'use a custom template (local git checkout or github:user/repo)')\n .option('--app-index <number>', `set this app's number for its dev ports, ${appIndexRule}`, (value) => {\n if (!isAppIndex(Number(value))) throw new InvalidArgumentError(`App index must be ${appIndexRule}`);\n return Number(value);\n })\n .option('--admin-email <email>', 'set the admin email for the initial seed user', (value) => {\n if (!isEmail(value)) throw new InvalidArgumentError('Admin email must be an address such as admin@example.com');\n return value;\n })\n .parse();\n\n const directory = program.args[0]?.trim() || undefined;\n if (directory && !isAppSlug(basename(resolve(directory)))) {\n program.error(`error: invalid app name \"${directory}\": ${appSlugRule}.`);\n }\n return { directory, ...program.opts<Omit<Flags, 'directory'>>() };\n}\n\nasync function main(): Promise<void> {\n const flags = parseFlags();\n showBanner();\n const answers = await askAnswers(flags);\n const { targetFolder } = answers;\n\n // Until the app is made, a failure or a signal removes what the run wrote\n let undo = async () => {};\n const onSignal = (code: number) => () => {\n stopSpinner();\n void undo().finally(() => process.exit(code));\n };\n const onSigint = onSignal(130);\n const onSigterm = onSignal(143);\n process.once('SIGINT', onSigint).once('SIGTERM', onSigterm);\n\n let missing: string[];\n try {\n step('creating app folder');\n const createdFolder = await mkdir(targetFolder, { recursive: true });\n undo = () => removeOutput(targetFolder, createdFolder);\n const baseCommit = await getTemplate(answers);\n step('cleaning template');\n missing = await writeAppFiles(answers);\n step('initializing git');\n await makeRepository(targetFolder, baseCommit);\n step();\n } catch (error) {\n stopSpinner();\n await undo();\n throw error;\n } finally {\n process.off('SIGINT', onSigint).off('SIGTERM', onSigterm);\n }\n\n if (missing.length > 0) warn(`Not in the template, skipped: ${missing.join(', ')}`);\n showNextSteps(answers);\n}\n\n/** Remove what a run wrote: the folders `mkdir` made, else everything in the target, which the run only accepts empty. */\nasync function removeOutput(targetFolder: string, createdFolder: string | undefined): Promise<void> {\n if (createdFolder) return rm(createdFolder, { recursive: true, force: true });\n const entries = await readdir(targetFolder);\n await Promise.all(entries.map((entry) => rm(join(targetFolder, entry), { recursive: true, force: true })));\n}\n\nmain().catch((error) => {\n // Ctrl-c at a prompt. Its class lives in @inquirer/core, which is no direct dependency: match the name.\n if (error instanceof Error && error.name === 'ExitPromptError') process.exit(130);\n console.error(`${pc.red('✗')} ${pc.red(error instanceof Error ? error.message : String(error))}`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,gBAAyB;CAEhC,MAAM,EAAE,UAAU,gBAAgB,QAAQ;CAC1C,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,gBAAgB,KAAA,GAAW,OAAO,gBAAgB,OAAO,gBAAgB;CAC7E,OAAO,CAAC,CAAC,QAAQ,OAAO;AAC1B;AAEA,SAAS,WAAW,OAAmB,MAAsB;CAC3D,IAAI,CAAC,cAAc,GAAG,OAAO;CAC7B,OAAO,UAAU,OAAO,MAAM,EAAE,gBAAgB,MAAM,CAAC;AACzD;AAEA,MAAM,KAAK;CACT,OAAO,SAAiB,WAAW,QAAQ,IAAI;CAC/C,OAAO,SAAiB,WAAW,QAAQ,IAAI;CAC/C,MAAM,SAAiB,WAAW,OAAO,IAAI;CAC7C,OAAO,SAAiB,WAAW,QAAQ,IAAI;CAC/C,QAAQ,SAAiB,WAAW,SAAS,IAAI;CACjD,MAAM,SAAiB,WAAW,OAAO,IAAI;CAC7C,SAAS,SAAiB,WAAW,UAAU,IAAI;AACrD;;;;;;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AAc,OAAO;EACrC,KAAK,kBAAkB;EACvB,MAAM,eAAe,cAAc,UAAU;EAC7C,KAAK;CACP,SAAS,OAAO;EACd,YAAY;EACZ,MAAM,KAAK;EACX,MAAM;CACR,UAAU;EACR,QAAQ,IAAI,UAAU,QAAQ,CAAC,CAAC,IAAI,WAAW,SAAS;CAC1D;CAEA,IAAI,QAAQ,SAAS,GAAG,KAAK,iCAAiC,QAAQ,KAAK,IAAI,GAAG;CAClF,cAAc,OAAO;AACvB;;AAGA,eAAe,aAAa,cAAsB,eAAkD;CAClG,IAAI,eAAe,OAAO,GAAG,eAAe;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;CAC5E,MAAM,UAAU,MAAM,QAAQ,YAAY;CAC1C,MAAM,QAAQ,IAAI,QAAQ,KAAK,UAAU,GAAG,KAAK,cAAc,KAAK,GAAG;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC,CAAC,CAAC;AAC3G;AAEA,KAAK,CAAC,CAAC,OAAO,UAAU;CAEtB,IAAI,iBAAiB,SAAS,MAAM,SAAS,mBAAmB,QAAQ,KAAK,GAAG;CAChF,QAAQ,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,GAAG,GAAG,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,GAAG;CAChG,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cellajs/create-cella",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Cella is a TypeScript template to create web apps with sync and offline capabilities.",
@@ -14,29 +14,21 @@
14
14
  "homepage": "https://cellajs.com",
15
15
  "author": "CellaJS <info@cellajs.com>",
16
16
  "engines": {
17
- "node": "26.x"
17
+ "node": ">=26"
18
18
  },
19
19
  "type": "module",
20
- "main": "./dist/index.js",
21
20
  "files": [
22
21
  "dist",
23
22
  "index.js",
24
23
  "README.md"
25
24
  ],
26
- "imports": {
27
- "#/*": "./src/*"
28
- },
29
25
  "bin": {
30
26
  "create-cella": "index.js"
31
27
  },
32
28
  "dependencies": {
33
29
  "@inquirer/prompts": "^8.8.0",
34
30
  "commander": "^15.1.0",
35
- "ignore": "^7.0.14",
36
- "isomorphic-git": "^1.44.13",
37
- "ora": "^10.0.0",
38
- "picocolors": "^1.1.1",
39
- "validate-npm-package-name": "^8.0.0"
31
+ "isomorphic-git": "^1.44.13"
40
32
  },
41
33
  "devDependencies": {
42
34
  "@biomejs/biome": "^2.6.7",
@@ -44,7 +36,6 @@
44
36
  "@commitlint/config-conventional": "^21.2.4",
45
37
  "@evilmartians/lefthook": "^2.2.2",
46
38
  "@types/node": "26.6.6",
47
- "@types/validate-npm-package-name": "^4.0.2",
48
39
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
49
40
  "rimraf": "^6.1.4",
50
41
  "tsdown": "^0.23.7",
@@ -73,15 +64,30 @@
73
64
  "style",
74
65
  "test"
75
66
  ]
67
+ ],
68
+ "header-max-length": [
69
+ 2,
70
+ "always",
71
+ 120
72
+ ],
73
+ "body-max-line-length": [
74
+ 0,
75
+ "always",
76
+ 200
77
+ ],
78
+ "footer-max-line-length": [
79
+ 0,
80
+ "always",
81
+ 200
76
82
  ]
77
83
  }
78
84
  },
79
85
  "scripts": {
80
86
  "start": "tsx ./src/create-cella-cli.ts",
81
- "try": "tsx ./src/create-cella-cli.ts ../cella-try-app",
87
+ "try": "rimraf ../cella-try-app && tsx ./src/create-cella-cli.ts ../cella-try-app",
82
88
  "clean": "rimraf ./dist",
83
89
  "build": "tsdown",
84
- "test-build": "pnpm run build && node index.js",
90
+ "test-build": "pnpm run build && node index.js --help",
85
91
  "check": "pnpm ts && pnpm biome check --write .",
86
92
  "ts": "tsgo --pretty",
87
93
  "lint": "biome check .",