alepha 0.19.3 → 0.19.4
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/assets/swagger-ui/swagger-ui-bundle.js +1 -1
- package/dist/api/audits/index.d.ts +8 -8
- package/dist/api/invitations/index.d.ts +790 -0
- package/dist/api/invitations/index.d.ts.map +1 -0
- package/dist/api/invitations/index.js +665 -0
- package/dist/api/invitations/index.js.map +1 -0
- package/dist/api/jobs/index.browser.js +8 -9
- package/dist/api/jobs/index.browser.js.map +1 -1
- package/dist/api/jobs/index.d.ts +99 -43
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/jobs/index.js +257 -40
- package/dist/api/jobs/index.js.map +1 -1
- package/dist/api/keys/index.d.ts +5 -5
- package/dist/api/notifications/index.browser.js +0 -1
- package/dist/api/notifications/index.browser.js.map +1 -1
- package/dist/api/notifications/index.d.ts +3 -3
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/notifications/index.js +0 -1
- package/dist/api/notifications/index.js.map +1 -1
- package/dist/api/parameters/index.browser.js +112 -1
- package/dist/api/parameters/index.browser.js.map +1 -1
- package/dist/api/parameters/index.d.ts +90 -3
- package/dist/api/parameters/index.d.ts.map +1 -1
- package/dist/api/parameters/index.js +79 -12
- package/dist/api/parameters/index.js.map +1 -1
- package/dist/{billing → api/payments}/index.d.ts +67 -49
- package/dist/api/payments/index.d.ts.map +1 -0
- package/dist/{billing → api/payments}/index.js +108 -74
- package/dist/api/payments/index.js.map +1 -0
- package/dist/api/subscriptions/index.d.ts +1692 -0
- package/dist/api/subscriptions/index.d.ts.map +1 -0
- package/dist/api/subscriptions/index.js +1870 -0
- package/dist/api/subscriptions/index.js.map +1 -0
- package/dist/api/users/index.d.ts +18 -2
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +167 -34
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts +13 -13
- package/dist/api/workflows/index.browser.js +246 -0
- package/dist/api/workflows/index.browser.js.map +1 -0
- package/dist/api/workflows/index.d.ts +1618 -0
- package/dist/api/workflows/index.d.ts.map +1 -0
- package/dist/api/workflows/index.js +1504 -0
- package/dist/api/workflows/index.js.map +1 -0
- package/dist/cli/core/index.d.ts +44 -28
- package/dist/cli/core/index.d.ts.map +1 -1
- package/dist/cli/core/index.js +16 -61
- package/dist/cli/core/index.js.map +1 -1
- package/dist/cli/vendor/index.d.ts +31 -8
- package/dist/cli/vendor/index.d.ts.map +1 -1
- package/dist/cli/vendor/index.js +79 -24
- package/dist/cli/vendor/index.js.map +1 -1
- package/dist/core/index.browser.js +21 -2
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +33 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +21 -2
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +21 -2
- package/dist/core/index.native.js.map +1 -1
- package/dist/core/index.workerd.js +21 -2
- package/dist/core/index.workerd.js.map +1 -1
- package/dist/email/smtp/index.js +24 -8
- package/dist/email/smtp/index.js.map +1 -1
- package/dist/orm/core/index.browser.js +0 -18
- package/dist/orm/core/index.browser.js.map +1 -1
- package/dist/orm/core/index.bun.js +0 -17
- package/dist/orm/core/index.bun.js.map +1 -1
- package/dist/orm/core/index.d.ts +1 -13
- package/dist/orm/core/index.d.ts.map +1 -1
- package/dist/orm/core/index.js +0 -17
- package/dist/orm/core/index.js.map +1 -1
- package/dist/orm/postgres/index.bun.js +3 -3
- package/dist/orm/postgres/index.bun.js.map +1 -1
- package/dist/orm/postgres/index.d.ts.map +1 -1
- package/dist/orm/postgres/index.js +3 -3
- package/dist/orm/postgres/index.js.map +1 -1
- package/dist/react/router/index.browser.js +25 -3
- package/dist/react/router/index.browser.js.map +1 -1
- package/dist/react/router/index.d.ts +16 -1
- package/dist/react/router/index.d.ts.map +1 -1
- package/dist/react/router/index.js +25 -3
- package/dist/react/router/index.js.map +1 -1
- package/dist/security/index.d.ts +28 -0
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js +28 -0
- package/dist/security/index.js.map +1 -1
- package/package.json +37 -20
- package/src/api/invitations/__tests__/InvitationService.spec.ts +439 -0
- package/src/api/invitations/controllers/AdminInvitationController.ts +86 -0
- package/src/api/invitations/controllers/InvitationController.ts +84 -0
- package/src/api/invitations/entities/invitations.ts +33 -0
- package/src/api/invitations/index.ts +65 -0
- package/src/api/invitations/jobs/InvitationJobs.ts +37 -0
- package/src/api/invitations/providers/InvitationProvider.ts +45 -0
- package/src/api/invitations/schemas/createInvitationSchema.ts +12 -0
- package/src/api/invitations/schemas/invitationConfigAtom.ts +20 -0
- package/src/api/invitations/schemas/invitationQuerySchema.ts +15 -0
- package/src/api/invitations/schemas/invitationResourceSchema.ts +6 -0
- package/src/api/invitations/schemas/invitationWithResourceInfoSchema.ts +22 -0
- package/src/api/invitations/schemas/myInvitationsQuerySchema.ts +10 -0
- package/src/api/invitations/services/InvitationService.ts +556 -0
- package/src/api/jobs/__tests__/$job.spec.ts +876 -0
- package/src/api/jobs/controllers/AdminJobController.ts +44 -0
- package/src/api/jobs/entities/jobExecutionEntity.ts +0 -2
- package/src/api/jobs/index.ts +0 -3
- package/src/api/jobs/primitives/$job.ts +22 -11
- package/src/api/jobs/providers/JobProvider.ts +229 -19
- package/src/api/jobs/schemas/jobConfigAtom.ts +4 -0
- package/src/api/jobs/schemas/jobCronInfoSchema.ts +1 -0
- package/src/api/jobs/schemas/jobExecutionQuerySchema.ts +0 -1
- package/src/api/jobs/schemas/jobQueueDepthSchema.ts +1 -0
- package/src/api/jobs/schemas/jobRegistrationSchema.ts +1 -6
- package/src/api/jobs/services/JobService.ts +51 -12
- package/src/api/notifications/schemas/notificationQuerySchema.ts +0 -1
- package/src/api/parameters/__tests__/$parameter.spec.ts +327 -0
- package/src/api/parameters/controllers/AdminParameterController.ts +29 -3
- package/src/api/parameters/index.browser.ts +12 -0
- package/src/api/parameters/primitives/$parameter.ts +20 -3
- package/src/api/parameters/services/ParameterProvider.ts +48 -7
- package/src/{billing → api/payments}/__tests__/PaymentMethodService.spec.ts +32 -6
- package/src/api/payments/__tests__/PaymentService.spec.ts +279 -0
- package/src/{billing/controllers/AdminBillingController.ts → api/payments/controllers/AdminPaymentController.ts} +26 -21
- package/src/{billing/controllers/BillingController.ts → api/payments/controllers/PaymentController.ts} +23 -11
- package/src/{billing → api/payments}/entities/paymentIntents.ts +1 -0
- package/src/{billing/errors/BillingError.ts → api/payments/errors/PaymentError.ts} +1 -1
- package/src/{billing → api/payments}/index.ts +31 -25
- package/src/{billing/providers/MemoryBillingProvider.ts → api/payments/providers/MemoryPaymentProvider.ts} +4 -4
- package/src/{billing/providers/BillingProvider.ts → api/payments/providers/PaymentProvider.ts} +9 -2
- package/src/{billing → api/payments}/services/PaymentMethodService.ts +5 -5
- package/src/{billing/services/BillingService.ts → api/payments/services/PaymentService.ts} +94 -18
- package/src/api/subscriptions/__tests__/BillingService.spec.ts +218 -0
- package/src/api/subscriptions/__tests__/SubscriptionService.spec.ts +278 -0
- package/src/api/subscriptions/controllers/AdminSubscriptionController.ts +212 -0
- package/src/api/subscriptions/controllers/SubscriptionController.ts +189 -0
- package/src/api/subscriptions/entities/subscriptionEvents.ts +54 -0
- package/src/api/subscriptions/entities/subscriptions.ts +68 -0
- package/src/api/subscriptions/index.ts +144 -0
- package/src/api/subscriptions/jobs/SubscriptionJobs.ts +382 -0
- package/src/api/subscriptions/middleware/$requireLimit.ts +50 -0
- package/src/api/subscriptions/middleware/$requirePlan.ts +49 -0
- package/src/api/subscriptions/notifications/SubscriptionNotifications.ts +110 -0
- package/src/api/subscriptions/schemas/cancelSubscriptionSchema.ts +8 -0
- package/src/api/subscriptions/schemas/changePlanSchema.ts +9 -0
- package/src/api/subscriptions/schemas/createSubscriptionSchema.ts +11 -0
- package/src/api/subscriptions/schemas/entitlementsSchema.ts +21 -0
- package/src/api/subscriptions/schemas/mrrSchema.ts +13 -0
- package/src/api/subscriptions/schemas/planDefinitionSchema.ts +71 -0
- package/src/api/subscriptions/schemas/planResourceSchema.ts +25 -0
- package/src/api/subscriptions/schemas/subscriptionEventResourceSchema.ts +8 -0
- package/src/api/subscriptions/schemas/subscriptionQuerySchema.ts +19 -0
- package/src/api/subscriptions/schemas/subscriptionResourceSchema.ts +6 -0
- package/src/api/subscriptions/schemas/subscriptionSettingsSchema.ts +32 -0
- package/src/api/subscriptions/schemas/subscriptionStatsSchema.ts +23 -0
- package/src/api/subscriptions/services/BillingService.ts +437 -0
- package/src/api/subscriptions/services/SubscriptionConfig.ts +56 -0
- package/src/api/subscriptions/services/SubscriptionService.ts +867 -0
- package/src/api/subscriptions/services/UsageService.ts +118 -0
- package/src/api/users/__tests__/AdminUserController.spec.ts +80 -1
- package/src/api/users/__tests__/CredentialService.spec.ts +177 -0
- package/src/api/users/__tests__/EmailVerification.spec.ts +29 -18
- package/src/api/users/__tests__/PasswordReset.spec.ts +3 -0
- package/src/api/users/__tests__/RegistrationService.spec.ts +148 -1
- package/src/api/users/__tests__/SessionService.spec.ts +142 -1
- package/src/api/users/atoms/realmAuthSettingsAtom.ts +10 -1
- package/src/api/users/controllers/UserController.ts +3 -8
- package/src/api/users/notifications/UserNotifications.ts +23 -0
- package/src/api/users/schemas/loginSchema.ts +1 -1
- package/src/api/users/services/CredentialService.ts +51 -4
- package/src/api/users/services/RegistrationService.ts +38 -9
- package/src/api/users/services/SessionService.ts +62 -9
- package/src/api/users/services/UserService.ts +21 -12
- package/src/api/workflows/__tests__/$workflow.spec.ts +616 -0
- package/src/api/workflows/controllers/AdminWorkflowController.ts +191 -0
- package/src/api/workflows/entities/workflowExecutions.ts +74 -0
- package/src/api/workflows/entities/workflowStepExecutions.ts +74 -0
- package/src/api/workflows/entities/workflowStepLogs.ts +13 -0
- package/src/api/workflows/index.browser.ts +22 -0
- package/src/api/workflows/index.ts +124 -0
- package/src/api/workflows/jobs/WorkflowJobs.ts +77 -0
- package/src/api/workflows/primitives/$workflow.ts +202 -0
- package/src/api/workflows/providers/WorkflowProvider.ts +1284 -0
- package/src/api/workflows/schemas/workflowActivitySchema.ts +15 -0
- package/src/api/workflows/schemas/workflowConfigAtom.ts +51 -0
- package/src/api/workflows/schemas/workflowExecutionDetailSchema.ts +18 -0
- package/src/api/workflows/schemas/workflowExecutionQuerySchema.ts +26 -0
- package/src/api/workflows/schemas/workflowExecutionResourceSchema.ts +30 -0
- package/src/api/workflows/schemas/workflowRegistrationSchema.ts +26 -0
- package/src/api/workflows/schemas/workflowStatsSchema.ts +16 -0
- package/src/api/workflows/schemas/workflowStepExecutionResourceSchema.ts +15 -0
- package/src/api/workflows/services/WorkflowService.ts +382 -0
- package/src/cli/core/templates/webAppRouterTs.ts +5 -58
- package/src/cli/vendor/__tests__/VendorService.spec.ts +283 -178
- package/src/cli/vendor/services/VendorService.ts +126 -27
- package/src/core/__tests__/TypeProvider.spec.ts +4 -2
- package/src/core/providers/SchemaValidator.ts +1 -1
- package/src/core/providers/TypeProvider.ts +46 -3
- package/src/orm/__tests__/enums.spec.ts +22 -29
- package/src/orm/__tests__/orm-showcase-tests.ts +430 -0
- package/src/orm/__tests__/orm-showcase.spec.ts +167 -0
- package/src/orm/core/providers/DatabaseTypeProvider.ts +0 -29
- package/src/orm/postgres/services/PostgresModelBuilder.ts +3 -6
- package/src/react/router/__tests__/$page.browser.spec.tsx +157 -0
- package/src/react/router/providers/ReactBrowserProvider.ts +39 -0
- package/src/react/router/providers/ReactBrowserRouterProvider.ts +22 -0
- package/src/security/__tests__/$secure-combinations.spec.ts +945 -0
- package/src/security/primitives/$secure.ts +28 -0
- package/dist/billing/index.d.ts.map +0 -1
- package/dist/billing/index.js.map +0 -1
- package/src/billing/__tests__/BillingService.spec.ts +0 -136
- /package/src/{billing → api/payments}/entities/paymentMethods.ts +0 -0
- /package/src/{billing → api/payments}/entities/refunds.ts +0 -0
- /package/src/{billing → api/payments}/schemas/intentSchemas.ts +0 -0
- /package/src/{billing → api/payments}/schemas/paymentMethodSchemas.ts +0 -0
- /package/src/{billing → api/payments}/schemas/refundSchemas.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["alephaPackageJson.devDependencies","devDependencies","viteAnalyzer","gzipCb","brotliCompressCb","viteAnalyzer"],"sources":["../../../src/cli/core/atoms/appEntryOptions.ts","../../../src/cli/core/atoms/buildOptions.ts","../../../src/cli/core/atoms/devOptions.ts","../../../src/cli/core/providers/AppEntryProvider.ts","../../../src/cli/core/services/ViteUtils.ts","../../../src/cli/core/providers/ViteBuildProvider.ts","../../../src/cli/core/services/AlephaCliUtils.ts","../../../package.json","../../../src/cli/core/version.ts","../../../src/cli/core/services/PackageManagerUtils.ts","../../../src/cli/core/assets.ts","../../../src/cli/core/templates/agentMd.ts","../../../src/cli/core/templates/alephaConfigTs.ts","../../../src/cli/core/templates/apiAppSecurityTs.ts","../../../src/cli/core/templates/apiHelloControllerTs.ts","../../../src/cli/core/templates/apiHelloResponseSchemaTs.ts","../../../src/cli/core/templates/apiIndexTs.ts","../../../src/cli/core/templates/biomeJson.ts","../../../src/cli/core/templates/dummySpecTs.ts","../../../src/cli/core/templates/editorconfig.ts","../../../src/cli/core/templates/gitignore.ts","../../../src/cli/core/templates/mainBrowserTs.ts","../../../src/cli/core/templates/mainCss.ts","../../../src/cli/core/templates/mainServerTs.ts","../../../src/cli/core/templates/tsconfigJson.ts","../../../src/cli/core/templates/viteConfigTs.ts","../../../src/cli/core/templates/webAdminDashboardTsx.ts","../../../src/cli/core/templates/webAppRouterTs.ts","../../../src/cli/core/templates/webHomeComponentTsx.ts","../../../src/cli/core/templates/webIndexTs.ts","../../../src/cli/core/services/ProjectScaffolder.ts","../../../src/cli/core/tasks/BuildTask.ts","../../../src/cli/core/tasks/BuildAssetsTask.ts","../../../src/cli/core/tasks/BuildClientTask.ts","../../../src/cli/core/tasks/BuildCloudflareTask.ts","../../../src/cli/core/tasks/BuildCompressTask.ts","../../../src/cli/core/tasks/BuildDockerTask.ts","../../../src/cli/core/tasks/BuildPrerenderTask.ts","../../../src/cli/core/tasks/BuildServerTask.ts","../../../src/cli/core/tasks/BuildSitemapTask.ts","../../../src/cli/core/tasks/BuildStaticTask.ts","../../../src/cli/core/tasks/BuildVercelTask.ts","../../../src/cli/core/commands/build.ts","../../../src/cli/core/commands/clean.ts","../../../src/cli/core/commands/db.ts","../../../src/cli/core/providers/ViteDevServerProvider.ts","../../../src/cli/core/commands/dev.ts","../../../src/cli/core/atoms/changelogOptions.ts","../../../src/cli/core/services/GitMessageParser.ts","../../../src/cli/core/commands/gen/changelog.ts","../../../src/cli/core/commands/gen/env.ts","../../../src/cli/core/commands/gen/openapi.ts","../../../src/cli/core/commands/gen.ts","../../../src/cli/core/commands/init.ts","../../../src/cli/core/commands/lint.ts","../../../src/cli/core/commands/root.ts","../../../src/cli/core/commands/test.ts","../../../src/cli/core/commands/typecheck.ts","../../../src/cli/core/commands/verify.ts","../../../src/cli/core/providers/AlephaCliExtensionProvider.ts","../../../src/cli/core/index.ts"],"sourcesContent":["import { $atom, type Static, t } from \"alepha\";\n\nexport const appEntryOptions = $atom({\n name: \"alepha.cli.appEntry.options\",\n schema: t.object({\n server: t.optional(t.text()),\n browser: t.optional(t.text()),\n style: t.optional(t.text()),\n }),\n default: {},\n});\n\nexport type AppEntryOptions = Static<typeof appEntryOptions.schema>;\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Deployment target for the build output.\n *\n * - `docker` - Generate Dockerfile for containerized deployment\n * - `vercel` - Generate Vercel deployment configuration (forces node runtime)\n * - `cloudflare` - Generate Cloudflare Workers configuration (forces workerd runtime)\n */\nexport type BuildTarget =\n | \"bare\"\n | \"docker\"\n | \"vercel\"\n | \"cloudflare\"\n | \"static\";\n\n/**\n * JavaScript runtime for the build output.\n *\n * - `node` - Node.js runtime (default)\n * - `bun` - Bun runtime (uses bun export conditions)\n * - `workerd` - Cloudflare Workers runtime (auto-set with cloudflare target)\n */\nexport type BuildRuntime = \"node\" | \"bun\" | \"workerd\";\n\n/**\n * Build options atom for CLI build command.\n *\n * Defines the available build configuration options with their defaults.\n * Options can be overridden via alepha.config.ts or CLI flags.\n */\nexport const buildOptions = $atom({\n name: \"alepha.cli.build.options\",\n description: \"Build configuration options\",\n schema: t.object({\n /**\n * Generate build stats report.\n *\n * - `true` - Generate a static HTML report\n * - `\"json\"` - Generate a JSON report\n */\n stats: t.optional(t.union([t.boolean(), t.enum([\"json\"])])),\n\n /**\n * Deployment target for the build output.\n *\n * - `docker` - Generate Dockerfile for containerized deployment\n * - `vercel` - Generate Vercel deployment configuration (forces node runtime)\n * - `cloudflare` - Generate Cloudflare Workers configuration (forces workerd runtime)\n */\n target: t.optional(\n t.enum([\"bare\", \"docker\", \"vercel\", \"cloudflare\", \"static\"]),\n ),\n\n /**\n * JavaScript runtime for the build output.\n *\n * - `node` - Node.js runtime (default)\n * - `bun` - Bun runtime (uses bun export conditions)\n * - `workerd` - Cloudflare Workers runtime (auto-set with cloudflare target)\n *\n * Note: Some targets force a specific runtime:\n * - `cloudflare` always uses `workerd`\n * - `vercel` always uses `node`\n */\n runtime: t.optional(t.enum([\"node\", \"bun\", \"workerd\"])),\n\n /**\n * Output directory configuration.\n */\n output: t.optional(\n t.object({\n /**\n * Root dist directory.\n *\n * @default \"dist\"\n */\n dist: t.optional(t.string({ default: \"dist\" })),\n\n /**\n * Public/client subdirectory.\n *\n * @default \"public\"\n */\n public: t.optional(t.string({ default: \"public\" })),\n }),\n ),\n\n /**\n * Vercel-specific deployment configuration.\n *\n * Note: Set `target: \"vercel\"` to enable Vercel deployment.\n * This object is only for additional configuration.\n */\n vercel: t.optional(\n t.object({\n projectName: t.optional(t.string()),\n orgId: t.optional(t.string()),\n projectId: t.optional(t.string()),\n config: t.optional(\n t.object({\n crons: t.optional(\n t.array(\n t.object({\n path: t.string(),\n schedule: t.string(),\n }),\n ),\n ),\n }),\n ),\n }),\n ),\n\n /**\n * Cloudflare-specific deployment configuration.\n *\n * Note: Set `target: \"cloudflare\"` to enable Cloudflare deployment.\n * This object is only for additional configuration.\n */\n cloudflare: t.optional(\n t.object({\n config: t.optional(t.json()),\n }),\n ),\n\n /**\n * Docker-specific deployment configuration.\n *\n * Note: Set `target: \"docker\"` to enable Docker deployment.\n * This object is only for additional configuration.\n */\n docker: t.optional(\n t.object({\n /**\n * Base image for the Dockerfile (FROM instruction).\n *\n * @default \"node:24-alpine\" for node runtime\n * @default \"oven/bun:alpine\" for bun runtime\n */\n from: t.optional(t.string()),\n\n /**\n * Command to run in the Docker container.\n *\n * @default \"node\" for node runtime\n * @default \"bun\" for bun runtime\n */\n command: t.optional(t.string()),\n\n /**\n * Docker build options (used when --image flag is passed).\n */\n image: t.optional(\n t.object({\n /**\n * Default image tag (name without version).\n *\n * Used when --image is provided without a full override:\n * - `--image` → `tag:latest`\n * - `--image=1.3.4` → `tag:1.3.4`\n * - `--image=other/img:v1` → `other/img:v1` (full override)\n *\n * @example \"myproject/myapp\"\n * @example \"ghcr.io/myorg/myapp\"\n */\n tag: t.string(),\n\n /**\n * Additional arguments to pass to `docker build`.\n *\n * @example '--platform linux/amd64 --no-cache'\n */\n args: t.optional(t.string()),\n\n /**\n * Auto-add OCI standard labels (revision, created, version).\n *\n * Adds:\n * - org.opencontainers.image.revision (git commit SHA)\n * - org.opencontainers.image.created (build timestamp)\n * - org.opencontainers.image.version (from image tag)\n */\n oci: t.optional(t.boolean()),\n }),\n ),\n }),\n ),\n\n /**\n * Static site deployment configuration.\n *\n * Note: Set `target: \"static\"` to enable static site generation.\n */\n static: t.optional(\n t.object({\n /**\n * Surge domain for deployment.\n *\n * If set, a CNAME file is written to dist/public/.\n * If not set, a domain is auto-generated from package.json name.\n *\n * @example \"my-app.surge.sh\"\n * @example \"my-custom-domain.com\"\n */\n domain: t.optional(t.string()),\n }),\n ),\n\n /**\n * Sitemap generation configuration.\n */\n sitemap: t.optional(\n t.object({\n /**\n * Base URL for sitemap entries.\n */\n hostname: t.string(),\n }),\n ),\n }),\n default: {},\n});\n\n/**\n * Type for build options.\n */\nexport type BuildOptions = Static<typeof buildOptions.schema>;\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Dev options atom for CLI dev command.\n *\n * Defines the available dev configuration options with their defaults.\n * Options can be overridden via alepha.config.ts or CLI flags.\n */\nexport const devOptions = $atom({\n name: \"alepha.cli.dev.options\",\n description: \"Dev configuration options\",\n schema: t.object({\n /**\n * Disable Vite React plugin.\n */\n noViteReactPlugin: t.optional(t.boolean({ default: false })),\n }),\n default: {},\n});\n\n/**\n * Type for dev options.\n */\nexport type DevOptions = Static<typeof devOptions.schema>;\n","import { $inject, $state, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { appEntryOptions } from \"../atoms/appEntryOptions.ts\";\n\n/**\n * Service for locating entry files in Alepha projects.\n *\n * Resolves application entry points for the CLI build pipeline.\n */\nexport class AppEntryProvider {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly options = $state(appEntryOptions);\n\n protected readonly serverEntries = [\n \"main.server.ts\",\n \"main.server.tsx\",\n \"main.ts\",\n \"main.tsx\",\n ] as const;\n\n protected readonly browserEntries = [\n \"main.browser.ts\",\n \"main.browser.tsx\",\n \"main.ts\",\n \"main.tsx\",\n ] as const;\n\n protected readonly styleEntries = [\n \"main.css\",\n \"styles.css\",\n \"style.css\",\n ] as const;\n\n /**\n * Get application entry points.\n *\n * Server entry is required, an error is thrown if not found.\n * Browser entry is optional.\n *\n * It will first check for custom entries in options, see appEntryOptions.\n */\n public async getAppEntry(root: string): Promise<AppEntry> {\n const appEntry: AppEntry = {\n root,\n server: \"\",\n };\n\n if (this.options.server) {\n const serverPath = this.fs.join(root, this.options.server);\n const serverExists = await this.fs.exists(serverPath);\n if (!serverExists) {\n throw new AlephaError(`Custom server entry not found: ${serverPath}`);\n }\n appEntry.server = this.options.server;\n }\n\n if (this.options.browser) {\n const browserPath = this.fs.join(root, this.options.browser);\n const browserExists = await this.fs.exists(browserPath);\n if (!browserExists) {\n throw new AlephaError(`Custom browser entry not found: ${browserPath}`);\n }\n appEntry.browser = this.options.browser;\n }\n\n if (this.options.style) {\n const stylePath = this.fs.join(root, this.options.style);\n const styleExists = await this.fs.exists(stylePath);\n if (!styleExists) {\n throw new AlephaError(`Custom style entry not found: ${stylePath}`);\n }\n appEntry.style = this.options.style;\n }\n\n const srcFiles = await this.fs.ls(this.fs.join(root, \"src\"));\n\n if (!appEntry.server) {\n // find in conventional locations\n for (const entry of this.serverEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.server = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n if (!appEntry.server) {\n const srcDir = this.fs.join(root, \"src\");\n const tried = this.serverEntries\n .map((e) => this.fs.join(srcDir, e))\n .join(\", \");\n throw new AlephaError(\n `No server entry found. Tried: ${tried}. Add a main.server.ts file or configure a custom entry in alepha.config.ts.`,\n );\n }\n\n if (!appEntry.browser) {\n // find in conventional locations\n for (const entry of this.browserEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.browser = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n if (!appEntry.style) {\n // find in conventional locations\n for (const entry of this.styleEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.style = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n return appEntry;\n }\n}\n\nexport interface AppEntry {\n root: string;\n server: string;\n browser?: string;\n style?: string;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { $hook, $inject, type Alepha, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { InlineConfig, Logger, Plugin, ViteDevServer } from \"vite\";\nimport type { AppEntry } from \"../providers/AppEntryProvider.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------------------------------------------\n\ninterface BufferedLogEntry {\n level: \"info\" | \"warn\" | \"error\";\n msg: string;\n timestamp: Date;\n}\n\nexport interface BufferedLogger extends Logger {\n /**\n * Flush all buffered log messages to console.\n * Call this on build failure to show what happened.\n */\n flush(): void;\n\n /**\n * Get all buffered log entries.\n */\n getEntries(): BufferedLogEntry[];\n\n /**\n * Clear all buffered entries without printing.\n */\n clear(): void;\n}\n\n/**\n * Preload manifest mapping short keys to source paths.\n * Generated at build time, consumed by SSRManifestProvider at runtime.\n */\nexport interface PreloadManifest {\n [key: string]: string;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n// ViteUtils\n// -----------------------------------------------------------------------------------------------------------------\n\n/**\n * Vite integration utilities for the Alepha CLI.\n *\n * Centralizes all Vite-specific code: lazy loading, plugin creation,\n * buffered logger, dev server management.\n * When Vite is replaced, only this file needs to change.\n */\nexport class ViteUtils {\n protected readonly fs = $inject(FileSystemProvider);\n protected viteDevServer?: ViteDevServer;\n\n // ---------------------------------------------------------------------------------------------------------------\n // Vite loaders\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Lazy-load Vite (with rolldown-vite fallback).\n */\n public async importVite(): Promise<typeof import(\"vite\")> {\n try {\n return createRequire(import.meta.url)(\"rolldown-vite\");\n } catch {\n try {\n return createRequire(import.meta.url)(\"vite\");\n } catch {\n throw new AlephaError(\n \"Vite is not installed. Please install it with `npm install vite`.\",\n );\n }\n }\n }\n\n /**\n * Lazy-load @vitejs/plugin-react (optional).\n */\n public async importViteReact(): Promise<any> {\n try {\n const { default: viteReact } = createRequire(import.meta.url)(\n \"@vitejs/plugin-react\",\n );\n return viteReact;\n } catch {\n // @vitejs/plugin-react not installed, skip\n }\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // Buffered logger\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Create a Vite logger that buffers all messages instead of printing them.\n * Useful for silent builds that only show output on failure.\n */\n public createBufferedLogger(): BufferedLogger {\n const entries: BufferedLogEntry[] = [];\n const loggedErrors = new WeakSet<Error>();\n const warnedMessages = new Set<string>();\n let hasWarned = false;\n\n const logger: BufferedLogger = {\n get hasWarned() {\n return hasWarned;\n },\n\n info(msg: string) {\n entries.push({ level: \"info\", msg, timestamp: new Date() });\n },\n\n warn(msg: string) {\n hasWarned = true;\n entries.push({ level: \"warn\", msg, timestamp: new Date() });\n },\n\n warnOnce(msg: string) {\n if (warnedMessages.has(msg)) {\n return;\n }\n warnedMessages.add(msg);\n hasWarned = true;\n entries.push({ level: \"warn\", msg, timestamp: new Date() });\n },\n\n error(msg: string, options?: { error?: Error | null }) {\n if (options?.error) {\n loggedErrors.add(options.error);\n }\n entries.push({ level: \"error\", msg, timestamp: new Date() });\n },\n\n clearScreen() {\n // No-op in buffered mode\n },\n\n hasErrorLogged(error: Error): boolean {\n return loggedErrors.has(error);\n },\n\n flush() {\n for (const entry of entries) {\n const prefix =\n entry.level === \"error\"\n ? \"\\x1b[31m✖\\x1b[0m\"\n : entry.level === \"warn\"\n ? \"\\x1b[33m⚠\\x1b[0m\"\n : \"\\x1b[36mℹ\\x1b[0m\";\n console.log(`${prefix} ${entry.msg}`);\n }\n },\n\n getEntries() {\n return [...entries];\n },\n\n clear() {\n entries.length = 0;\n warnedMessages.clear();\n hasWarned = false;\n },\n };\n\n return logger;\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // TSConfig paths plugin\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Vite plugin that reads tsconfig.json `compilerOptions.paths` and converts\n * them to Vite `resolve.alias` entries. Enables `@/*` → `src/*` style imports\n * with zero config beyond tsconfig.json.\n */\n public createTsconfigPathsPlugin(): Plugin {\n return {\n name: \"alepha-tsconfig-paths\",\n async config(config) {\n const root = config.root || process.cwd();\n const tsconfigPath = join(root, \"tsconfig.json\");\n\n let content: string;\n try {\n content = await readFile(tsconfigPath, \"utf-8\");\n } catch {\n return;\n }\n\n // Strip JSONC comments before parsing\n const clean = content\n .replace(/\\/\\/.*$/gm, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n\n let tsconfig: any;\n try {\n tsconfig = JSON.parse(clean);\n } catch {\n return;\n }\n\n const paths = tsconfig?.compilerOptions?.paths;\n if (!paths || typeof paths !== \"object\") return;\n\n const alias: Record<string, string> = {};\n for (const [pattern, targets] of Object.entries(paths)) {\n if (!Array.isArray(targets) || targets.length === 0) continue;\n const target = targets[0] as string;\n const aliasKey = pattern.replace(/\\*$/, \"\");\n const aliasPath = target.replace(/\\*$/, \"\").replace(/^\\.\\//, \"\");\n const resolved = resolve(root, aliasPath);\n alias[aliasKey] = aliasKey.endsWith(\"/\") ? `${resolved}/` : resolved;\n }\n\n if (Object.keys(alias).length === 0) return;\n return { resolve: { alias } };\n },\n };\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // SSR preload plugin\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Vite plugin that generates a preload manifest for SSR module preloading.\n *\n * Collects lazy import paths from $page definitions during transform,\n * generates a manifest mapping short keys to resolved source paths,\n * and injects only the short key into $page definitions.\n */\n public createSsrPreloadPlugin(): Plugin {\n let root = \"\";\n const preloadMap = new Map<string, string>();\n\n function generateKey(sourcePath: string): string {\n return createHash(\"md5\").update(sourcePath).digest(\"hex\").slice(0, 8);\n }\n\n return {\n name: \"alepha-preload\",\n configResolved(config) {\n root = config.root;\n },\n transform(code, id) {\n if (!id.match(/\\.[tj]sx?$/)) return null;\n if (id.includes(\"node_modules\")) return null;\n if (!code.includes(\"$page\") || !code.includes(\"lazy\")) return null;\n\n const insertions: Array<{ position: number; text: string }> = [];\n const pageStartRegex = /\\$page\\s*\\(\\s*\\{/g;\n let pageMatch: RegExpExecArray | null = pageStartRegex.exec(code);\n\n while (pageMatch !== null) {\n const objectStartIndex = pageMatch.index + pageMatch[0].length - 1;\n\n let braceCount = 1;\n let i = objectStartIndex + 1;\n while (i < code.length && braceCount > 0) {\n if (code[i] === \"{\") braceCount++;\n else if (code[i] === \"}\") braceCount--;\n i++;\n }\n\n if (braceCount !== 0) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const objectEndIndex = i - 1;\n const pageContent = code.slice(objectStartIndex, objectEndIndex + 1);\n\n if (pageContent.includes(\"alepha.page.preload\")) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const lazyRegex =\n /lazy\\s*:\\s*\\(\\s*\\)\\s*=>\\s*import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/;\n const lazyMatch = lazyRegex.exec(pageContent);\n\n if (!lazyMatch) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const importPath = lazyMatch[1];\n const currentDir = dirname(id);\n let resolvedPath: string;\n\n if (importPath.startsWith(\".\")) {\n resolvedPath = resolve(currentDir, importPath);\n } else if (importPath.startsWith(\"/\")) {\n resolvedPath = resolve(root, importPath.slice(1));\n } else {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n let relativePath = relative(root, resolvedPath);\n relativePath = relativePath.replace(/\\\\/g, \"/\");\n\n if (!relativePath.match(/\\.[tj]sx?$/)) {\n relativePath = `${relativePath}.tsx`;\n } else if (relativePath.endsWith(\".jsx\")) {\n relativePath = relativePath.replace(/\\.jsx$/, \".tsx\");\n } else if (relativePath.endsWith(\".js\")) {\n relativePath = relativePath.replace(/\\.js$/, \".ts\");\n }\n\n const key = generateKey(relativePath);\n preloadMap.set(key, relativePath);\n\n const beforeBrace = code.slice(0, objectEndIndex).trimEnd();\n const needsComma = !beforeBrace.endsWith(\",\");\n const preloadProperty = `${needsComma ? \",\" : \"\"} [Symbol.for(\"alepha.page.preload\")]: \"${key}\"`;\n\n insertions.push({ position: objectEndIndex, text: preloadProperty });\n pageMatch = pageStartRegex.exec(code);\n }\n\n if (insertions.length === 0) return null;\n\n let result = code;\n for (let j = insertions.length - 1; j >= 0; j--) {\n const { position, text } = insertions[j];\n result = result.slice(0, position) + text + result.slice(position);\n }\n\n return { code: result, map: null };\n },\n writeBundle(options) {\n const outDir = options.dir || \"\";\n if (outDir.includes(\"server\")) return;\n\n if (preloadMap.size > 0) {\n const viteDir = join(outDir, \".vite\");\n if (!existsSync(viteDir)) {\n mkdirSync(viteDir, { recursive: true });\n }\n\n const manifest: PreloadManifest = Object.fromEntries(preloadMap);\n const manifestPath = join(viteDir, \"preload-manifest.json\");\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));\n }\n },\n };\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // HTML template\n // ---------------------------------------------------------------------------------------------------------------\n\n public generateIndexHtml(entry: AppEntry): string {\n const style = entry.style;\n const browser = entry.browser ?? entry.server;\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<title>App</title>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n${style ? `<link rel=\"stylesheet\" href=\"/${style}\" />` : \"\"}\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/${browser}\"></script>\n</body>\n</html>\n`.trim();\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // Dev server management\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * We need to close the Vite dev server after build is done.\n */\n protected onReady = $hook({\n on: \"ready\",\n priority: \"last\",\n handler: async () => {\n await this.viteDevServer?.close();\n },\n });\n\n protected onStop = $hook({\n on: \"stop\",\n handler: async () => {\n await this.viteDevServer?.close();\n },\n });\n\n public async runAlepha(opts: {\n entry: AppEntry;\n mode: \"production\" | \"development\";\n }): Promise<Alepha> {\n const { createServer } = await this.importVite();\n\n process.env.NODE_ENV = opts.mode;\n process.env.ALEPHA_CLI_IMPORT = \"true\"; // signal Alepha App about CLI import, run(alepha) won't start server\n process.env.LOG_LEVEL ??= \"warn\"; // reduce log noise\n process.env.APP_SECRET ??= \"123456\"; // avoid warning about missing secret, not used in CLI context\n\n /**\n * 01/26 Vite 7\n * \"runnerImport\" doesn't work as expected here. (e.g. build docs fail)\n * -> We still use devServer and ssrLoadModule for now.\n * -> This is clearly a bad stuff, we need to find better way.\n */\n this.viteDevServer = await createServer({\n server: { middlewareMode: true },\n appType: \"custom\",\n logLevel: \"silent\",\n plugins: [this.createTsconfigPathsPlugin()],\n } satisfies InlineConfig);\n\n await this.viteDevServer.ssrLoadModule(opts.entry.server);\n\n delete process.env.ALEPHA_CLI_IMPORT;\n\n const alepha: Alepha = (globalThis as any).__alepha;\n if (!alepha) {\n throw new AlephaError(\n \"Alepha instance not found after loading entry module\",\n );\n }\n\n return alepha;\n }\n}\n","import { $inject, type Alepha, AlephaError } from \"alepha\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport type { AppEntry } from \"./AppEntryProvider.ts\";\n\nexport class ViteBuildProvider {\n protected alepha?: Alepha;\n protected appEntry?: AppEntry;\n protected readonly viteUtils = $inject(ViteUtils);\n\n public async init(opts: { entry: AppEntry }) {\n const alepha = await this.viteUtils.runAlepha({\n entry: opts.entry,\n mode: \"production\",\n });\n\n this.alepha = alepha;\n this.appEntry = opts.entry;\n\n return alepha;\n }\n\n public hasClient(): boolean {\n if (!this.alepha) {\n throw new AlephaError(\"ViteBuildProvider not initialized\");\n }\n try {\n this.alepha.inject(\"ReactServerProvider\");\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { $inject, Alepha } from \"alepha\";\nimport { EnvUtils } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider, ShellProvider } from \"alepha/system\";\nimport {\n type AppEntry,\n AppEntryProvider,\n} from \"../providers/AppEntryProvider.ts\";\nimport { ViteUtils } from \"./ViteUtils.ts\";\n\n/**\n * Core utility service for CLI commands.\n *\n * Provides:\n * - Command execution\n * - File editing helpers\n * - Drizzle/ORM utilities\n * - Environment loading\n */\nexport class AlephaCliUtils {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly envUtils = $inject(EnvUtils);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly shell = $inject(ShellProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n protected readonly alepha = $inject(Alepha);\n\n // ===========================================\n // Command Execution\n // ===========================================\n\n /**\n * Execute a command with inherited stdio.\n */\n public async exec(\n command: string,\n options: {\n root?: string;\n env?: Record<string, string>;\n global?: boolean;\n capture?: boolean;\n } = {},\n ): Promise<void> {\n await this.shell.run(command, {\n root: options.root,\n env: options.env,\n resolve: !options.global,\n capture: options.capture,\n });\n }\n\n /**\n * Write a configuration file to node_modules/.alepha directory.\n */\n public async writeConfigFile(\n name: string,\n content: string,\n root = process.cwd(),\n ): Promise<string> {\n const dir = this.fs.join(root, \"node_modules\", \".alepha\");\n\n await this.fs.mkdir(dir, { recursive: true }).catch(() => null);\n\n const path = this.fs.join(dir, name);\n await this.fs.writeFile(path, content);\n\n this.log.debug(`Config file written: ${path}`);\n\n return path;\n }\n\n public async loadAlephaFromServerEntryFile(\n opts: {\n mode: \"production\" | \"development\";\n } & ({ entry: AppEntry } | { root: string }),\n ): Promise<Alepha> {\n let entry: AppEntry;\n if (\"root\" in opts) {\n entry = await this.boot.getAppEntry(opts.root);\n } else {\n entry = opts.entry;\n }\n\n return await this.viteUtils.runAlepha({\n entry,\n mode: opts.mode,\n });\n }\n\n // ===========================================\n // Environment\n // ===========================================\n\n /**\n * Load environment variables from a .env file.\n */\n public async loadEnv(\n root: string,\n files: string[] = [\".env\"],\n ): Promise<void> {\n await this.envUtils.loadEnv(root, files);\n }\n\n // ===========================================\n // Helpers\n // ===========================================\n\n public async exists(root: string, path: string): Promise<boolean> {\n return this.fs.exists(this.fs.join(root, path));\n }\n\n /**\n * Check if a command is installed and available in the system PATH.\n */\n public isInstalledAsync(cmd: string): Promise<boolean> {\n return this.shell.isInstalled(cmd);\n }\n\n /**\n * Get the current git revision (commit SHA).\n *\n * @returns The short commit SHA or \"unknown\" if not in a git repo\n */\n public async getGitRevision(): Promise<string> {\n try {\n const result = await this.shell.run(\"git rev-parse --short HEAD\", {\n capture: true,\n });\n return result.trim();\n } catch {\n return \"unknown\";\n }\n }\n\n /**\n * Get the user's email from git config.\n *\n * @returns The git user email or undefined if not configured\n */\n public async getGitEmail(): Promise<string | undefined> {\n try {\n const result = await this.shell.run(\"git config user.email\", {\n capture: true,\n });\n const email = result.trim();\n return email || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","","import { readFileSync } from \"node:fs\";\n\nconst packageJson = JSON.parse(\n readFileSync(new URL(\"../../../package.json\", import.meta.url), \"utf-8\"),\n);\n\nexport const version = packageJson.version;\n","import { basename } from \"node:path\";\nimport { $inject, Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport alephaPackageJson from \"alepha/package.json\" with { type: \"json\" };\nimport { FileSystemProvider } from \"alepha/system\";\nimport { version } from \"../version.ts\";\n\n/**\n * Context information about a workspace root.\n * Used when initializing a package inside a monorepo.\n */\nexport interface WorkspaceContext {\n /**\n * Whether we're inside a workspace package.\n */\n isPackage: boolean;\n /**\n * The workspace root directory (e.g., ../.. from packages/my-pkg).\n */\n workspaceRoot: string | null;\n /**\n * Package manager detected at workspace root.\n */\n packageManager: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\" | null;\n /**\n * Config files present at workspace root.\n */\n config: {\n biomeJson: boolean;\n editorconfig: boolean;\n tsconfigJson: boolean;\n };\n}\n\n/**\n * Utility service for package manager operations.\n *\n * Handles detection, installation, and cleanup for:\n * - Yarn\n * - npm\n * - pnpm\n * - Bun\n */\nexport class PackageManagerUtils {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly alepha = $inject(Alepha);\n\n /**\n * Detect the package manager used in the project.\n * Checks current directory first, then workspace root if in a monorepo.\n */\n public async getPackageManager(\n root: string,\n pm?: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\",\n ): Promise<\"yarn\" | \"pnpm\" | \"npm\" | \"bun\"> {\n if (pm) return pm;\n if (this.alepha.isBun()) return \"bun\";\n\n // Check current directory first\n if (await this.fs.exists(this.fs.join(root, \"bun.lock\"))) return \"bun\";\n if (await this.fs.exists(this.fs.join(root, \"yarn.lock\"))) return \"yarn\";\n if (await this.fs.exists(this.fs.join(root, \"pnpm-lock.yaml\")))\n return \"pnpm\";\n if (await this.fs.exists(this.fs.join(root, \"package-lock.json\")))\n return \"npm\";\n\n // Check workspace root (for monorepo packages like apps/blog)\n const workspace = await this.getWorkspaceContext(root);\n if (workspace.packageManager) {\n return workspace.packageManager;\n }\n\n return \"npm\";\n }\n\n /**\n * Detect workspace context when inside a monorepo package.\n *\n * Checks if we're inside a workspace package by walking up to 3 levels\n * for workspace indicators like lockfiles and config files.\n * This covers both standard layouts (packages/my-pkg) and deeper nesting\n * (packages/scope/my-pkg).\n *\n * @param root - The current package directory\n * @returns Workspace context with root path, PM, and config presence\n */\n public async getWorkspaceContext(root: string): Promise<WorkspaceContext> {\n const noContext: WorkspaceContext = {\n isPackage: false,\n workspaceRoot: null,\n packageManager: null,\n config: { biomeJson: false, editorconfig: false, tsconfigJson: false },\n };\n\n // Walk up 2–3 levels (covers packages/pkg and packages/scope/pkg)\n for (let depth = 2; depth <= 3; depth++) {\n const segments = Array.from({ length: depth }, () => \"..\");\n const candidate = this.fs.join(root, ...segments);\n\n // Don't check above filesystem root\n if (candidate === root) break;\n\n const result = await this.checkWorkspaceRoot(candidate);\n if (result) return result;\n }\n\n return noContext;\n }\n\n protected async checkWorkspaceRoot(\n candidate: string,\n ): Promise<WorkspaceContext | null> {\n const [hasYarnLock, hasPnpmLock, hasNpmLock, hasBunLock] =\n await Promise.all([\n this.fs.exists(this.fs.join(candidate, \"yarn.lock\")),\n this.fs.exists(this.fs.join(candidate, \"pnpm-lock.yaml\")),\n this.fs.exists(this.fs.join(candidate, \"package-lock.json\")),\n this.fs.exists(this.fs.join(candidate, \"bun.lock\")),\n ]);\n\n const hasLockfile = hasYarnLock || hasPnpmLock || hasNpmLock || hasBunLock;\n if (!hasLockfile) return null;\n\n const [hasBiome, hasEditorConfig, hasTsConfig, hasPackageJson] =\n await Promise.all([\n this.fs.exists(this.fs.join(candidate, \"biome.json\")),\n this.fs.exists(this.fs.join(candidate, \".editorconfig\")),\n this.fs.exists(this.fs.join(candidate, \"tsconfig.json\")),\n this.fs.exists(this.fs.join(candidate, \"package.json\")),\n ]);\n\n if (!hasPackageJson) return null;\n\n let packageManager: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\" | null = null;\n if (hasYarnLock) packageManager = \"yarn\";\n else if (hasPnpmLock) packageManager = \"pnpm\";\n else if (hasBunLock) packageManager = \"bun\";\n else if (hasNpmLock) packageManager = \"npm\";\n\n return {\n isPackage: true,\n workspaceRoot: candidate,\n packageManager,\n config: {\n biomeJson: hasBiome,\n editorconfig: hasEditorConfig,\n tsconfigJson: hasTsConfig,\n },\n };\n }\n\n /**\n * Get the install command for a package.\n */\n public async getInstallCommand(\n root: string,\n packageName: string,\n dev = true,\n ): Promise<string> {\n const pm = await this.getPackageManager(root);\n let cmd: string;\n\n switch (pm) {\n case \"yarn\":\n cmd = `yarn add ${dev ? \"-D\" : \"\"} ${packageName}`;\n break;\n case \"pnpm\":\n cmd = `pnpm add ${dev ? \"-D\" : \"\"} ${packageName}`;\n break;\n case \"bun\":\n cmd = `bun add ${dev ? \"-d\" : \"\"} ${packageName}`;\n break;\n default:\n cmd = `npm install ${dev ? \"--save-dev\" : \"\"} ${packageName}`;\n }\n\n return cmd.replace(/\\s+/g, \" \").trim();\n }\n\n /**\n * Check if a dependency is installed in the project.\n */\n public async hasDependency(\n root: string,\n packageName: string,\n ): Promise<boolean> {\n try {\n const pkg = await this.readPackageJson(root);\n return !!(\n pkg.dependencies?.[packageName] || pkg.devDependencies?.[packageName]\n );\n } catch {\n return false;\n }\n }\n\n /**\n * Check if Expo is present in the project.\n */\n public async hasExpo(root: string): Promise<boolean> {\n return this.hasDependency(root, \"expo\");\n }\n\n /**\n * Check if React is present in the project.\n */\n public async hasReact(root: string): Promise<boolean> {\n return this.hasDependency(root, \"react\");\n }\n\n /**\n * Install a dependency if it's missing from the project.\n * Optionally checks workspace root for the dependency in monorepo setups.\n */\n public async ensureDependency(\n root: string,\n packageName: string,\n options: {\n dev?: boolean;\n /**\n * Also check workspace root for the dependency (for monorepo setups).\n */\n checkWorkspace?: boolean;\n run?: RunnerMethod;\n exec?: (\n cmd: string,\n opts?: { global?: boolean; root?: string },\n ) => Promise<void>;\n } = {},\n ): Promise<void> {\n const { dev = true, checkWorkspace = false } = options;\n\n // Check current package\n if (await this.hasDependency(root, packageName)) {\n this.log.debug(`Dependency '${packageName}' is already installed`);\n return;\n }\n\n // Check workspace root (for monorepo setups)\n if (checkWorkspace) {\n const workspace = await this.getWorkspaceContext(root);\n if (workspace.workspaceRoot) {\n if (await this.hasDependency(workspace.workspaceRoot, packageName)) {\n this.log.debug(\n `Dependency '${packageName}' is already installed in workspace root`,\n );\n return;\n }\n }\n }\n\n const cmd = await this.getInstallCommand(root, packageName, dev);\n\n if (options.run) {\n await options.run(cmd, { alias: `add ${packageName}`, root });\n } else if (options.exec) {\n this.log.debug(`Installing ${packageName}`);\n await options.exec(cmd, { global: true, root });\n }\n }\n\n // ===========================================\n // Package Manager Setup & Cleanup\n // ===========================================\n\n public async ensureYarn(root: string): Promise<void> {\n const yarnrcPath = this.fs.join(root, \".yarnrc.yml\");\n if (!(await this.fs.exists(yarnrcPath))) {\n await this.fs.writeFile(yarnrcPath, \"nodeLinker: node-modules\");\n }\n await this.removeAllPmFilesExcept(root, \"yarn\");\n }\n\n public async ensureBun(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"bun\");\n }\n\n public async ensurePnpm(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"pnpm\");\n }\n\n public async ensureNpm(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"npm\");\n }\n\n public async removeAllPmFilesExcept(\n root: string,\n except: string,\n ): Promise<void> {\n if (except !== \"yarn\") await this.removeYarn(root);\n if (except !== \"pnpm\") await this.removePnpm(root);\n if (except !== \"npm\") await this.removeNpm(root);\n if (except !== \"bun\") await this.removeBun(root);\n }\n\n public async removeYarn(root: string): Promise<void> {\n await this.removeFiles(root, [\".yarn\", \".yarnrc.yml\", \"yarn.lock\"]);\n await this.editPackageJson(root, (pkg) => {\n delete pkg.packageManager;\n return pkg;\n });\n }\n\n public async removePnpm(root: string): Promise<void> {\n await this.removeFiles(root, [\"pnpm-lock.yaml\", \"pnpm-workspace.yaml\"]);\n await this.editPackageJson(root, (pkg) => {\n delete pkg.packageManager;\n return pkg;\n });\n }\n\n public async removeNpm(root: string): Promise<void> {\n await this.removeFiles(root, [\"package-lock.json\"]);\n }\n\n public async removeBun(root: string): Promise<void> {\n await this.removeFiles(root, [\"bun.lockb\", \"bun.lock\"]);\n }\n\n // ===========================================\n // Package.json utilities\n // ===========================================\n\n public async readPackageJson(root: string): Promise<Record<string, any>> {\n const content = await this.fs\n .createFile({ path: this.fs.join(root, \"package.json\") })\n .text();\n return JSON.parse(content);\n }\n\n public async writePackageJson(\n root: string,\n content: Record<string, any>,\n ): Promise<void> {\n await this.fs.writeFile(\n this.fs.join(root, \"package.json\"),\n JSON.stringify(content, null, 2),\n );\n }\n\n public async editPackageJson(\n root: string,\n editFn: (pkg: Record<string, any>) => Record<string, any>,\n ): Promise<void> {\n try {\n const pkg = await this.readPackageJson(root);\n const updated = editFn(pkg);\n await this.writePackageJson(root, updated);\n } catch {\n // package.json doesn't exist, skip\n }\n }\n\n public async ensurePackageJson(\n root: string,\n modes: DependencyModes,\n ): Promise<Record<string, any>> {\n const packageJsonPath = this.fs.join(root, \"package.json\");\n\n if (!(await this.fs.exists(packageJsonPath))) {\n const dirName = basename(root) || \"app\";\n const content = {\n name: dirName,\n private: true,\n ...this.generatePackageJsonContent(modes),\n };\n await this.writePackageJson(root, content);\n return content;\n }\n\n const packageJson = await this.readPackageJson(root);\n const newContent = this.generatePackageJsonContent(modes);\n\n packageJson.type = \"module\";\n packageJson.dependencies ??= {};\n packageJson.devDependencies ??= {};\n packageJson.scripts ??= {};\n\n Object.assign(packageJson.dependencies, newContent.dependencies);\n Object.assign(packageJson.devDependencies, newContent.devDependencies);\n Object.assign(packageJson.scripts, newContent.scripts);\n\n await this.writePackageJson(root, packageJson);\n return packageJson;\n }\n\n public generatePackageJsonContent(modes: DependencyModes): {\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n scripts: Record<string, string>;\n type: \"module\";\n } {\n const alephaDeps = alephaPackageJson.devDependencies;\n\n const dependencies: Record<string, string> = {\n alepha: `^${version}`,\n };\n\n const devDependencies: Record<string, string> = {\n vite: alephaDeps.vite,\n };\n\n // Only include drizzle-kit when the project uses a database.\n // React-only projects (--react without --api/--saas) don't need it.\n const isReactOnly = modes.react && !modes.ui;\n if (!isReactOnly) {\n devDependencies[\"drizzle-kit\"] = alephaDeps[\"drizzle-kit\"];\n }\n\n // Add biome/vitest only if not a workspace package (workspace root has them)\n if (!modes.isPackage) {\n devDependencies[\"@biomejs/biome\"] = alephaDeps[\"@biomejs/biome\"];\n if (modes.test) {\n devDependencies.vitest = alephaDeps.vitest;\n }\n }\n\n const scripts: Record<string, string> = {\n dev: \"alepha dev\",\n build: \"alepha build\",\n lint: \"alepha lint\",\n typecheck: \"alepha typecheck\",\n verify: \"alepha verify\",\n };\n\n if (modes.test) {\n scripts.test = \"vitest run\";\n }\n\n if (modes.ui) {\n dependencies[\"@alepha/ui\"] = `^${version}`;\n modes.react = true;\n }\n\n if (modes.tailwind) {\n devDependencies.tailwindcss = \"^4.2.0\";\n devDependencies[\"@tailwindcss/vite\"] = \"^4.2.0\";\n }\n\n if (modes.react) {\n dependencies.react = alephaDeps.react;\n dependencies[\"react-dom\"] = alephaDeps[\"react-dom\"];\n devDependencies[\"@types/react\"] = alephaDeps[\"@types/react\"];\n }\n\n return {\n type: \"module\",\n dependencies,\n devDependencies,\n scripts,\n };\n }\n\n // ===========================================\n // Helper methods\n // ===========================================\n\n protected async removeFiles(root: string, files: string[]): Promise<void> {\n await Promise.all(\n files.map((file) =>\n this.fs.rm(this.fs.join(root, file), { force: true, recursive: true }),\n ),\n );\n }\n}\n\nexport interface DependencyModes {\n react?: boolean;\n ui?: boolean;\n expo?: boolean;\n tailwind?: boolean;\n test?: boolean;\n /**\n * Skip biome/vitest when inside a workspace package (they're at root).\n */\n isPackage?: boolean;\n}\n","import { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst packageRoot = join(fileURLToPath(import.meta.url), \"../../../..\");\n\nexport const cliAssets = {\n logo: join(packageRoot, \"assets/logo.svg\"),\n};\n","export type AgentMdType = \"claude\" | \"agents\";\n\nexport interface AgentMdOptions {\n type: AgentMdType;\n ui?: boolean;\n}\n\nexport const agentMd = (options: AgentMdOptions): string => {\n const header = options.type === \"claude\" ? `# CLAUDE.md` : `# AGENTS.md`;\n\n const docs = [`- Framework source: \\`node_modules/alepha/src/\\``];\n if (options.ui) {\n docs.push(`- UI components: \\`node_modules/@alepha/ui/src/\\``);\n }\n docs.push(`- Docs: https://alepha.dev/llms.txt`);\n\n return `${header}\n\nThis is an **Alepha** project.\n\n## Rules\n\n- Always check \\`node_modules/alepha/src/\\` before suggesting npm packages\n- Use \\`t\\` from Alepha for schemas (not Zod)\n- Use \\`protected\\` instead of \\`private\\` for class members\n- Import with file extensions: \\`import { User } from \"./User.ts\"\\`\n\n## Commands\n\n\\`\\`\\`bash\nalepha lint # Format and lint\nalepha typecheck # Type checking\nalepha test # Run tests\nalepha build # Build\n\\`\\`\\`\n\n## Documentation\n\n${docs.join(\"\\n\")}\n`.trim();\n};\n","/**\n * Template for alepha.config.ts with documented options.\n */\nexport const alephaConfigTs = () => {\n return `import { defineConfig } from \"alepha/cli/config\";\n\nexport default defineConfig({\n //\n // entry: {\n // server: \"src/main.server.ts\",\n // browser: \"src/main.browser.ts\",\n // style: \"src/main.css\",\n // },\n //\n // build: {\n // target: \"docker\",\n // runtime: \"node\",\n // },\n //\n // env: {\n // VITE_BUILD_DATE: new Date().toISOString(),\n // VITE_VERSION: pkg.version,\n // },\n});\n`;\n};\n","export const apiAppSecurityTs = (opts: { adminEmail?: string } = {}) => {\n const adminEmailsValue = opts.adminEmail ? `[\"${opts.adminEmail}\"]` : \"[]\";\n\n return `\nimport { $realm } from \"alepha/api/users\";\n\nexport class AppSecurity {\n users = $realm({\n settings: {\n // Auto-promote these users to admin on login\n adminEmails: ${adminEmailsValue},\n adminUsernames: [],\n\n // Registration & login options\n registrationAllowed: true,\n email: \"required\",\n username: \"none\",\n phoneNumber: \"none\",\n\n // Verification (requires notifications feature)\n verifyEmailRequired: false,\n verifyPhoneRequired: false,\n resetPasswordAllowed: false,\n },\n features: {\n // Enable additional features\n notifications: false,\n audits: false,\n apiKeys: false,\n sessionPurge: false,\n avatars: false,\n parameters: false,\n },\n identities: {\n // Enable authentication providers\n credentials: true,\n // google: true,\n // github: true,\n },\n });\n}\n`.trim();\n};\n","export interface ApiHelloControllerOptions {\n appName?: string;\n}\n\nexport const apiHelloControllerTs = (\n options: ApiHelloControllerOptions = {},\n) => {\n const appName = options.appName || \"my-app\";\n const appNameCapitalized = appName\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n\n return `import { $action } from \"alepha/server\";\nimport { helloResponseSchema } from \"../schemas/helloResponseSchema.ts\";\n\nexport class HelloController {\n\n hello = $action({\n path: \"/hello\",\n schema: {\n response: helloResponseSchema,\n },\n handler: () => ({\n appName: \"${appNameCapitalized}\",\n serverTime: new Date().toISOString(),\n }),\n });\n}\n`.trim();\n};\n","export const apiHelloResponseSchemaTs = () => {\n return `import { type Static, t } from \"alepha\";\n\nexport const helloResponseSchema = t.object({\n appName: t.text(),\n serverTime: t.datetime(),\n});\n\nexport type HelloResponse = Static<typeof helloResponseSchema>;\n`.trim();\n};\n","export interface ApiIndexTsOptions {\n appName?: string;\n auth?: boolean;\n}\n\nexport const apiIndexTs = (options: ApiIndexTsOptions = {}) => {\n const { appName = \"app\", auth = false } = options;\n\n const imports: string[] = ['import { $module } from \"alepha\";'];\n const services: string[] = [];\n\n if (auth) {\n imports.push('import { AppSecurity } from \"./AppSecurity.ts\";');\n services.push(\"AppSecurity\");\n }\n\n imports.push(\n 'import { HelloController } from \"./controllers/HelloController.ts\";',\n );\n services.push(\"HelloController\");\n\n return `\n${imports.join(\"\\n\")}\n\nexport const ApiModule = $module({\n name: \"${appName}.api\",\n services: [${services.join(\", \")}],\n});\n`.trim();\n};\n","export const biomeJson = () =>\n `\n{\n \"$schema\": \"https://biomejs.dev/schemas/latest/schema.json\",\n \"vcs\": {\n \"enabled\": true,\n \"clientKind\": \"git\"\n },\n \"files\": {\n \"ignoreUnknown\": true,\n \"includes\": [\"**\", \"!node_modules\", \"!dist\"]\n },\n \"formatter\": {\n \"enabled\": true,\n \"useEditorconfig\": true\n },\n \"linter\": {\n \"enabled\": true,\n \"rules\": {\n \"recommended\": true\n },\n \"domains\": {\n \"react\": \"recommended\"\n }\n },\n \"assist\": {\n \"actions\": {\n \"source\": {\n \"organizeImports\": \"on\"\n }\n }\n }\n}\n`.trim();\n","export const dummySpecTs = () =>\n `\nimport { test, expect } from \"vitest\";\n\ntest(\"dummy test\", () => {\n expect(1 + 1).toBe(2);\n});\n`.trim();\n","export const editorconfig = () =>\n `\n# https://editorconfig.org\n\nroot = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nindent_style = space\nindent_size = 2\n`.trim();\n","export const gitignore = () =>\n `\n# Dependencies\nnode_modules/\n\n# Build outputs\ndist/\n.vite/\n\n# Environment files\n.env\n.env.*\n!.env.example\n\n# IDE\n.idea/\n*.swp\n*.swo\n\n# OS\n.DS_Store\nThumbs.db\n\n# Logs\n*.log\nlogs/\n\n# Test coverage\ncoverage/\n\n# Yarn\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n`.trim();\n","export const mainBrowserTs = () =>\n `\nimport { Alepha, run } from \"alepha\";\nimport { WebModule } from \"./web/index.ts\";\n\nconst alepha = Alepha.create();\n\nalepha.with(WebModule);\n\nrun(alepha);\n`.trim();\n","export const mainCss = (opts: { ui?: boolean; tailwind?: boolean } = {}) => {\n if (opts.ui) {\n return `/**\n * Alepha UI - Based on Mantine component library\n * Mantine Docs: https://mantine.dev\n * Mantine LLM context: https://mantine.dev/llms.txt\n *\n * Switch theme index: alepha.set(alephaThemeAtom, { index: 1 })\n *\n * Custom themes (in src/web/index.ts):\n *\n * import { alephaThemeListAtom } from \"@alepha/ui\";\n *\n * export const WebModule = $module({\n * name: \"app.web\",\n * services: [AppRouter],\n * register(alepha) {\n * alepha.register(AppRouter);\n * alepha.set(alephaThemeListAtom, [{\n * name: \"My Theme\",\n * description: \"Custom theme\",\n * primaryColor: \"blue\",\n * defaultColorScheme: \"dark\",\n * // ...MantineThemeOverride options\n * }]);\n * },\n * });\n *\n * Alternatives (remove the import below):\n * - Tailwind CSS: https://tailwindcss.com/docs/installation/using-vite\n * - Raw CSS: Write your own styles\n */\n@import \"@alepha/ui/styles\";`;\n }\n\n if (opts.tailwind) {\n return `@import \"tailwindcss\";\n\n/* Add your styles here */\n`;\n }\n\n return `/**\n * Global styles for your application.\n *\n * Options:\n * - @alepha/ui: Use \\`alepha init --ui\\` to add Mantine-based components\n * - Tailwind CSS: Use \\`alepha init --tailwind\\` to add Tailwind CSS\n * - Raw CSS: Write your own styles below\n */\n\n/* Add your styles here */\n`;\n};\n","export interface MainServerTsOptions {\n api?: boolean;\n react?: boolean;\n}\n\nexport const mainServerTs = (options: MainServerTsOptions = {}) => {\n const { api = false, react = false } = options;\n\n const imports: string[] = [];\n const withs: string[] = [];\n\n if (api) {\n imports.push(`import { ApiModule } from \"./api/index.ts\";`);\n withs.push(`alepha.with(ApiModule);`);\n }\n\n if (react) {\n imports.push(`import { WebModule } from \"./web/index.ts\";`);\n withs.push(`alepha.with(WebModule);`);\n }\n\n const importsBlock = imports.length > 0 ? `${imports.join(\"\\n\")}\\n` : \"\";\n const withsBlock = withs.length > 0 ? `\\n${withs.join(\"\\n\")}` : \"\";\n\n return `\nimport { Alepha, run } from \"alepha\";\n${importsBlock}\nconst alepha = Alepha.create();\n${withsBlock}\n\nrun(alepha);\n`.trim();\n};\n","export const tsconfigJson = () =>\n `\n{\n \"extends\": \"alepha/tsconfig.base\",\n \"compilerOptions\": {\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n }\n}\n`.trim();\n","export const viteConfigTs = () => {\n return `import tailwindcss from \"@tailwindcss/vite\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n plugins: [tailwindcss()],\n});\n`;\n};\n","export const webAdminDashboardTsx = () => {\n return `import { Flex, Text } from \"@alepha/ui\";\n\nconst AdminDashboard = () => {\n return (\n <Flex direction=\"column\" align=\"center\" justify=\"center\" mih=\"60vh\" gap=\"md\">\n <Text size=\"xl\" fw={600}>\n Admin Panel\n </Text>\n <Text c=\"dimmed\">Welcome to the admin panel.</Text>\n </Flex>\n );\n};\n\nexport default AdminDashboard;\n`;\n};\n","export const webAppRouterTs = (options: {\n api?: boolean;\n ui?: boolean;\n auth?: boolean;\n admin?: boolean;\n}) => {\n const imports: string[] = [];\n const classMembers: string[] = [];\n\n // UI import and setup\n if (options.ui) {\n imports.push('import { $ui } from \"@alepha/ui\";');\n }\n\n // Auth import\n if (options.auth) {\n imports.push('import { $uiAuth } from \"@alepha/ui/auth\";');\n }\n\n // Admin imports\n if (options.admin) {\n imports.push('import { $uiAdmin } from \"@alepha/ui/admin\";');\n imports.push('import { AdminUserRouter } from \"@alepha/ui/admin-users\";');\n imports.push(\n 'import { AdminSessionRouter } from \"@alepha/ui/admin-sessions\";',\n );\n imports.push('import { AdminAuditRouter } from \"@alepha/ui/admin-audits\";');\n imports.push('import { AdminFileRouter } from \"@alepha/ui/admin-files\";');\n imports.push(\n 'import { AdminParameterRouter } from \"@alepha/ui/admin-parameters\";',\n );\n imports.push('import { AdminJobRouter } from \"@alepha/ui/admin-jobs\";');\n imports.push('import { AdminApiKeyRouter } from \"@alepha/ui/admin-keys\";');\n imports.push(\n 'import { AdminNotificationRouter } from \"@alepha/ui/admin-notifications\";',\n );\n imports.push(\n 'import { AdminBillingRouter } from \"@alepha/ui/admin-billing\";',\n );\n imports.push('import { $inject } from \"alepha\";');\n imports.push(\n 'import { IconLayoutDashboard, IconLockPassword, IconCreditCard } from \"@tabler/icons-react\";',\n );\n }\n\n // Page import\n imports.push('import { $page } from \"alepha/react/router\";');\n\n // API imports (only if api flag is set)\n if (options.api) {\n imports.push('import { $client } from \"alepha/server/links\";');\n imports.push(\n 'import type { HelloController } from \"../api/controllers/HelloController.ts\";',\n );\n classMembers.push(\" api = $client<HelloController>();\");\n }\n\n // UI layout setup\n if (options.ui) {\n classMembers.push(\" ui = $ui();\");\n\n if (options.auth) {\n classMembers.push(\" uiAuth = $uiAuth();\");\n }\n\n if (options.admin) {\n classMembers.push(` // ── Admin Domain Routers ──────────────────────────\n protected users = $inject(AdminUserRouter);\n protected sessions = $inject(AdminSessionRouter);\n protected audits = $inject(AdminAuditRouter);\n protected files = $inject(AdminFileRouter);\n protected parameters = $inject(AdminParameterRouter);\n protected jobs = $inject(AdminJobRouter);\n protected apiKeys = $inject(AdminApiKeyRouter);\n protected notifications = $inject(AdminNotificationRouter);\n protected billing = $inject(AdminBillingRouter);\n\n // ── Admin Panel ─────────────────────────────────\n admin = $uiAdmin({\n pages: [\n this.users.adminUsers,\n this.sessions.adminSessions,\n this.audits.adminAudits,\n this.files.adminFiles,\n this.parameters.adminParameters,\n this.jobs.adminJobs,\n this.apiKeys.adminApiKeys,\n this.notifications.adminNotifications,\n this.billing.adminBilling,\n ],\n sidebarItems: [\n {\n label: \"Security\",\n children: [\n { label: \"Identity\", icon: IconLockPassword, children: [\n this.users.adminUsers,\n this.sessions.adminSessions,\n this.apiKeys.adminApiKeys,\n ]},\n this.audits.adminAudits,\n ],\n },\n {\n label: \"System\",\n children: [\n this.files.adminFiles,\n this.jobs.adminJobs,\n this.notifications.adminNotifications,\n this.parameters.adminParameters,\n ],\n },\n {\n label: \"Commerce\",\n icon: IconCreditCard,\n children: [\n this.billing.adminBilling,\n ],\n },\n ],\n });\n\n // ── Admin Dashboard ─────────────────────────────\n adminDashboard = $page({\n parent: this.admin.adminLayout,\n path: \"/\",\n label: \"Dashboard\",\n icon: IconLayoutDashboard,\n lazy: () => import(\"./components/AdminDashboard.tsx\"),\n });`);\n }\n\n classMembers.push(` layout = $page({\n parent: this.ui.root,\n children: () => [this.home],\n });`);\n }\n\n // Home page - with or without loader\n if (options.api) {\n classMembers.push(` home = $page({\n path: \"/\",\n lazy: () => import(\"./components/Home.tsx\"),\n loader: () => this.api.hello(),\n });`);\n } else {\n classMembers.push(` home = $page({\n path: \"/\",\n lazy: () => import(\"./components/Home.tsx\"),\n });`);\n }\n\n return `${imports.join(\"\\n\")}\n\nexport class AppRouter {\n${classMembers.join(\"\\n\\n\")}\n}`;\n};\n","export interface WebHomeComponentOptions {\n api?: boolean;\n}\n\nexport const webHomeComponentTsx = (options: WebHomeComponentOptions = {}) => {\n if (options.api) {\n return `import { GettingStarted } from \"alepha/react/intro\";\n\ntype Props = {\n appName: string;\n serverTime: string;\n}\n\nconst Home = (props: Props) => {\n return <GettingStarted welcome={props} />;\n};\n\nexport default Home;\n`;\n }\n\n return `import { GettingStarted } from \"alepha/react/intro\";\n\nconst Home = () => {\n return <GettingStarted />;\n};\n\nexport default Home;\n`;\n};\n","export interface WebIndexTsOptions {\n appName?: string;\n}\n\nexport const webIndexTs = (options: WebIndexTsOptions = {}) => {\n const { appName = \"app\" } = options;\n return `\nimport { $module } from \"alepha\";\nimport { AppRouter } from \"./AppRouter.ts\";\n\nexport const WebModule = $module({\n name: \"${appName}.web\",\n services: [AppRouter],\n});\n`.trim();\n};\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport { $inject, AlephaError } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { cliAssets } from \"../assets.ts\";\nimport { type AgentMdOptions, agentMd } from \"../templates/agentMd.ts\";\nimport { alephaConfigTs } from \"../templates/alephaConfigTs.ts\";\nimport { apiAppSecurityTs } from \"../templates/apiAppSecurityTs.ts\";\nimport { apiHelloControllerTs } from \"../templates/apiHelloControllerTs.ts\";\nimport { apiHelloResponseSchemaTs } from \"../templates/apiHelloResponseSchemaTs.ts\";\nimport { apiIndexTs } from \"../templates/apiIndexTs.ts\";\nimport { biomeJson } from \"../templates/biomeJson.ts\";\nimport { dummySpecTs } from \"../templates/dummySpecTs.ts\";\nimport { editorconfig } from \"../templates/editorconfig.ts\";\nimport { gitignore } from \"../templates/gitignore.ts\";\nimport { mainBrowserTs } from \"../templates/mainBrowserTs.ts\";\nimport { mainCss } from \"../templates/mainCss.ts\";\nimport { mainServerTs } from \"../templates/mainServerTs.ts\";\nimport { tsconfigJson } from \"../templates/tsconfigJson.ts\";\nimport { viteConfigTs } from \"../templates/viteConfigTs.ts\";\nimport { webAdminDashboardTsx } from \"../templates/webAdminDashboardTsx.ts\";\nimport { webAppRouterTs } from \"../templates/webAppRouterTs.ts\";\nimport { webHomeComponentTsx } from \"../templates/webHomeComponentTsx.ts\";\nimport { webIndexTs } from \"../templates/webIndexTs.ts\";\nimport { AlephaCliUtils } from \"./AlephaCliUtils.ts\";\nimport {\n type DependencyModes,\n PackageManagerUtils,\n} from \"./PackageManagerUtils.ts\";\n\n/**\n * Service for scaffolding new Alepha projects.\n *\n * Handles creation of:\n * - Project structure (src/api, src/web)\n * - Configuration files (tsconfig, biome, editorconfig)\n * - Entry points (main.server.ts, main.browser.ts)\n * - Example code (HelloController, Home component)\n */\nexport class ProjectScaffolder {\n protected readonly log = $logger();\n protected readonly colors = $inject(ConsoleColorProvider);\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly utils = $inject(AlephaCliUtils);\n\n /**\n * Get the app name from the directory name.\n *\n * Converts the directory name to a valid module name:\n * - Converts to lowercase\n * - Replaces spaces, dashes, underscores with nothing\n * - Falls back to \"app\" if empty\n */\n public getAppName(root: string): string {\n const dirName = basename(root);\n const appName = dirName.toLowerCase().replace(/[\\s\\-_.\\d]/g, \"\");\n return appName || \"app\";\n }\n\n /**\n * Ensure all configuration files exist.\n */\n public async ensureConfig(\n root: string,\n opts: {\n force?: boolean;\n /**\n * Check workspace root for existing config files.\n */\n checkWorkspace?: boolean;\n packageJson?: boolean | DependencyModes;\n tsconfigJson?: boolean;\n biomeJson?: boolean;\n editorconfig?: boolean;\n agentMd?: false | AgentMdOptions;\n },\n ): Promise<void> {\n const tasks: Promise<void>[] = [];\n const force = opts.force ?? false;\n const checkWorkspace = opts.checkWorkspace ?? false;\n\n if (opts.packageJson) {\n tasks.push(\n this.pm\n .ensurePackageJson(\n root,\n typeof opts.packageJson === \"boolean\" ? {} : opts.packageJson,\n )\n .then(() => {}),\n );\n }\n if (opts.tsconfigJson) {\n tasks.push(this.ensureTsConfig(root, { force }));\n }\n if (opts.biomeJson) {\n tasks.push(this.ensureBiomeConfig(root, { force, checkWorkspace }));\n }\n if (opts.editorconfig) {\n tasks.push(this.ensureEditorConfig(root, { force, checkWorkspace }));\n }\n if (opts.agentMd) {\n tasks.push(this.ensureAgentMd(root, { ...opts.agentMd, force }));\n }\n\n await Promise.all(tasks);\n }\n\n // ===========================================\n // Config Files\n // ===========================================\n\n public async ensureTsConfig(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<void> {\n // Check if tsconfig.json exists in current or parent directories\n if (!opts.force && (await this.existsInParents(root, \"tsconfig.json\"))) {\n return;\n }\n await this.fs.writeFile(\n this.fs.join(root, \"tsconfig.json\"),\n tsconfigJson(),\n );\n }\n\n public async ensureBiomeConfig(\n root: string,\n opts: { force?: boolean; checkWorkspace?: boolean } = {},\n ): Promise<void> {\n if (\n !opts.force &&\n opts.checkWorkspace &&\n (await this.existsInParents(root, \"biome.json\"))\n ) {\n return;\n }\n await this.ensureFile(root, \"biome.json\", biomeJson(), opts.force);\n }\n\n public async ensureEditorConfig(\n root: string,\n opts: { force?: boolean; checkWorkspace?: boolean } = {},\n ): Promise<void> {\n if (\n !opts.force &&\n opts.checkWorkspace &&\n (await this.existsInParents(root, \".editorconfig\"))\n ) {\n return;\n }\n await this.ensureFile(root, \".editorconfig\", editorconfig(), opts.force);\n }\n\n /**\n * Ensure git repository is initialized with .gitignore.\n *\n * @returns true if git was initialized, false if already exists or git unavailable\n */\n public async ensureGitRepo(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<boolean> {\n const gitDir = this.fs.join(root, \".git\");\n\n // Skip if .git already exists\n if (!opts.force && (await this.fs.exists(gitDir))) {\n return false;\n }\n\n // Check if git is available\n const hasGit = await this.utils.isInstalledAsync(\"git\");\n if (!hasGit) {\n return false;\n }\n\n // Initialize git repository\n await this.utils.exec(\"git init\", { root, global: true });\n\n // Write .gitignore\n await this.ensureFile(root, \".gitignore\", gitignore(), opts.force);\n\n return true;\n }\n\n public async ensureAgentMd(\n root: string,\n options: AgentMdOptions & { force?: boolean },\n ): Promise<void> {\n const filename = options.type === \"claude\" ? \"CLAUDE.md\" : \"AGENTS.md\";\n await this.ensureFile(root, filename, agentMd(options), options.force);\n }\n\n /**\n * Ensure alepha.config.ts exists with documented options.\n */\n public async ensureAlephaConfig(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<void> {\n await this.ensureFile(\n root,\n \"alepha.config.ts\",\n alephaConfigTs(),\n opts.force,\n );\n }\n\n // ===========================================\n // Minimal Project Structure\n // ===========================================\n\n /**\n * Ensure src/main.server.ts exists with correct module imports.\n */\n public async ensureMainServerTs(\n root: string,\n opts: { api?: boolean; react?: boolean; force?: boolean } = {},\n ): Promise<void> {\n const srcDir = this.fs.join(root, \"src\");\n await this.fs.mkdir(srcDir, { recursive: true });\n await this.ensureFile(\n srcDir,\n \"main.server.ts\",\n mainServerTs({ api: opts.api, react: opts.react }),\n opts.force,\n );\n }\n\n // ===========================================\n // API Project Structure\n // ===========================================\n\n /**\n * Ensure API module structure exists.\n *\n * Creates:\n * - src/api/index.ts (API module)\n * - src/api/controllers/HelloController.ts (example controller)\n */\n public async ensureApiProject(\n root: string,\n opts: { auth?: boolean; adminEmail?: string; force?: boolean } = {},\n ): Promise<void> {\n const appName = this.getAppName(root);\n\n // Create directories\n await this.fs.mkdir(this.fs.join(root, \"src/api/controllers\"), {\n recursive: true,\n });\n await this.fs.mkdir(this.fs.join(root, \"src/api/schemas\"), {\n recursive: true,\n });\n\n // Create files\n await this.ensureFile(\n root,\n \"src/api/index.ts\",\n apiIndexTs({ appName, auth: opts.auth }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/api/controllers/HelloController.ts\",\n apiHelloControllerTs({ appName }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/api/schemas/helloResponseSchema.ts\",\n apiHelloResponseSchemaTs(),\n opts.force,\n );\n\n // Create AppSecurity if auth is enabled\n if (opts.auth) {\n await this.ensureFile(\n root,\n \"src/api/AppSecurity.ts\",\n apiAppSecurityTs({ adminEmail: opts.adminEmail }),\n opts.force,\n );\n }\n }\n\n // ===========================================\n // Web Project Structure\n // ===========================================\n\n /**\n * Ensure web/React project structure exists.\n *\n * Creates:\n * - src/main.browser.ts\n * - src/main.css\n * - src/web/index.ts, src/web/AppRouter.ts, src/web/components/Home.tsx\n */\n public async ensureWebProject(\n root: string,\n opts: {\n api?: boolean;\n ui?: boolean;\n auth?: boolean;\n admin?: boolean;\n tailwind?: boolean;\n force?: boolean;\n } = {},\n ): Promise<void> {\n const appName = this.getAppName(root);\n\n // Create directories\n await this.fs.mkdir(this.fs.join(root, \"src/web/components\"), {\n recursive: true,\n });\n\n // public/favicon.svg\n await this.fs.mkdir(this.fs.join(root, \"public\"), { recursive: true });\n const logoSvg = (await readFile(cliAssets.logo)).toString();\n await this.ensureFile(root, \"public/favicon.svg\", logoSvg, opts.force);\n\n // src/main.css\n await this.ensureFile(\n root,\n \"src/main.css\",\n mainCss({ ui: opts.ui, tailwind: opts.tailwind }),\n opts.force,\n );\n\n // vite.config.ts (Tailwind CSS plugin)\n if (opts.tailwind) {\n await this.ensureFile(root, \"vite.config.ts\", viteConfigTs(), opts.force);\n }\n\n // Web structure\n await this.ensureFile(\n root,\n \"src/web/index.ts\",\n webIndexTs({ appName }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/AppRouter.ts\",\n webAppRouterTs({\n api: opts.api,\n ui: opts.ui,\n auth: opts.auth,\n admin: opts.admin,\n }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/Home.tsx\",\n webHomeComponentTsx({ api: opts.api }),\n opts.force,\n );\n if (opts.admin) {\n await this.ensureFile(\n root,\n \"src/web/components/AdminDashboard.tsx\",\n webAdminDashboardTsx(),\n opts.force,\n );\n }\n await this.ensureFile(\n root,\n \"src/main.browser.ts\",\n mainBrowserTs(),\n opts.force,\n );\n }\n\n // ===========================================\n // Test Directory\n // ===========================================\n\n /**\n * Ensure test directory exists with a dummy test file.\n */\n public async ensureTestDir(root: string): Promise<void> {\n const testDir = this.fs.join(root, \"test\");\n const dummyPath = this.fs.join(testDir, \"dummy.spec.ts\");\n\n if (!(await this.fs.exists(testDir))) {\n await this.fs.mkdir(testDir, { recursive: true });\n await this.fs.writeFile(dummyPath, dummySpecTs());\n return;\n }\n\n const files = await this.fs.ls(testDir);\n if (files.length === 0) {\n await this.fs.writeFile(dummyPath, dummySpecTs());\n }\n }\n\n // ===========================================\n // Full Init Orchestration\n // ===========================================\n\n /**\n * Full project init — scaffolds files, installs deps, sets up PM and git.\n */\n async init({\n run,\n root,\n flags,\n args,\n }: {\n run: RunnerMethod;\n root: string;\n flags: {\n pm?: \"yarn\" | \"npm\" | \"pnpm\" | \"bun\";\n api?: boolean;\n react?: boolean;\n ui?: boolean;\n saas?: boolean;\n tailwind?: boolean;\n test?: boolean;\n force?: boolean;\n };\n args?: string;\n }) {\n if (args) {\n root = this.fs.join(root, args);\n await this.fs.mkdir(root, { force: true });\n }\n\n // Flag cascading: --saas → --api + --ui → --react\n if (flags.saas) {\n flags.api = true;\n flags.ui = true;\n }\n if (flags.ui) {\n flags.react = true;\n }\n if (flags.tailwind) {\n flags.react = true;\n }\n\n // When codegen flags are set, target directory must be empty (unless --force)\n const hasCodegenFlags =\n flags.saas || flags.api || flags.ui || flags.react || flags.tailwind;\n if (hasCodegenFlags && !flags.force) {\n const files = await this.fs.ls(root);\n // Allow a directory that only has package.json (common for monorepo packages)\n const meaningful = files.filter((f) => f !== \"package.json\");\n if (meaningful.length > 0) {\n throw new AlephaError(\n `Target directory is not empty (${root}). Use --force to overwrite existing files.`,\n );\n }\n }\n\n // Detect workspace context (are we inside packages/ or apps/ of a monorepo?)\n const workspace = await this.pm.getWorkspaceContext(root);\n\n // Detect agent type: claude CLI → CLAUDE.md, else → AGENTS.md\n let agentType: \"claude\" | \"agents\" | false = false;\n if (!workspace.isPackage) {\n const hasClaudeCli = await this.utils.isInstalledAsync(\"claude\");\n agentType = hasClaudeCli ? \"claude\" : \"agents\";\n }\n\n const isExpo = await this.pm.hasExpo(root);\n\n // Get git email for admin auto-promotion (if saas enabled)\n const adminEmail = flags.saas ? await this.utils.getGitEmail() : undefined;\n\n const force = !!flags.force;\n\n await run({\n name: \"ensuring configuration files\",\n handler: async () => {\n await this.ensureConfig(root, {\n force,\n packageJson: { ...flags, isPackage: workspace.isPackage },\n // Skip workspace-level configs if they exist at workspace root\n tsconfigJson: !workspace.config.tsconfigJson,\n biomeJson: true,\n editorconfig: !workspace.config.editorconfig,\n agentMd: agentType ? { type: agentType, ui: !!flags.ui } : false,\n });\n\n // Create alepha.config.ts with documented options\n await this.ensureAlephaConfig(root, { force });\n\n // Create project structure based on flags\n await this.ensureMainServerTs(root, {\n api: !!flags.api,\n react: !!flags.react && !isExpo,\n force,\n });\n if (flags.api) {\n await this.ensureApiProject(root, {\n auth: !!flags.saas,\n adminEmail,\n force,\n });\n }\n if (flags.react && !isExpo) {\n await this.ensureWebProject(root, {\n api: !!flags.api,\n ui: !!flags.ui,\n auth: !!flags.saas,\n admin: !!flags.saas,\n tailwind: !!flags.tailwind,\n force,\n });\n }\n },\n });\n\n // Use workspace PM if detected, otherwise detect from current root\n const pmName = await this.pm.getPackageManager(\n workspace.workspaceRoot ?? root,\n flags.pm ?? workspace.packageManager ?? undefined,\n );\n\n // Only setup PM files if not in a workspace package\n if (!workspace.isPackage) {\n if (pmName === \"yarn\") {\n await this.pm.ensureYarn(root);\n await run(\"yarn set version stable\", { root });\n } else if (pmName === \"bun\") {\n await this.pm.ensureBun(root);\n } else if (pmName === \"pnpm\") {\n await this.pm.ensurePnpm(root);\n } else {\n await this.pm.ensureNpm(root);\n }\n }\n\n // Run install from workspace root if in a package, otherwise from current root\n const installRoot = workspace.workspaceRoot ?? root;\n await run(`${pmName} install`, {\n alias: `installing dependencies with ${pmName}`,\n root: installRoot,\n });\n\n // Create test directory if --test flag is set (vitest is in package.json)\n if (flags.test) {\n await this.ensureTestDir(root);\n }\n\n await run(`${pmName} run lint`, {\n alias: \"running linter\",\n root,\n });\n\n // Initialize git repository if not in a workspace package\n if (!workspace.isPackage) {\n const gitInitialized = await this.ensureGitRepo(root, {\n force,\n });\n if (gitInitialized) {\n await run(\"git add .\", {\n alias: \"staging generated files\",\n root,\n });\n }\n }\n\n // Don't show success message if no path arg, e.g. just \"alepha init\" to re-configure current dir\n if (!args) {\n return;\n }\n\n // We must end the run context in order to log success message\n run.end();\n\n // Success message\n const projectName = args || \".\";\n const pmRun = pmName === \"npm\" ? \"npm run\" : pmName;\n const c = this.colors;\n\n this.log.info(\"\");\n this.log.info(` ${c.set(\"GREEN\", \"✓\")} Project ready!`);\n this.log.info(\"\");\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"$\")} cd ${c.set(\"CYAN\", projectName)}`,\n );\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"$\")} ${c.set(\"CYAN\", `${pmRun} dev`)}`,\n );\n\n if (adminEmail) {\n this.log.info(\"\");\n this.log.info(` Admin email: ${c.set(\"GREEN\", adminEmail)}`);\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"(from git config, change in src/api/AppSecurity.ts)\")}`,\n );\n }\n\n this.log.info(\"\");\n }\n\n // ===========================================\n // Helpers\n // ===========================================\n\n /**\n * Write a file, optionally overriding if it exists.\n */\n protected async ensureFile(\n root: string,\n relativePath: string,\n content: string,\n force?: boolean,\n ): Promise<void> {\n const fullPath = this.fs.join(root, relativePath);\n if (force || !(await this.fs.exists(fullPath))) {\n await this.fs.writeFile(fullPath, content);\n }\n }\n\n /**\n * Check if a file exists in the given directory or any parent directory.\n */\n protected async existsInParents(\n root: string,\n filename: string,\n ): Promise<boolean> {\n let current = root;\n while (true) {\n if (await this.fs.exists(this.fs.join(current, filename))) {\n return true;\n }\n const parent = dirname(current);\n if (parent === current) {\n // Reached filesystem root\n return false;\n }\n current = parent;\n }\n }\n}\n","import type { Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport type { BuildOptions } from \"../atoms/buildOptions.ts\";\nimport type { AppEntry } from \"../providers/AppEntryProvider.ts\";\n\nexport interface BuildTaskContext {\n /**\n * The user's app Alepha container (NOT the CLI container).\n * Used for metadata extraction (pages, primitives, store, etc.).\n */\n alepha: Alepha;\n\n /**\n * Resolved build options (flags merged with atom defaults).\n * BuildCommand mutates the atom before creating the context,\n * so stats, target, runtime are all resolved values.\n */\n options: BuildOptions;\n\n /**\n * CLI runner for progress logging.\n * Tasks call this when they have work to show.\n * Tasks decide IF and WHEN to call run — e.g. skip entirely if nothing to do.\n */\n run: RunnerMethod;\n\n /**\n * Project root directory.\n */\n root: string;\n\n /**\n * Application entry points resolved by AppEntryProvider.\n */\n entry: AppEntry;\n\n /**\n * Whether the app has a client-side bundle (React).\n */\n hasClient: boolean;\n\n /**\n * Raw CLI flags passed through from the command.\n * Tasks can read flags relevant to their domain.\n */\n flags?: {\n image?: boolean | string;\n };\n}\n\n/**\n * Abstract base class for build pipeline tasks.\n *\n * Each task encapsulates a step in the build pipeline.\n * Tasks control their own progress reporting via ctx.run.\n */\nexport abstract class BuildTask {\n abstract run(ctx: BuildTaskContext): Promise<void>;\n}\n","import { createRequire } from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Copy assets from Alepha packages to the build output directory.\n *\n * Reads `alepha.build.assets` state to find packages with assets,\n * and copies their `/assets` directories to the build output.\n * Used by modules like AlephaServerSwagger to distribute UI files.\n */\nexport class BuildAssetsTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const assets = ctx.alepha.store.get(\"alepha.build.assets\");\n\n if (!assets || assets.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const entry = `${distDir}/index.js`;\n\n await ctx.run({\n name: \"copy assets\",\n handler: async () => {\n const require = createRequire(this.fs.join(ctx.root, entry));\n const buildAssetsDir = this.fs.join(ctx.root, distDir, \"assets\");\n await this.fs.mkdir(buildAssetsDir);\n\n for (const pkgName of assets ?? []) {\n const pkgDir = dirname(require.resolve(`${pkgName}/package.json`));\n const assetsPkgDir = resolve(pkgDir, \"assets\");\n await this.fs.cp(assetsPkgDir, buildAssetsDir);\n }\n },\n });\n }\n}\n","import { $inject, Alepha } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { UserConfig } from \"vite\";\nimport { analyzer as viteAnalyzer } from \"vite-bundle-analyzer\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Build client-side bundle with Vite.\n *\n * Compiles the browser/client code for production,\n * including code splitting and minification.\n * Analyze step stays in BuildCommand (ViteBuildProvider).\n * This task wraps only the actual Vite client build call.\n */\nexport class BuildClientTask extends BuildTask {\n protected readonly alepha = $inject(Alepha);\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const stats = ctx.options.stats ?? false;\n const isCI = this.alepha.isCI();\n\n // Write index.html template for Vite to consume\n const template = this.viteUtils.generateIndexHtml(ctx.entry);\n await this.fs.mkdir(this.fs.join(ctx.root, \"node_modules/.alepha\"));\n const indexHtmlPath = this.fs.join(\n ctx.root,\n \"node_modules/.alepha/index.html\",\n );\n await this.fs.writeFile(indexHtmlPath, template);\n\n try {\n await ctx.run({\n name: \"build client\",\n handler: async () => {\n await this.buildClient({\n dist: `${distDir}/${publicDir}`,\n stats,\n silent: !isCI,\n });\n },\n });\n } finally {\n await this.fs.rm(indexHtmlPath);\n }\n }\n\n protected async buildClient(opts: {\n dist: string;\n stats?: boolean | \"json\";\n silent?: boolean;\n }): Promise<void> {\n const { build: viteBuild } = await this.viteUtils.importVite();\n const plugins: any[] = [];\n\n const viteReact = await this.viteUtils.importViteReact();\n if (viteReact) plugins.push(viteReact());\n\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n\n if (opts.stats) {\n plugins.push(\n viteAnalyzer({\n analyzerMode: opts.stats === \"json\" ? \"json\" : \"static\",\n }),\n );\n }\n\n const logger = opts.silent\n ? this.viteUtils.createBufferedLogger()\n : undefined;\n\n const viteBuildClientConfig: UserConfig = {\n mode: \"production\",\n logLevel: opts.silent ? \"silent\" : undefined,\n define: {\n \"process.env.NODE_ENV\": '\"production\"',\n },\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n publicDir: \"public\",\n build: {\n outDir: opts.dist,\n manifest: true,\n chunkSizeWarningLimit: 1000,\n rolldownOptions: {\n input: \"node_modules/.alepha/index.html\",\n output: {\n entryFileNames: \"entry.[hash].js\",\n chunkFileNames: \"chunk.[hash].js\",\n assetFileNames: \"asset.[hash][extname]\",\n },\n },\n },\n customLogger: logger,\n plugins,\n };\n\n try {\n await viteBuild(viteBuildClientConfig);\n await this.postBuildCleanUpForIndexHtml();\n } catch (error) {\n logger?.flush();\n throw error;\n }\n }\n\n /**\n * Weird cleanup required because we changed input from \"index.html\" to \"node_modules/.alepha/index.html\".\n */\n public async postBuildCleanUpForIndexHtml(dist = \"dist/public\") {\n const manifestPath = `${dist}/.vite/manifest.json`;\n let text = await this.fs.readTextFile(manifestPath);\n text = text.replaceAll(\"node_modules/.alepha/index.html\", \"index.html\");\n await this.fs.writeFile(manifestPath, text);\n await this.fs.cp(\n `${dist}/node_modules/.alepha/index.html`,\n `${dist}/index.html`,\n );\n await this.fs.rm(`${dist}/node_modules`, { recursive: true });\n }\n}\n","import { basename } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { KV_DEFAULT_BINDING } from \"alepha/cache\";\nimport { QUEUE_DEFAULT_BINDING } from \"alepha/queue\";\nimport type { CronProvider, WorkerdCronProvider } from \"alepha/scheduler\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\ninterface WranglerConfig {\n [key: string]: any;\n}\n\n/**\n * Generate Cloudflare Workers deployment configuration.\n *\n * Creates:\n * - wrangler.jsonc with worker configuration\n * - main.cloudflare.js entry point for Cloudflare Workers\n */\nexport class BuildCloudflareTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n protected readonly warningComment =\n \"// This file was automatically generated. DO NOT MODIFY.\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"cloudflare\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n\n await ctx.run({\n name: \"generate deploy config (cloudflare)\",\n handler: async () => {\n await this.generateCloudflare(ctx, distDir);\n },\n });\n }\n\n protected async generateCloudflare(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const root = ctx.root;\n const name = basename(root);\n const hasAssets = await this.fs.exists(\n this.fs.join(root, distDir, \"public\"),\n );\n\n const wrangler: WranglerConfig = {\n name,\n main: \"./main.cloudflare.js\",\n compatibility_flags: [\"nodejs_compat\"],\n compatibility_date: \"2025-11-17\",\n no_bundle: true,\n rules: [\n {\n type: \"ESModule\",\n globs: [\"index.js\", \"server/*.js\"],\n },\n ],\n ...ctx.options.cloudflare?.config,\n };\n\n if (hasAssets) {\n wrangler.assets ??= {\n directory: \"./public\",\n binding: \"ASSETS\",\n };\n }\n\n this.enhanceDomain(wrangler);\n this.enhanceCron(ctx, wrangler);\n this.enhanceDatabase(wrangler);\n this.enhanceR2(wrangler);\n this.enhanceKV(wrangler);\n this.enhanceQueue(wrangler);\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"wrangler.jsonc\"),\n JSON.stringify(wrangler, null, 2),\n );\n\n await this.writeWorkerEntryPoint(root, distDir);\n }\n\n protected enhanceDomain(wrangler: WranglerConfig): void {\n const domain = process.env.CLOUDFLARE_DOMAIN;\n if (!domain) {\n return;\n }\n\n wrangler.routes = [\n {\n pattern: domain,\n custom_domain: true,\n },\n ];\n }\n\n protected enhanceCron(ctx: BuildTaskContext, wrangler: WranglerConfig): void {\n if (ctx.alepha.primitives(\"scheduler\").length === 0) {\n return;\n }\n\n let cronProvider: CronProvider | undefined;\n try {\n cronProvider = ctx.alepha.inject(\"CronProvider\") as WorkerdCronProvider;\n } catch {}\n\n const crons = cronProvider?.getCronJobs();\n if (!crons || crons.length === 0) {\n return;\n }\n\n const cronExpressions = [...new Set(crons.map((c) => c.expression))];\n wrangler.triggers ??= {};\n wrangler.triggers.crons = cronExpressions;\n }\n\n protected enhanceDatabase(wrangler: WranglerConfig): void {\n if (process.env.HYPERDRIVE_ID) {\n this.enhanceHyperdrive(wrangler);\n return;\n }\n\n this.enhanceD1(wrangler);\n }\n\n protected static readonly D1_BINDING = \"DB\";\n\n protected enhanceD1(wrangler: WranglerConfig): void {\n const url = process.env.DATABASE_URL;\n if (!url?.startsWith(\"d1:\")) {\n return;\n }\n\n const [dbName, id] = url.replace(\"d1://\", \"\").replace(\"d1:\", \"\").split(\":\");\n const binding = BuildCloudflareTask.D1_BINDING;\n wrangler.d1_databases = wrangler.d1_databases || [];\n wrangler.d1_databases.push({\n binding,\n database_name: dbName,\n database_id: id,\n });\n wrangler.vars ??= {};\n wrangler.vars.DATABASE_URL = `d1://${binding}`;\n }\n\n protected enhanceHyperdrive(wrangler: WranglerConfig): void {\n const hyperdriveId = process.env.HYPERDRIVE_ID;\n if (!hyperdriveId) {\n return;\n }\n\n const binding = \"HYPERDRIVE\";\n wrangler.hyperdrive = wrangler.hyperdrive || [];\n wrangler.hyperdrive.push({\n binding,\n id: hyperdriveId,\n });\n wrangler.vars ??= {};\n wrangler.vars.DATABASE_URL = `hyperdrive://${binding}`;\n\n if (process.env.POSTGRES_SCHEMA) {\n wrangler.vars.POSTGRES_SCHEMA = process.env.POSTGRES_SCHEMA;\n }\n }\n\n protected enhanceR2(wrangler: WranglerConfig): void {\n const bucketName = process.env.R2_BUCKET_NAME;\n if (!bucketName) {\n return;\n }\n\n wrangler.r2_buckets = wrangler.r2_buckets || [];\n wrangler.r2_buckets.push({\n binding: bucketName,\n bucket_name: bucketName,\n });\n wrangler.vars ??= {};\n wrangler.vars.R2_BUCKET_NAME = bucketName;\n }\n\n protected enhanceKV(wrangler: WranglerConfig): void {\n const kvName = process.env.CLOUDFLARE_KV_NAME;\n if (!kvName) {\n return;\n }\n\n const kvId = process.env.CLOUDFLARE_KV_ID;\n\n wrangler.kv_namespaces = wrangler.kv_namespaces || [];\n wrangler.kv_namespaces.push({\n binding: KV_DEFAULT_BINDING,\n id: kvId ?? \"\",\n });\n }\n\n protected enhanceQueue(wrangler: WranglerConfig): void {\n const queueName = process.env.CLOUDFLARE_QUEUE_NAME;\n if (!queueName) {\n return;\n }\n\n wrangler.queues ??= {};\n wrangler.queues.producers = wrangler.queues.producers || [];\n wrangler.queues.producers.push({\n binding: QUEUE_DEFAULT_BINDING,\n queue: queueName,\n });\n wrangler.queues.consumers = wrangler.queues.consumers || [];\n wrangler.queues.consumers.push({\n queue: queueName,\n });\n }\n\n protected async writeWorkerEntryPoint(\n root: string,\n distDir: string,\n ): Promise<void> {\n const workerCode = `\nimport \"./index.js\";\n\nexport default {\n fetch: async (request, env) => {\n const ctx = { req: request, res: undefined };\n\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for fetch event\", err);\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n\n await __alepha.events.emit(\"web:request\", ctx);\n\n return ctx.res;\n },\n\n scheduled: async (event, env, ctx) => {\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for scheduled event\", err);\n throw err;\n }\n\n await __alepha.events.emit(\"cloudflare:scheduled\", {\n cron: event.cron,\n scheduledTime: event.scheduledTime,\n });\n },\n\n queue: async (batch, env) => {\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for queue event\", err);\n throw err;\n }\n\n for (const msg of batch.messages) {\n try {\n await __alepha.events.emit(\"cloudflare:queue\", msg.body);\n msg.ack();\n } catch (e) {\n msg.retry();\n }\n }\n },\n};\n`.trim();\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"main.cloudflare.js\"),\n `${this.warningComment}\\n${workerCode}`.trim(),\n );\n }\n}\n","import { promisify } from \"node:util\";\nimport {\n type BrotliOptions,\n brotliCompress as brotliCompressCb,\n gzip as gzipCb,\n type ZlibOptions,\n} from \"node:zlib\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\nexport interface CompressOptions {\n /**\n * Enable brotli compression. Can be true or brotli-specific options.\n *\n * @default true\n */\n brotli?: boolean | BrotliOptions;\n\n /**\n * Enable gzip compression. Can be true or gzip-specific options.\n *\n * @default false\n */\n gzip?: boolean | ZlibOptions;\n\n /**\n * Filter which files to compress.\n * Can be a RegExp or a function that returns true for files to compress.\n *\n * @default /\\.(js|mjs|cjs|css|wasm|svg|html|xml)$/\n */\n filter?: RegExp | ((fileName: string) => boolean);\n}\n\n/**\n * Compresses all matching files in the public output directory.\n *\n * Creates .gz and .br copies alongside each matching file.\n * Runs as the LAST step in the build pipeline, after all other tasks\n * have written their files.\n */\nexport class BuildCompressTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly gzipCompress = promisify(gzipCb);\n protected readonly brotliCompress = promisify(brotliCompressCb);\n protected readonly defaultFilter = /\\.(js|mjs|cjs|css|wasm|svg|html|xml)$/;\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const dist = ctx.options.output?.dist ?? \"dist\";\n const pub = ctx.options.output?.public ?? \"public\";\n const dir = this.fs.join(ctx.root, dist, pub);\n\n const hasDir = await this.fs.exists(dir);\n if (!hasDir) {\n return;\n }\n\n await ctx.run({\n name: \"compress assets\",\n handler: async () => {\n await this.compressDirectory(dir);\n },\n });\n }\n\n /**\n * Compress all matching files in a directory (recursive).\n */\n protected async compressDirectory(\n dir: string,\n options?: CompressOptions,\n ): Promise<number> {\n const filter = options?.filter ?? this.defaultFilter;\n const files = await this.fs.ls(dir, { recursive: true });\n\n const matchingFiles = files.filter((fileName) => {\n if (typeof filter === \"function\") {\n return filter(fileName);\n }\n return filter.test(fileName);\n });\n\n const tasks: Promise<void>[] = [];\n for (const fileName of matchingFiles) {\n tasks.push(this.compressFile(this.fs.join(dir, fileName), options));\n }\n\n await Promise.all(tasks);\n return matchingFiles.length;\n }\n\n /**\n * Compress a single file. Creates .gz and .br alongside original.\n */\n protected async compressFile(\n filePath: string,\n options?: CompressOptions,\n ): Promise<void> {\n const { brotli = true, gzip = false } = options ?? {};\n const tasks: Promise<void>[] = [];\n const contentPromise = this.fs.readFile(filePath);\n\n if (gzip) {\n const gzipOptions = typeof gzip === \"object\" ? gzip : { level: 9 };\n tasks.push(\n contentPromise.then(async (content) => {\n const compressed = await this.gzipCompress(content, gzipOptions);\n await this.fs.writeFile(`${filePath}.gz`, compressed);\n }),\n );\n }\n\n if (brotli) {\n const brotliOptions = typeof brotli === \"object\" ? brotli : {};\n tasks.push(\n contentPromise.then(async (content) => {\n const compressed = await this.brotliCompress(content, brotliOptions);\n await this.fs.writeFile(`${filePath}.br`, compressed);\n }),\n );\n }\n\n await Promise.all(tasks);\n }\n}\n","import { $inject, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate Docker deployment configuration and optionally build the image.\n *\n * Creates:\n * - Dockerfile with configurable base image\n * - Copies drizzle migrations if they exist\n * - Builds Docker image when `--image` flag is provided\n */\nexport class BuildDockerTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"docker\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const { runtime } = ctx.options;\n\n const dockerFrom =\n ctx.options.docker?.from ??\n (runtime === \"bun\" ? \"oven/bun:alpine\" : \"node:24-alpine\");\n const dockerCommand =\n ctx.options.docker?.command ?? (runtime === \"bun\" ? \"bun\" : \"node\");\n\n await ctx.run({\n name: \"generate deploy config (docker)\",\n handler: async () => {\n await this.copyDrizzleMigrations(ctx.root, distDir);\n await this.writeDockerfile(\n ctx.root,\n distDir,\n dockerFrom,\n dockerCommand,\n );\n },\n });\n\n if (ctx.flags?.image) {\n await this.buildDockerImage(ctx, distDir);\n }\n }\n\n protected async copyDrizzleMigrations(\n root: string,\n distDir: string,\n ): Promise<void> {\n const drizzleDir = this.fs.join(root, \"drizzle\");\n const hasMigrations = await this.fs.exists(drizzleDir);\n if (hasMigrations) {\n await this.fs.cp(drizzleDir, this.fs.join(root, distDir, \"drizzle\"));\n }\n }\n\n protected async writeDockerfile(\n root: string,\n distDir: string,\n image: string,\n command: string,\n ): Promise<void> {\n const dockerfile = `# This file was automatically generated. DO NOT MODIFY.\n# Changes to this file will be lost when the code is regenerated.\nFROM ${image}\nWORKDIR /app\n\nCOPY . .\n\nRUN ${command === \"bun\" ? \"bun\" : \"npm\"} install\n\nENV SERVER_HOST=0.0.0.0\n\nCMD [\"${command}\", \"index.js\"]\n`;\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"Dockerfile\"),\n dockerfile,\n );\n }\n\n protected async buildDockerImage(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const imageConfig = ctx.options.docker?.image;\n const flagValue =\n typeof ctx.flags?.image === \"string\" ? ctx.flags.image : null;\n\n let imageTag: string;\n let version: string;\n\n if (!flagValue) {\n if (!imageConfig?.tag) {\n throw new AlephaError(\n \"Flag '--image' requires 'build.docker.image.tag' in config\",\n );\n }\n version = \"latest\";\n imageTag = `${imageConfig.tag}:${version}`;\n } else if (flagValue.startsWith(\":\")) {\n if (!imageConfig?.tag) {\n throw new AlephaError(\n \"Flag '--image=:version' requires 'build.docker.image.tag' in config\",\n );\n }\n version = flagValue.slice(1);\n imageTag = `${imageConfig.tag}:${version}`;\n } else if (flagValue.includes(\":\")) {\n imageTag = flagValue;\n version = flagValue.split(\":\")[1];\n } else {\n imageTag = `${flagValue}:latest`;\n version = \"latest\";\n }\n\n const args: string[] = [];\n\n if (imageConfig?.args) {\n args.push(imageConfig.args);\n }\n\n if (imageConfig?.oci) {\n const revision = await this.utils.getGitRevision();\n const created = new Date().toISOString();\n\n args.push(`--label \"org.opencontainers.image.revision=${revision}\"`);\n args.push(`--label \"org.opencontainers.image.created=${created}\"`);\n args.push(`--label \"org.opencontainers.image.version=${version}\"`);\n }\n\n const argsStr = args.length > 0 ? `${args.join(\" \")} ` : \"\";\n const dockerCmd = `docker build ${argsStr}-t ${imageTag} ${distDir}`;\n\n await ctx.run(dockerCmd, {\n alias: `docker build ${imageTag}`,\n });\n }\n}\n","import { dirname } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Pre-render static pages defined in the Alepha application.\n *\n * Queries all page primitives with `static: true` and generates\n * static HTML files for each page. Supports pages with parameterized\n * routes via `static.entries` configuration.\n */\nexport class BuildPrerenderTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const pages = this.getStaticPages(ctx);\n if (pages.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const dist = this.fs.join(ctx.root, distDir, publicDir);\n\n await ctx.run({\n name: \"pre-render pages\",\n handler: async () => {\n // TODO: running configure here is a temporary workaround\n if (!ctx.alepha.isConfigured()) {\n await ctx.alepha.events.emit(\"configure\", ctx.alepha);\n }\n await this.prerenderFromAlepha(pages, dist);\n },\n });\n }\n\n protected getStaticPages(ctx: BuildTaskContext): any[] {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n return pages.filter((page) => {\n const options = page.options;\n return options.static && !options.children;\n });\n }\n\n protected async prerenderFromAlepha(\n pages: any[],\n dist: string,\n ): Promise<number> {\n let count = 0;\n\n for (const page of pages) {\n const options = page.options;\n const config = typeof options.static === \"object\" ? options.static : {};\n\n if (!options.schema?.params) {\n count += 1;\n await this.renderFile(page, {}, dist);\n continue;\n }\n\n if (config.entries) {\n for (const entry of config.entries) {\n count += 1;\n await this.renderFile(page, entry, dist);\n }\n }\n }\n\n return count;\n }\n\n protected async renderFile(\n page: any,\n options: any,\n dist: string,\n ): Promise<void> {\n const { html, state } = await page.render({\n html: true,\n ...options,\n });\n\n const pathname = state.url.pathname;\n const filepath = `${dist}${pathname === \"/\" ? \"/index\" : pathname}.html`;\n\n await this.fs.mkdir(dirname(filepath));\n await this.fs.writeFile(filepath, html);\n }\n}\n","import { createRequire } from \"node:module\";\nimport { isAbsolute, join } from \"node:path\";\nimport { $inject, Alepha, AlephaError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type * as vite from \"vite\";\nimport type { UserConfig } from \"vite\";\nimport { analyzer as viteAnalyzer } from \"vite-bundle-analyzer\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Build server-side SSR bundle with Vite.\n *\n * Compiles the server code for production, generates the externals\n * package.json, and creates the dist/index.js entry wrapper.\n */\nexport class BuildServerTask extends BuildTask {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const stats = ctx.options.stats ?? false;\n const isCI = this.alepha.isCI();\n\n const clientIndexPath = this.fs.join(\n ctx.root,\n distDir,\n publicDir,\n \"index.html\",\n );\n const clientBuilt = await this.fs.exists(clientIndexPath);\n\n const conditions: string[] = [];\n if (ctx.options.runtime === \"bun\") {\n conditions.push(\"bun\");\n } else if (ctx.options.runtime === \"workerd\") {\n conditions.push(\"workerd\");\n }\n\n await ctx.run({\n name: \"build server\",\n handler: async () => {\n await this.buildServer({\n root: ctx.root,\n entry: ctx.entry.server,\n distDir,\n clientDir: clientBuilt ? publicDir : undefined,\n stats,\n silent: !isCI,\n conditions,\n alepha: ctx.alepha,\n });\n\n // Server will handle index.html if both client & server are built\n if (clientBuilt) {\n await this.fs.rm(clientIndexPath);\n }\n },\n });\n }\n\n protected async buildServer(opts: {\n root: string;\n entry: string;\n distDir: string;\n clientDir?: string;\n stats?: boolean | \"json\";\n silent?: boolean;\n conditions?: string[];\n alepha: Alepha;\n }): Promise<void> {\n const { build: viteBuild, resolveConfig } =\n await this.viteUtils.importVite();\n const plugins: any[] = [];\n\n const viteReact = await this.viteUtils.importViteReact();\n if (viteReact && opts.clientDir) {\n plugins.push(viteReact());\n }\n\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n\n if (opts.stats) {\n plugins.push(\n viteAnalyzer({\n analyzerMode: opts.stats === \"json\" ? \"json\" : \"static\",\n }),\n );\n }\n\n const logger = opts.silent\n ? this.viteUtils.createBufferedLogger()\n : undefined;\n\n const conditions = [\"node\", \"import\", \"module\", \"default\"];\n if (opts.conditions) {\n conditions.unshift(...opts.conditions);\n }\n\n const viteBuildServerConfig: UserConfig = {\n mode: \"production\",\n logLevel: opts.silent ? \"silent\" : undefined,\n define: {\n \"process.env.NODE_ENV\": '\"production\"',\n },\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n publicDir: false,\n ssr: {\n noExternal: true,\n resolve: { conditions },\n },\n build: {\n ssr: opts.entry,\n minify: true,\n sourcemap: true,\n chunkSizeWarningLimit: 10000,\n outDir: `${opts.distDir}/server`,\n rolldownOptions: {\n external: [/^bun(:|$)/, /^cloudflare:/],\n output: {\n entryFileNames: \"[hash].js\",\n chunkFileNames: \"[hash].js\",\n assetFileNames: \"[hash][extname]\",\n format: \"esm\",\n // Rolldown/Oxc minifier: preserve class and function names\n minify: {\n mangle: { keepNames: true },\n compress: {\n keepNames: { function: true, class: true },\n },\n },\n },\n },\n },\n customLogger: logger,\n plugins,\n };\n\n let result: vite.Rollup.RollupOutput | vite.Rollup.RollupOutput[];\n try {\n result = (await viteBuild(viteBuildServerConfig)) as\n | vite.Rollup.RollupOutput\n | vite.Rollup.RollupOutput[];\n } catch (error) {\n logger?.flush();\n throw error;\n }\n\n const resolvedConfig = await resolveConfig(viteBuildServerConfig, \"build\");\n\n const externals: string[] = [];\n if (Array.isArray(resolvedConfig?.ssr?.external)) {\n externals.push(...resolvedConfig.ssr.external);\n }\n\n await this.generateExternals(opts.distDir, externals);\n\n const entryFile = this.extractEntryFromBundle(\n opts.root,\n opts.entry,\n result,\n );\n\n let manifest = \"\";\n let manifestData:\n | {\n base?: string;\n client?: Record<string, any>;\n preload?: Record<string, string>;\n favicon?: string;\n }\n | undefined;\n\n if (opts.clientDir) {\n const viteDir = `${opts.distDir}/${opts.clientDir}/.vite`;\n const clientManifest = await this.loadJsonFile(\n `${viteDir}/manifest.json`,\n );\n const preloadManifest = await this.loadJsonFile(\n `${viteDir}/preload-manifest.json`,\n );\n\n const strippedClientManifest = this.stripClientManifest(clientManifest);\n\n let base = resolvedConfig.base || \"/\";\n if (!base.startsWith(\"/\")) {\n base = `/${base}`;\n }\n if (base.length > 1 && base.endsWith(\"/\")) {\n base = base.slice(0, -1);\n }\n\n const favicon = await this.detectFavicon(\n `${opts.distDir}/${opts.clientDir}`,\n );\n\n manifestData = {\n base: base !== \"/\" ? base : undefined,\n client: strippedClientManifest,\n preload: preloadManifest,\n favicon,\n };\n\n manifest = `__alepha.set(\"alepha.react.ssr.manifest\", ${JSON.stringify(manifestData, null, \" \")});\\n`;\n\n opts.alepha.store.set(\"alepha.react.ssr.manifest\" as any, manifestData);\n\n await this.fs.rm(viteDir, { recursive: true });\n }\n\n const warning =\n \"// This file was automatically generated. DO NOT MODIFY.\" +\n \"\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n await this.fs.writeFile(\n `${opts.distDir}/index.js`,\n `${warning}\\nimport './server/${entryFile}';\\n\\n${manifest}`.trim(),\n );\n }\n\n /**\n * Detect a favicon file in the given directory.\n * Returns \"mimeType:/path\" if found, undefined otherwise.\n */\n protected async detectFavicon(\n publicDir: string,\n ): Promise<string | undefined> {\n const candidates: [string, string][] = [\n [\"favicon.svg\", \"image/svg+xml\"],\n [\"favicon.png\", \"image/png\"],\n [\"favicon.ico\", \"image/x-icon\"],\n ];\n for (const [file, mime] of candidates) {\n if (await this.fs.exists(join(publicDir, file))) {\n return `${mime}:/${file}`;\n }\n }\n return undefined;\n }\n\n protected async generateExternals(\n distDir: string,\n externals: string[],\n ): Promise<void> {\n const require = createRequire(import.meta.filename);\n const deps: Record<string, string> = {};\n\n for (const dep of externals) {\n try {\n const requirePath = require.resolve(dep);\n const pkgPath = `${requirePath.split(`node_modules/${dep}`)[0]}node_modules/${dep}/package.json`;\n const pkg = JSON.parse((await this.fs.readFile(pkgPath)).toString());\n deps[dep] = `^${pkg.version}`;\n } catch {\n this.log.warn(`Cannot find '${dep}' in node_modules`);\n }\n }\n\n const minimalPkg = {\n type: \"module\",\n main: \"index.js\",\n dependencies: deps,\n };\n\n await this.fs.mkdir(distDir);\n await this.fs.writeFile(\n join(distDir, \"package.json\"),\n JSON.stringify(minimalPkg, null, 2),\n );\n }\n\n protected async loadJsonFile(path: string): Promise<any> {\n try {\n const content = (await this.fs.readFile(path)).toString();\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n protected stripClientManifest(\n manifest: Record<string, any> | undefined,\n ): Record<string, any> | undefined {\n if (!manifest) return undefined;\n\n const stripped: Record<string, any> = {};\n for (const [key, entry] of Object.entries(manifest)) {\n stripped[key] = {\n file: entry.file,\n ...(entry.isEntry && { isEntry: entry.isEntry }),\n ...(entry.imports?.length && { imports: entry.imports }),\n ...(entry.css?.length && { css: entry.css }),\n };\n }\n return stripped;\n }\n\n protected extractEntryFromBundle(\n root: string,\n entry: string,\n result:\n | vite.Rollup.RollupOutput\n | vite.Rollup.RollupOutput[]\n | vite.Rollup.RollupWatcher,\n ): string {\n const entryFilePath = isAbsolute(entry) ? entry : join(root, entry);\n\n const normalizedEntryPath = entryFilePath.replace(/\\\\/g, \"/\");\n\n const rollupOutput = (\n Array.isArray(result) ? result[0] : result\n ) as vite.Rollup.RollupOutput;\n\n const entryFile = rollupOutput.output.find(\n (it) =>\n \"facadeModuleId\" in it && it.facadeModuleId === normalizedEntryPath,\n )?.fileName;\n\n if (!entryFile) {\n throw new AlephaError(\n `Could not find the entry file \"${entryFilePath}\" in the build output. Please check your entry file and try again.`,\n );\n }\n\n return entryFile;\n }\n}\n","import { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate sitemap.xml from Alepha page primitives.\n *\n * Queries all page primitives and generates a sitemap.xml\n * containing URLs for all accessible pages.\n */\nexport class BuildSitemapTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const hostname = ctx.options.sitemap?.hostname;\n if (!hostname) {\n return;\n }\n\n const pages = this.getSitemapPages(ctx);\n if (pages.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const output = this.fs.join(ctx.root, distDir, publicDir, \"sitemap.xml\");\n\n await ctx.run({\n name: \"generate sitemap\",\n handler: async () => {\n const xml = this.generateSitemapFromPages(pages, hostname);\n await this.fs.writeFile(output, xml);\n },\n });\n }\n\n protected getSitemapPages(ctx: BuildTaskContext): any[] {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n return pages.filter((page) => {\n const options = page.options;\n if (options.children) {\n return false;\n }\n if (!options.schema?.params) {\n return true;\n }\n if (\n options.static &&\n typeof options.static === \"object\" &&\n options.static.entries\n ) {\n return true;\n }\n return false;\n });\n }\n\n protected generateSitemapFromPages(pages: any[], baseUrl: string): string {\n const urls: string[] = [];\n const normalizedBaseUrl = baseUrl.replace(/\\/$/, \"\");\n\n for (const page of pages) {\n const options = page.options;\n\n if (!options.schema?.params) {\n const path = options.path || \"\";\n const url = `${normalizedBaseUrl}${path === \"\" ? \"/\" : path}`;\n urls.push(url);\n } else if (\n options.static &&\n typeof options.static === \"object\" &&\n options.static.entries\n ) {\n for (const entry of options.static.entries) {\n const path = this.buildPathFromParams(\n options.path || \"\",\n entry.params || {},\n );\n const url = `${normalizedBaseUrl}${path}`;\n urls.push(url);\n }\n }\n }\n\n return this.buildSitemapXml(urls);\n }\n\n protected buildPathFromParams(\n pathPattern: string,\n params: Record<string, any>,\n ): string {\n let path = pathPattern;\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, String(value));\n }\n return path || \"/\";\n }\n\n protected buildSitemapXml(urls: string[]): string {\n const lastMod = new Date().toISOString().split(\"T\")[0];\n const urlEntries = urls\n .map(\n (url) =>\n ` <url>\\n <loc>${this.escapeXml(url)}</loc>\\n <lastmod>${lastMod}</lastmod>\\n </url>`,\n )\n .join(\"\\n\");\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n${urlEntries}\n</urlset>`;\n }\n\n protected escapeXml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate a static site output.\n *\n * Ensures index.html, 200.html, and 404.html exist in the client directory,\n * then removes all server artifacts from dist, keeping only the public directory.\n */\nexport class BuildStaticTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"static\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const clientDir = ctx.options.output?.public ?? \"public\";\n const publicDir = this.fs.join(ctx.root, distDir, clientDir);\n\n await ctx.run({\n name: \"generate static site\",\n handler: async () => {\n if (!ctx.alepha.isConfigured()) {\n await ctx.alepha.events.emit(\"configure\", ctx.alepha);\n }\n\n const indexPath = this.fs.join(publicDir, \"index.html\");\n const isPrerendered = await this.fs.exists(indexPath);\n if (!isPrerendered) {\n await this.renderRootPage(ctx, publicDir);\n }\n\n const indexHtml = (await this.fs.readFile(indexPath)).toString();\n const shell = this.stripRootContent(indexHtml);\n\n if (!isPrerendered) {\n await this.fs.writeFile(indexPath, shell);\n }\n\n const notFoundPath = this.fs.join(publicDir, \"404.html\");\n if (!(await this.fs.exists(notFoundPath))) {\n await this.fs.writeFile(notFoundPath, shell);\n }\n\n const spaPath = this.fs.join(publicDir, \"200.html\");\n if (!(await this.fs.exists(spaPath))) {\n await this.fs.writeFile(spaPath, shell);\n }\n\n const cnamePath = this.fs.join(publicDir, \"CNAME\");\n if (!(await this.fs.exists(cnamePath))) {\n const domain =\n ctx.options.static?.domain ?? (await this.generateDomain(ctx.root));\n await this.fs.writeFile(cnamePath, domain);\n }\n\n await this.cleanDist(this.fs.join(ctx.root, distDir), clientDir);\n },\n });\n }\n\n protected async renderRootPage(\n ctx: BuildTaskContext,\n publicDir: string,\n ): Promise<void> {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n const rootPage = pages.find(\n (p) => p.options.path === \"/\" && !p.options.children,\n );\n\n if (!rootPage) {\n return;\n }\n\n const { html } = await rootPage.render({ html: true });\n const filepath = this.fs.join(publicDir, \"index.html\");\n\n await this.fs.mkdir(dirname(filepath));\n await this.fs.writeFile(filepath, html);\n }\n\n protected stripRootContent(html: string): string {\n return html.replace(\n /(<body[^>]*>)[\\s\\S]*?(<\\/body>)/,\n '$1<div id=\"root\"></div>$2',\n );\n }\n\n protected async cleanDist(distDir: string, clientDir: string): Promise<void> {\n const entries = await this.fs.ls(distDir);\n for (const entry of entries) {\n if (entry !== clientDir) {\n await this.fs.rm(this.fs.join(distDir, entry), { recursive: true });\n }\n }\n }\n\n protected async generateDomain(root: string): Promise<string> {\n let name = \"app\";\n try {\n const content = (\n await this.fs.readFile(this.fs.join(root, \"package.json\"))\n ).toString();\n const pkg = JSON.parse(content);\n if (pkg.name) {\n name = pkg.name\n .replace(/^@/, \"\")\n .replace(/\\//g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n }\n } catch {\n // fallback to \"app\"\n }\n\n const hash = createHash(\"sha256\").update(name).digest(\"hex\").slice(0, 6);\n return `${name}-${hash}.surge.sh`;\n }\n}\n","import { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate Vercel Build Output API v3 deployment configuration.\n *\n * Creates:\n * - .vercel/output/config.json with routes and version\n * - .vercel/output/static/ (moved from dist/public/)\n * - .vercel/output/functions/index.func/ with handler, index.js, server/, package.json\n * - .vercel/project.json if projectId and orgId are set\n */\nexport class BuildVercelTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n protected readonly warningComment =\n \"// This file was automatically generated. DO NOT MODIFY.\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"vercel\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n\n await ctx.run({\n name: \"generate deploy config (vercel)\",\n handler: async () => {\n await this.generateVercel(ctx, distDir);\n },\n });\n }\n\n protected async generateVercel(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const root = ctx.root;\n const dist = this.fs.join(root, distDir);\n\n const outputDir = this.fs.join(dist, \".vercel\", \"output\");\n const funcDir = this.fs.join(outputDir, \"functions\", \"index.func\");\n const staticDir = this.fs.join(outputDir, \"static\");\n\n await this.fs.mkdir(funcDir);\n await this.fs.mkdir(staticDir);\n\n await this.writeOutputConfig(outputDir, ctx.options.vercel?.config);\n await this.writeVcConfig(funcDir);\n await this.writeHandler(funcDir);\n await this.copyServerBundle(dist, funcDir);\n await this.copyStaticAssets(dist, staticDir);\n await this.writeProjectConfig(ctx, dist);\n }\n\n /**\n * Write .vercel/output/config.json with Build Output API v3 format.\n */\n protected async writeOutputConfig(\n outputDir: string,\n config?: { crons?: { path: string; schedule: string }[] },\n ): Promise<void> {\n const outputConfig: Record<string, any> = {\n version: 3,\n routes: [{ handle: \"filesystem\" }, { src: \"/(.*)\", dest: \"/index\" }],\n };\n\n if (config?.crons && config.crons.length > 0) {\n outputConfig.crons = config.crons;\n }\n\n await this.fs.writeFile(\n this.fs.join(outputDir, \"config.json\"),\n JSON.stringify(outputConfig, null, 2),\n );\n }\n\n /**\n * Write .vc-config.json for the serverless function.\n */\n protected async writeVcConfig(funcDir: string): Promise<void> {\n await this.fs.writeFile(\n this.fs.join(funcDir, \".vc-config.json\"),\n JSON.stringify(\n {\n runtime: \"nodejs22.x\",\n handler: \"handler.js\",\n launcherType: \"Nodejs\",\n },\n null,\n 2,\n ),\n );\n }\n\n /**\n * Write the handler.js entry point that uses node:request event.\n */\n protected async writeHandler(funcDir: string): Promise<void> {\n const handlerCode = `\nimport \"./index.js\";\n\nexport default async (req, res) => {\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for request\", err);\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"Internal Server Error\");\n return;\n }\n\n await __alepha.events.emit(\"node:request\", { req, res });\n};\n`.trim();\n\n await this.fs.writeFile(\n this.fs.join(funcDir, \"handler.js\"),\n `${this.warningComment}\\n${handlerCode}`,\n );\n }\n\n /**\n * Copy the server bundle (index.js, server/, package.json) into the function directory.\n */\n protected async copyServerBundle(\n dist: string,\n funcDir: string,\n ): Promise<void> {\n await this.fs.cp(\n this.fs.join(dist, \"index.js\"),\n this.fs.join(funcDir, \"index.js\"),\n );\n\n await this.fs.cp(\n this.fs.join(dist, \"package.json\"),\n this.fs.join(funcDir, \"package.json\"),\n );\n\n const serverDir = this.fs.join(dist, \"server\");\n if (await this.fs.exists(serverDir)) {\n await this.fs.cp(serverDir, this.fs.join(funcDir, \"server\"));\n }\n }\n\n /**\n * Move static assets from dist/public/ to .vercel/output/static/.\n */\n protected async copyStaticAssets(\n dist: string,\n staticDir: string,\n ): Promise<void> {\n const publicDir = this.fs.join(dist, \"public\");\n if (await this.fs.exists(publicDir)) {\n await this.fs.cp(publicDir, staticDir);\n } else {\n await this.fs.writeFile(this.fs.join(staticDir, \".keep\"), \"\");\n }\n }\n\n /**\n * Write .vercel/project.json if projectId and orgId are available.\n */\n protected async writeProjectConfig(\n ctx: BuildTaskContext,\n dist: string,\n ): Promise<void> {\n const projectId =\n process.env.VERCEL_PROJECT_ID ?? ctx.options.vercel?.projectId;\n const projectName =\n process.env.VERCEL_PROJECT_NAME ?? ctx.options.vercel?.projectName;\n const orgId = process.env.VERCEL_ORG_ID ?? ctx.options.vercel?.orgId;\n\n if (!projectId || !orgId) {\n return;\n }\n\n const vercelDir = this.fs.join(dist, \".vercel\");\n await this.fs.mkdir(vercelDir);\n\n await this.fs.writeFile(\n this.fs.join(vercelDir, \"project.json\"),\n JSON.stringify(\n {\n projectId,\n projectName,\n orgId,\n },\n null,\n 2,\n ),\n );\n }\n}\n","import { $inject, $state, Alepha, AlephaError, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport {\n type BuildRuntime,\n type BuildTarget,\n buildOptions,\n} from \"../atoms/buildOptions.ts\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { ViteBuildProvider } from \"../providers/ViteBuildProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\nimport { BuildAssetsTask } from \"../tasks/BuildAssetsTask.ts\";\nimport { BuildClientTask } from \"../tasks/BuildClientTask.ts\";\nimport { BuildCloudflareTask } from \"../tasks/BuildCloudflareTask.ts\";\nimport { BuildCompressTask } from \"../tasks/BuildCompressTask.ts\";\nimport { BuildDockerTask } from \"../tasks/BuildDockerTask.ts\";\nimport { BuildPrerenderTask } from \"../tasks/BuildPrerenderTask.ts\";\nimport { BuildServerTask } from \"../tasks/BuildServerTask.ts\";\nimport { BuildSitemapTask } from \"../tasks/BuildSitemapTask.ts\";\nimport { BuildStaticTask } from \"../tasks/BuildStaticTask.ts\";\nimport type { BuildTaskContext } from \"../tasks/BuildTask.ts\";\nimport { BuildVercelTask } from \"../tasks/BuildVercelTask.ts\";\n\nexport class BuildCommand {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly viteBuildProvider = $inject(ViteBuildProvider);\n protected readonly options = $state(buildOptions);\n\n /**\n * Build pipeline: tasks run sequentially in this order.\n * Each task self-guards (checks target, hasClient, etc.).\n * Order matters — compress must be last.\n */\n protected readonly pipeline = [\n $inject(BuildClientTask),\n $inject(BuildServerTask),\n $inject(BuildAssetsTask),\n $inject(BuildSitemapTask),\n $inject(BuildPrerenderTask),\n $inject(BuildVercelTask),\n $inject(BuildCloudflareTask),\n $inject(BuildDockerTask),\n $inject(BuildStaticTask),\n $inject(BuildCompressTask),\n ];\n\n /**\n * Resolve the effective runtime based on target and explicit runtime flag.\n *\n * Some targets force a specific runtime:\n * - `cloudflare` always uses `workerd`\n * - `vercel` always uses `node`\n * - `docker` and bare deployments respect the runtime flag\n *\n * @throws {AlephaError} If an incompatible runtime is specified for a target\n */\n protected resolveRuntime(\n target: BuildTarget | undefined,\n runtime: BuildRuntime | undefined,\n ): BuildRuntime {\n if (target === \"cloudflare\") {\n if (runtime && runtime !== \"workerd\") {\n throw new AlephaError(\n `Target 'cloudflare' requires 'workerd' runtime, got '${runtime}'`,\n );\n }\n return \"workerd\";\n }\n\n if (target === \"vercel\") {\n if (runtime && runtime !== \"node\") {\n throw new AlephaError(\n `Target 'vercel' requires 'node' runtime, got '${runtime}'`,\n );\n }\n return \"node\";\n }\n\n return runtime ?? \"node\";\n }\n\n public readonly build = $command({\n name: \"build\",\n mode: \"production\",\n description: \"Build the project for production\",\n flags: t.object({\n stats: t.optional(\n t.union([t.boolean(), t.enum([\"json\"])], {\n description: \"Generate build stats report\",\n }),\n ),\n target: t.optional(\n t.enum([\"bare\", \"docker\", \"vercel\", \"cloudflare\", \"static\"], {\n aliases: [\"t\"],\n description: \"Deployment target\",\n }),\n ),\n runtime: t.optional(\n t.enum([\"node\", \"bun\", \"workerd\"], {\n aliases: [\"r\"],\n description: \"JavaScript runtime\",\n }),\n ),\n image: t.optional(\n t.union([t.boolean(), t.text()], {\n aliases: [\"i\"],\n description:\n \"Build Docker image. Use -i for latest, -i=<version> for specific version\",\n }),\n ),\n sitemap: t.optional(\n t.text({\n description: \"Generate sitemap.xml with base URL\",\n }),\n ),\n }),\n handler: async ({ flags, run, root }) => {\n process.env.NODE_ENV = \"production\";\n\n if (await this.pm.hasExpo(root)) {\n // will come soon\n return;\n }\n\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const entry = await this.boot.getAppEntry(root);\n this.log.trace(\"Entry file found\", { entry });\n\n // Resolve flags → mutate the atom (single source of truth)\n this.alepha.store.mut(buildOptions, (current) => ({\n ...current,\n stats: flags.stats ?? current.stats ?? false,\n target: flags.target ?? current.target,\n runtime: this.resolveRuntime(\n flags.target ?? current.target,\n flags.runtime ?? current.runtime,\n ),\n ...(flags.sitemap && {\n sitemap: { hostname: flags.sitemap },\n }),\n }));\n\n const options = this.options;\n\n const distDir = options.output?.dist ?? \"dist\";\n\n await run.rm(distDir, { alias: \"clean dist\" });\n\n const { target } = options;\n\n // Validate --image requires --target=docker\n if (flags.image && target !== \"docker\") {\n throw new AlephaError(\n `Flag '--image' requires '--target=docker', got '${target ?? \"bare\"}'`,\n );\n }\n\n this.log.trace(\"Build configuration\", {\n target,\n runtime: options.runtime,\n });\n\n let appAlepha: Alepha | undefined;\n let hasClient = false;\n\n await run({\n name: \"analyze app\",\n handler: async () => {\n appAlepha = await this.viteBuildProvider.init({ entry });\n hasClient = this.viteBuildProvider.hasClient();\n },\n });\n\n if (!appAlepha) {\n throw new AlephaError(\"Alepha instance not found\");\n }\n\n const ctx: BuildTaskContext = {\n alepha: appAlepha,\n options,\n root,\n run,\n entry,\n hasClient,\n flags: { image: flags.image },\n };\n\n for (const task of this.pipeline) {\n await task.run(ctx);\n }\n },\n });\n}\n","import { $command } from \"alepha/command\";\n\nexport class CleanCommand {\n /**\n * Clean the project, removing the \"dist\" directory\n */\n public readonly clean = $command({\n name: \"clean\",\n description: \"Clean the project\",\n handler: async ({ run }) => {\n await run.rm(\"./dist\");\n },\n });\n}\n","import { $inject, AlephaError, t } from \"alepha\";\nimport { $command, Runner } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport type {\n DatabaseProvider,\n DrizzleKitProvider,\n RepositoryProvider,\n} from \"alepha/orm\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\n\nconst drizzleCommandFlags = t.object({\n provider: t.optional(\n t.text({\n description:\n \"Database provider name to target (e.g., 'postgres', 'sqlite')\",\n }),\n ),\n});\n\nexport class DbCommand {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly entryProvider = $inject(AppEntryProvider);\n protected readonly viteUtil = $inject(ViteUtils);\n protected readonly runner = $inject(Runner);\n\n /**\n * Check if database migrations are up to date.\n */\n protected readonly check = $command({\n name: \"check\",\n mode: true,\n description: \"Check if migration files are up to date\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ args, root }) => {\n const rootDir = root;\n this.log.debug(`Using project root: ${rootDir}`);\n\n const entry = await this.entryProvider.getAppEntry(root);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n if (accepted.has(providerName)) {\n continue;\n }\n\n accepted.add(providerName);\n\n const migrationDir = this.fs.join(rootDir, \"migrations\", providerName);\n\n const journalBuffer = await this.fs\n .readFile(this.fs.join(migrationDir, \"meta\", \"_journal.json\"))\n .catch(() => null);\n\n if (!journalBuffer) {\n this.log.info(\"No migration journal found.\");\n return;\n }\n\n const journal = JSON.parse(journalBuffer.toString(\"utf-8\"));\n const lastMigration = journal.entries[journal.entries.length - 1];\n const snapshotBuffer = await this.fs.readFile(\n this.fs.join(\n migrationDir,\n \"meta\",\n `${String(lastMigration.idx).padStart(4, \"0\")}_snapshot.json`,\n ),\n );\n const lastSnapshot = JSON.parse(snapshotBuffer.toString(\"utf-8\"));\n\n const { statements: migrationStatements } =\n await drizzleKitProvider.generateMigration(provider, lastSnapshot, {\n withoutSchema: true,\n });\n\n if (migrationStatements.length === 0) {\n this.log.info(\"No changes detected.\");\n return;\n }\n\n this.log.info(\"\");\n this.log.info(\"Detected migration statements:\");\n this.log.info(\"\");\n for (const stmt of migrationStatements) {\n this.log.info(stmt);\n }\n this.log.info(\"\");\n\n this.log.info(\n `At least ${migrationStatements.length} change(s) detected.`,\n );\n this.log.info(\n \"Please, run 'alepha db migrations generate' to update the migration files.\",\n );\n this.log.info(\"\");\n\n throw new AlephaError(\"Database migrations are not up to date.\");\n }\n },\n });\n\n /**\n * Generate database migration files\n */\n protected readonly create = $command({\n name: \"create\",\n mode: true,\n description: \"Generate migration files from current schema\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: t.extend(drizzleCommandFlags, {\n custom: t.optional(\n t.boolean({\n description:\n \"Generate an empty migration file for custom SQL (e.g., for data migrations or manual adjustments)\",\n }),\n ),\n name: t.optional(\n t.text({\n description: \"Name for the generated migration file\",\n }),\n ),\n }),\n handler: async ({ args, flags, root }) => {\n const parts: string[] = [];\n if (flags.custom) parts.push(`--custom=1`);\n if (flags.name) parts.push(`--name=${flags.name}`);\n const commandFlags = parts.length > 0 ? parts.join(\" \") : undefined;\n\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"generate\",\n commandFlags,\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Generate '${providerName}' migrations (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Push database schema changes directly to the database\n */\n protected readonly push = $command({\n name: \"push\",\n mode: true,\n description: \"Push database schema changes directly to the database\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: t.extend(drizzleCommandFlags, {\n dryRun: t.optional(\n t.boolean({\n description: \"Preview SQL statements without executing them\",\n }),\n ),\n }),\n handler: async ({ root, args, flags }) => {\n if (flags.dryRun) {\n const entry = await this.entryProvider.getAppEntry(root);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n\n if (accepted.has(providerName)) continue;\n accepted.add(providerName);\n\n if (flags.provider && flags.provider !== providerName) continue;\n\n this.log.info(\"\");\n this.log.info(\n `Dry run for '${providerName}' (${provider.dialect}) ...`,\n );\n\n await (provider as any).connect();\n\n try {\n const result = await drizzleKitProvider.dryRunPush(provider);\n\n if (result.statements.length === 0) {\n this.log.info(\"No changes detected.\");\n } else {\n if (result.hasDataLoss) {\n this.log.warn(\"WARNING: These changes would cause data loss!\");\n for (const warning of result.warnings) {\n this.log.warn(` ${warning}`);\n }\n }\n\n this.log.info(\"\");\n this.log.info(\n `${result.statements.length} statement(s) would be executed:`,\n );\n this.log.info(\"\");\n for (const stmt of result.statements) {\n this.log.info(stmt);\n }\n }\n } finally {\n await (provider as any).close();\n }\n }\n return;\n }\n\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"push\",\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Push '${providerName}' schema (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Apply pending database migrations\n */\n protected readonly apply = $command({\n name: \"apply\",\n mode: true,\n description: \"Apply pending migrations to the database\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ root, run, mode }) => {\n const entry = await this.entryProvider.getAppEntry(root);\n\n await run({\n name: `db migrate (${mode || \"development\"})`,\n handler: async () => {\n process.env.MIGRATE = \"true\";\n\n if (this.runner.useDynamicLogger) {\n process.env.LOG_LEVEL = \"warn\";\n }\n\n const alepha = await this.viteUtil.runAlepha({\n entry,\n mode: \"production\",\n });\n\n await alepha.start();\n },\n });\n },\n\n // await run({\n // name: `db migrate (${mode || \"development\"})`,\n // handler: async () => {\n // await this.utils.exec(`tsx ${entry.server}`, {\n // capture: this.runner.useDynamicLogger,\n // env: {\n // ...process.env,\n // NODE_ENV: \"production\",\n // MIGRATE: \"true\",\n // },\n // });\n // },\n // });\n // },\n });\n\n /**\n * Launch Drizzle Studio database browser\n */\n protected readonly studio = $command({\n name: \"studio\",\n mode: true,\n description: \"Launch Drizzle Studio database browser\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ root, args, flags }) => {\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"studio\",\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Launch Studio for '${providerName}' (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Parent command for migration operations.\n */\n protected readonly migrations = $command({\n name: \"migrations\",\n aliases: [\"m\"],\n description: \"Manage database migrations\",\n children: [this.check, this.create, this.apply],\n handler: async ({ help }) => {\n help();\n },\n });\n\n /**\n * Parent command for database operations.\n */\n public readonly db = $command({\n name: \"db\",\n description: \"Database management commands\",\n children: [this.migrations, this.push, this.studio],\n handler: async ({ help }) => {\n help();\n },\n });\n\n /**\n * Run a drizzle-kit command for all database providers in an Alepha instance.\n */\n public async runDrizzleKitCommand(options: {\n root: string;\n args?: string;\n command: string;\n commandFlags?: string;\n provider?: string;\n logMessage: (providerName: string, dialect: string) => string;\n }): Promise<void> {\n const rootDir = options.root;\n\n this.log.debug(`Using project root: ${rootDir}`);\n\n const entry = await this.entryProvider.getAppEntry(rootDir);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n const dialect = provider.dialect;\n\n if (providerName === \"\") {\n continue;\n }\n\n if (accepted.has(providerName)) {\n continue;\n }\n accepted.add(providerName);\n\n // Skip if provider filter is set and doesn't match\n if (options.provider && options.provider !== providerName) {\n this.log.debug(\n `Skipping provider '${providerName}' (filter: ${options.provider})`,\n );\n continue;\n }\n\n this.log.info(\"\");\n this.log.info(options.logMessage(providerName, dialect));\n\n const drizzleConfigJsPath = await this.prepareDrizzleConfig({\n kit: drizzleKitProvider,\n provider,\n providerName,\n providerUrl: provider.url,\n providerDriver: provider.driver,\n dialect,\n entry: this.fs.join(rootDir, entry.server),\n rootDir,\n command: options.command,\n });\n\n const flags = options.commandFlags ? ` ${options.commandFlags}` : \"\";\n await this.utils.exec(\n `drizzle-kit ${options.command} --config=${drizzleConfigJsPath}${flags}`,\n {\n env: {\n ALEPHA_CLI_IMPORT: \"true\",\n NODE_OPTIONS: [process.env.NODE_OPTIONS, \"--import tsx\"]\n .filter(Boolean)\n .join(\" \"),\n },\n },\n );\n\n // Post-process generated SQL: strip explicit \"public\". schema qualifiers\n // from FK REFERENCES so migration files stay truly schema-free.\n // search_path handles resolution at runtime.\n if (options.command === \"generate\" && dialect === \"postgresql\") {\n await this.stripPublicSchemaFromMigrations(\n this.fs.join(rootDir, \"migrations\", providerName),\n );\n }\n }\n }\n\n /**\n * Remove `\"public\".` schema qualifiers from FK REFERENCES in SQL migration files.\n *\n * drizzle-kit generates `REFERENCES \"public\".\"table\"(...)` even for schema-free\n * models. This breaks when deploying to a non-public schema via search_path.\n */\n protected async stripPublicSchemaFromMigrations(\n migrationsDir: string,\n ): Promise<void> {\n const files = await this.fs.ls(migrationsDir).catch(() => []);\n\n for (const file of files) {\n if (!file.endsWith(\".sql\")) continue;\n\n const filePath = this.fs.join(migrationsDir, file);\n const content = await this.fs.readFile(filePath);\n const sql = content.toString(\"utf-8\");\n const cleaned = sql.replaceAll('\"public\".', \"\");\n\n if (cleaned !== sql) {\n await this.fs.writeFile(filePath, cleaned);\n this.log.debug(`Stripped \"public\". qualifiers from ${file}`);\n }\n }\n }\n\n /**\n * Prepare Drizzle configuration files for a database provider.\n */\n public async prepareDrizzleConfig(options: {\n kit: any;\n provider: DatabaseProvider;\n providerName: string;\n providerUrl: string;\n providerDriver: string;\n dialect: string;\n entry: string;\n rootDir: string;\n command?: string;\n }): Promise<string> {\n // For migration generation, use schema-free models so the SQL output\n // doesn't contain hardcoded schema qualifiers (e.g. \"myschema\".\"users\").\n // The schema is applied at runtime via search_path.\n const withoutSchema = options.command === \"generate\";\n const models = withoutSchema\n ? Object.keys(options.kit.getModelsWithoutSchema(options.provider))\n : Object.keys(options.kit.getModels(options.provider));\n const entitiesJs = this.generateEntitiesJs(\n options.entry,\n options.providerName,\n models,\n withoutSchema,\n );\n\n const entitiesJsPath = await this.utils.writeConfigFile(\n \"entities.js\",\n entitiesJs,\n options.rootDir,\n );\n\n const config: Record<string, any> = {\n schema: entitiesJsPath,\n out: `./migrations/${options.providerName}`,\n dialect: options.dialect,\n dbCredentials: {\n url: options.providerUrl,\n },\n };\n\n // Use schema-specific migration table so multiple schemas sharing\n // the same database each track their own migration history.\n if (options.dialect === \"postgresql\") {\n config.migrations = {\n table: options.provider.migrationsTable,\n };\n }\n\n // Schema filter is only needed for push/studio (introspection).\n // For generate, models are already schema-free.\n if (options.provider.schema && !withoutSchema) {\n config.schemaFilter = options.provider.schema;\n }\n\n if (options.providerDriver === \"d1\") {\n config.driver = \"d1-http\";\n }\n\n if (options.providerDriver === \"pglite\") {\n config.driver = \"pglite\";\n }\n\n if (options.dialect === \"sqlite\") {\n if (options.providerDriver === \"d1\") {\n // For D1, we need to fill D1 bindings in a way that drizzle-kit can use it, since D1 doesn't use a traditional connection URL\n } else {\n let url = options.providerUrl;\n url = url.replace(\"sqlite://\", \"\").replace(\"file://\", \"\");\n url = this.fs.join(options.rootDir, url);\n\n config.dbCredentials = {\n url,\n };\n }\n }\n\n const drizzleConfigJs = `export default ${JSON.stringify(config, null, 2)}`;\n\n return await this.utils.writeConfigFile(\n \"drizzle.config.js\",\n drizzleConfigJs,\n options.rootDir,\n );\n }\n\n // ===========================================\n // Drizzle ORM & Kit Utilities\n // ===========================================\n\n /**\n * Generate JavaScript code for Drizzle entities export.\n *\n * When `withoutSchema` is true, uses `getModelsWithoutSchema()` to produce\n * schema-free models for migration generation.\n */\n public generateEntitiesJs(\n entry: string,\n provider: string,\n models: string[] = [],\n withoutSchema = false,\n ): string {\n const getModelsCall = withoutSchema\n ? \"kit.getModelsWithoutSchema(provider)\"\n : \"kit.getModels(provider)\";\n\n return `\nimport \"${entry}\";\nimport { DrizzleKitProvider, Repository } from \"alepha/orm\";\n\nconst alepha = globalThis.__alepha;\nconst kit = alepha.inject(DrizzleKitProvider);\nconst provider = alepha.services(Repository).find((it) => it.provider.name === \"${provider}\").provider;\nconst models = ${getModelsCall};\n\n${models.map((it: string) => `export const ${it} = models[\"${it}\"];`).join(\"\\n\")}\n\n`.trim();\n }\n}\n","import { join } from \"node:path\";\nimport { __alephaRef, $inject, type Alepha, AlephaError } from \"alepha\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport type { AppEntry } from \"./AppEntryProvider.ts\";\n\nexport interface DevServerOptions {\n /**\n * Root directory of the project.\n */\n root: string;\n\n /**\n * Path to the server entry file.\n */\n entry: AppEntry;\n\n /**\n * Disable Vite React plugin.\n */\n noViteReactPlugin?: boolean;\n}\n\n/**\n * Hook called after Alepha is loaded during dev server init/reload.\n */\nexport type OnAlephaLoadedHook = (\n alepha: Alepha,\n server: ViteDevServer,\n) => Promise<void>;\n\n/**\n * Vite development server with Alepha integration.\n *\n * Architecture:\n * - Vite owns the HTTP server\n * - Alepha handles requests via Vite plugin middleware\n * - Request flow: Vite built-in (HMR, assets) → Alepha routes\n *\n * HMR Strategy:\n * - Browser-only changes (CSS, client components) → Vite HMR (React Fast Refresh)\n * - Server-only changes → Reload Alepha → Full browser reload\n * - Shared changes → Reload Alepha → Let HMR propagate\n */\nexport class ViteDevServerProvider {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly colors = $inject(ConsoleColorProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n protected server!: ViteDevServer;\n protected options!: DevServerOptions;\n public alepha: Alepha | null = null;\n protected hasError = false;\n protected currentError: Error | null = null;\n protected changedFiles = new Set<string>();\n protected waitingForRetry = false;\n protected reloadDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n protected isReloading = false;\n protected needsBrowserReload = false;\n protected currentReloadPromise: Promise<void> | null = null;\n protected extraVitePlugins: Plugin[] = [];\n protected alephaLoadedHooks: OnAlephaLoadedHook[] = [];\n\n /**\n * Register an additional Vite plugin.\n * Must be called before init().\n */\n public addVitePlugin(plugin: Plugin): void {\n this.extraVitePlugins.push(plugin);\n }\n\n /**\n * Register a hook called after Alepha is loaded/reloaded.\n */\n public onAlephaLoaded(hook: OnAlephaLoadedHook): void {\n this.alephaLoadedHooks.push(hook);\n }\n\n /**\n * Trigger a full Alepha reload programmatically.\n */\n public reload(): void {\n this.hasError = true;\n this.needsBrowserReload = true;\n this.changedFiles.add(\"__manual_reload__\");\n this.scheduleReload();\n }\n\n /**\n * Initialize the dev server and load Alepha.\n */\n public async init(options: DevServerOptions): Promise<Alepha> {\n this.options = options;\n await this.createServer();\n\n try {\n return await this.loadAlepha(true);\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n return await this.waitForSuccessfulLoad();\n }\n }\n\n /**\n * Start the Alepha server and begin listening.\n */\n public async start(): Promise<void> {\n try {\n await this.alepha?.start();\n await this.listen();\n\n const port = this.server.config.server.port ?? 5173;\n const url = `http://localhost:${port}/`;\n const log = this.alepha?.log ?? this.log;\n log.info(`Listening on ${this.colors.set(\"CYAN\", url)}`);\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n this.alepha = await this.waitForSuccessfulLoad();\n await this.alepha.start();\n await this.listen();\n }\n }\n\n /**\n * Check if project uses React.\n */\n public hasReact(): boolean {\n try {\n this.alepha?.inject(\"ReactServerProvider\");\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Create the Vite server with Alepha plugin.\n */\n protected async createServer(): Promise<void> {\n const { createServer, resolveConfig } = await this.viteUtils.importVite();\n const viteReact = await this.viteUtils.importViteReact();\n\n const plugins: Plugin[] = [];\n if (viteReact && !this.options.noViteReactPlugin) plugins.push(viteReact());\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n plugins.push(...this.extraVitePlugins);\n plugins.push(this.createAlephaPlugin());\n\n // DEFAULT PORT\n // Dev: 5173\n // Prod: 3000\n\n let port: number;\n if (process.env.SERVER_PORT) {\n port = Number(process.env.SERVER_PORT);\n } else {\n const config = await resolveConfig({}, \"serve\", \"development\");\n port = config.server?.port ? Number(config.server.port) : 5173;\n }\n\n this.server = await createServer({\n root: this.options.root,\n plugins,\n appType: \"custom\",\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n server: {\n port,\n },\n optimizeDeps: {\n entries: [\n ...(this.options.entry.browser ? [this.options.entry.browser] : []),\n ],\n },\n });\n\n this.patchServerRestartForEnvReload();\n }\n\n /**\n * Intercept Vite's server.restart() to handle .env file changes.\n * Vite calls restart() when .env files change.\n */\n protected patchServerRestartForEnvReload(): void {\n this.server.restart = async () => {\n if (this.waitingForRetry || this.isReloading) return;\n\n this.isReloading = true;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Reloading ...\"));\n console.log();\n\n try {\n this.hasError = true; // Force full invalidation for env changes\n await this.loadAlepha(false);\n await this.alepha?.start();\n\n this.currentError = null;\n this.sendBrowserReload();\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Reload failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n } finally {\n this.isReloading = false;\n }\n };\n }\n\n /**\n * Start listening for connections.\n */\n protected async listen(): Promise<void> {\n await this.server.listen();\n }\n\n /**\n * Vite plugin that integrates Alepha.\n */\n protected createAlephaPlugin(): Plugin {\n return {\n name: \"alepha\",\n\n configureServer: (server) => {\n // Re-send error overlay when a new browser connects (e.g. page refresh during error state)\n server.hot.on(\"connection\", () => {\n if (this.currentError) {\n setTimeout(() => this.sendErrorOverlay(this.currentError!), 50);\n }\n });\n\n // Readiness endpoint: responds only when Alepha is fully loaded\n server.middlewares.use(async (req, res, next) => {\n if (req.url !== \"/__alepha/ready\") {\n next();\n return;\n }\n\n if (this.currentReloadPromise) {\n await this.currentReloadPromise;\n }\n\n if (this.alepha?.isReady()) {\n res.writeHead(200, { \"content-type\": \"text/plain\" });\n res.end(\"ok\");\n } else {\n res.writeHead(503, { \"content-type\": \"text/plain\" });\n res.end(\"not ready\");\n }\n });\n\n // Return function to run AFTER Vite's built-in middleware\n return () => {\n server.middlewares.use(async (req, res, next) => {\n // Skip Vite internal routes\n const url = req.url || \"/\";\n if (url.startsWith(\"/@\") || url.startsWith(\"/__vite\")) {\n next();\n return;\n }\n\n // Wait for in-progress reload to complete before serving\n if (this.currentReloadPromise) {\n await this.currentReloadPromise;\n }\n\n // In error state, serve a minimal HTML shell so the browser\n // can connect to Vite's HMR and display the error overlay\n if (this.hasError && !this.alepha) {\n if (req.headers.accept?.includes(\"text/html\")) {\n res.writeHead(200, { \"content-type\": \"text/html\" });\n res.end(\n '<!DOCTYPE html><html><head><script type=\"module\" src=\"/@vite/client\"></script></head><body></body></html>',\n );\n return;\n }\n next();\n return;\n }\n\n // Emit to Alepha's request handler\n try {\n await this.alepha?.events.emit(\"node:request\", { req, res });\n } catch (err) {\n this.log.error(\"Request handler error\", err);\n if (!res.headersSent) {\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"Internal Server Error\");\n }\n return;\n }\n\n // If Alepha didn't handle it, pass to next (404 handled by Vite)\n if (!res.headersSent && !res.writableEnded) {\n next();\n }\n });\n };\n },\n\n handleHotUpdate: async (ctx) => {\n // Ignore IDE files\n if (/[/\\\\]\\.idea[/\\\\]/.test(ctx.file)) return [];\n\n // Skip when waiting for startup retry\n if (this.waitingForRetry) return [];\n\n const firstModule = ctx.modules[0] as\n | { _ssrModule?: unknown; _clientModule?: unknown }\n | undefined;\n const isBrowserOnly = firstModule && !firstModule._ssrModule;\n\n // Browser-only: let Vite HMR handle it (React Fast Refresh)\n if (isBrowserOnly) return;\n\n // Queue Alepha reload for server-side invalidation\n this.changedFiles.add(ctx.file);\n\n // React components (.tsx/.jsx): reload Alepha BEFORE letting\n // Vite HMR reach the browser, to prevent 503 errors from\n // components that fetch data on mount during server reload.\n if (/\\.(tsx|jsx)$/.test(ctx.file)) {\n if (this.reloadDebounceTimer) {\n clearTimeout(this.reloadDebounceTimer);\n this.reloadDebounceTimer = null;\n }\n await this.performReload();\n return;\n }\n\n // Pure server files: need full browser reload after Alepha restart\n this.needsBrowserReload = true;\n this.scheduleReload();\n return [];\n },\n };\n }\n\n /**\n * Send full browser reload via Vite's HMR.\n * Uses a custom event so the client can poll for readiness before reloading.\n */\n protected sendBrowserReload(): void {\n this.server.hot.send(\"alepha:reload\", {});\n }\n\n /**\n * Send error to Vite's native error overlay.\n */\n protected sendErrorOverlay(err: Error): void {\n this.fixStacktrace(err);\n this.server.hot.send({\n type: \"error\",\n err: {\n message: err.message,\n stack: err.stack ?? \"\",\n plugin: \"alepha\",\n id: this.options.entry.server,\n },\n });\n }\n\n /**\n * Schedule a debounced reload.\n * Batches rapid file changes into a single reload operation.\n */\n protected scheduleReload(): void {\n // Clear any pending reload\n if (this.reloadDebounceTimer) {\n clearTimeout(this.reloadDebounceTimer);\n }\n\n // If already reloading, the pending changes will be picked up\n // when the current reload checks changedFiles\n if (this.isReloading) {\n return;\n }\n\n this.reloadDebounceTimer = setTimeout(() => {\n this.reloadDebounceTimer = null;\n this.performReload();\n }, 100);\n }\n\n /**\n * Perform the actual reload.\n * Returns a promise that callers can await to know when reload is done.\n * If a reload is already in progress, returns that promise.\n */\n protected performReload(): Promise<void> {\n if (this.changedFiles.size === 0) {\n return this.currentReloadPromise ?? Promise.resolve();\n }\n\n if (this.isReloading) {\n return this.currentReloadPromise ?? Promise.resolve();\n }\n\n this.currentReloadPromise = this.executeReload();\n return this.currentReloadPromise;\n }\n\n /**\n * Execute the reload work.\n */\n protected async executeReload(): Promise<void> {\n this.isReloading = true;\n\n // Snapshot files to process and clear immediately\n // New files arriving during reload will go to fresh set\n const filesToInvalidate = new Set(this.changedFiles);\n const sendReload = this.needsBrowserReload;\n const wasInError = this.hasError;\n this.changedFiles.clear();\n this.needsBrowserReload = false;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Reloading...\"));\n console.log();\n\n try {\n await this.loadAlepha(false, filesToInvalidate);\n await this.alepha?.start();\n\n this.currentError = null;\n if (sendReload || wasInError) {\n this.sendBrowserReload();\n }\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Reload failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n } finally {\n this.isReloading = false;\n this.currentReloadPromise = null;\n\n // If more files changed during reload, schedule another\n if (this.changedFiles.size > 0) {\n this.scheduleReload();\n }\n }\n }\n\n /**\n * Load or reload the Alepha instance.\n */\n protected async loadAlepha(\n isInitialLoad = false,\n filesToInvalidate?: Set<string>,\n ): Promise<Alepha> {\n await this.destroyAlepha();\n this.clearAlephaRefs();\n\n if (isInitialLoad || this.hasError) {\n this.server.moduleGraph.invalidateAll();\n } else {\n this.invalidateModulesWithImporters(filesToInvalidate ?? new Set());\n }\n\n // Snapshot and restore process.env to isolate each reload\n const envSnapshot = { ...process.env };\n await this.setupEnvironment();\n\n try {\n await this.server.ssrLoadModule(this.options.entry.server, {\n fixStacktrace: true,\n });\n } catch (err) {\n this.hasError = true;\n process.env = envSnapshot;\n throw err;\n }\n\n const alepha = this.getLoadedAlepha();\n\n // Expose Vite server to Alepha for Logger SSR stack trace fixing\n alepha.store.set(\"alepha.vite.server\" as any, this.server);\n\n for (const hook of this.alephaLoadedHooks) {\n await hook(alepha, this.server);\n }\n\n this.alepha = alepha;\n await this.setupAlepha();\n\n this.hasError = false;\n process.env = envSnapshot;\n\n return alepha;\n }\n\n /**\n * Setup Alepha instance with dev-specific configuration.\n */\n protected async setupAlepha(): Promise<void> {\n if (!this.alepha || !this.hasReact()) {\n return;\n }\n\n const devHead = await this.generateDevHead();\n const favicon = await this.detectFavicon(join(this.options.root, \"public\"));\n this.alepha.store.set(\"alepha.react.ssr.manifest\", { devHead, favicon });\n }\n\n /**\n * Detect a favicon file in the given directory.\n * Returns \"mimeType:/path\" if found, undefined otherwise.\n */\n protected async detectFavicon(\n publicDir: string,\n ): Promise<string | undefined> {\n const candidates: [string, string][] = [\n [\"favicon.svg\", \"image/svg+xml\"],\n [\"favicon.png\", \"image/png\"],\n [\"favicon.ico\", \"image/x-icon\"],\n ];\n for (const [file, mime] of candidates) {\n if (await this.fs.exists(join(publicDir, file))) {\n return `${mime}:/${file}`;\n }\n }\n return undefined;\n }\n\n /**\n * Generate dev head content for SSR.\n *\n * IMPORTANT: We call transformIndexHtml() on an EMPTY <head> (no script/link\n * tags) to collect plugin-injected preambles — specifically the React Fast\n * Refresh runtime from @vitejs/plugin-react. We then manually append our\n * own browser entry and stylesheet tags.\n *\n * Why not include <script>/<link> tags in the HTML passed to transformIndexHtml?\n * Because Vite would pre-transform the referenced browser entry module, which\n * walks the entire client module graph and triggers dep discovery. This creates\n * a race condition with Vite's background dep scanner: both find the same deps,\n * but the scanner commits a second optimization pass that replaces the first,\n * causing \"504 Outdated Optimize Dep\" errors on cold start.\n *\n * By passing empty HTML, we get the preamble without triggering the module\n * graph walk, leaving the scanner as the single dep discovery mechanism.\n */\n protected async generateDevHead(): Promise<string> {\n const { browser, style } = this.options.entry;\n\n // Get plugin preambles (React Fast Refresh, etc.) without triggering\n // client module graph walk — see JSDoc above for why this matters.\n const emptyHtml = \"<!DOCTYPE html><html><head></head><body></body></html>\";\n const transformed = await this.server.transformIndexHtml(\"/\", emptyHtml);\n const headMatch = transformed.match(/<head>([\\s\\S]*?)<\\/head>/i);\n const preamble = headMatch?.[1]?.trim() ?? \"\";\n\n const tags: string[] = [];\n if (preamble) {\n tags.push(preamble);\n }\n\n // Reload handler: polls /__alepha/ready before reloading to avoid\n // hitting the server while it's still restarting.\n tags.push(`<script type=\"module\">\nif (import.meta.hot) {\n import.meta.hot.on(\"alepha:reload\", async () => {\n for (let i = 0; i < 50; i++) {\n try {\n const res = await fetch(\"/__alepha/ready\");\n if (res.ok) { window.location.reload(); return; }\n } catch {}\n await new Promise(r => setTimeout(r, 200));\n }\n window.location.reload();\n });\n}\n</script>`);\n\n if (style) {\n tags.push(`<link rel=\"stylesheet\" href=\"/${style}\">`);\n }\n if (browser) {\n tags.push(`<script type=\"module\" src=\"/${browser}\"></script>`);\n }\n\n return tags.join(\"\\n\");\n }\n\n /**\n * Setup environment variables for dev mode.\n */\n protected async setupEnvironment(): Promise<void> {\n const { loadEnv } = await this.viteUtils.importVite();\n\n process.env.VITE_ALEPHA_DEV = \"true\";\n process.env.NODE_ENV ??= \"development\";\n\n const mode = process.env.NODE_ENV;\n const env = loadEnv(mode, this.options.root, \"\");\n\n // Merge into process.env (only set if not already defined)\n for (const [key, value] of Object.entries(env)) {\n process.env[key] ??= value;\n }\n\n const port = this.server.config.server.port ?? 3000;\n\n process.env.SERVER_PORT ??= `${port}`;\n }\n\n /**\n * Invalidate modules and all their importers.\n */\n protected invalidateModulesWithImporters(changedFiles: Set<string>): void {\n const graph = this.server.moduleGraph;\n const invalidated = new Set<string>();\n const queue: string[] = [...changedFiles];\n\n while (queue.length > 0) {\n const file = queue.pop()!;\n if (invalidated.has(file)) continue;\n\n const mod = this.server.moduleGraph.getModuleById(file);\n if (!mod) continue;\n\n graph.invalidateModule(mod);\n invalidated.add(file);\n\n for (const importer of mod.importers) {\n if (importer.id && !invalidated.has(importer.id)) {\n queue.push(importer.id);\n }\n }\n }\n\n // Always invalidate entry module\n const entryPath = this.options.entry.server;\n const absoluteEntryPath = join(this.options.root, entryPath);\n const entryMod =\n graph.getModuleById(absoluteEntryPath) ??\n graph.getModuleById(entryPath) ??\n graph.getModuleById(`/${entryPath}`);\n if (entryMod) {\n graph.invalidateModule(entryMod);\n }\n }\n\n /**\n * Wait for file changes and retry loading until successful.\n */\n protected waitForSuccessfulLoad(): Promise<Alepha> {\n this.waitingForRetry = true;\n\n return new Promise((resolve) => {\n const onFileChange = async (file: string) => {\n if (/[/\\\\]\\.idea[/\\\\]/.test(file)) return;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Retrying...\"));\n\n const filesToInvalidate = new Set([file]);\n\n try {\n const alepha = await this.loadAlepha(false, filesToInvalidate);\n this.waitingForRetry = false;\n this.currentError = null;\n this.server.watcher.off(\"change\", onFileChange);\n this.server.watcher.off(\"add\", onFileChange);\n this.sendBrowserReload();\n resolve(alepha);\n } catch (err) {\n this.hasError = true;\n this.currentError =\n err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n }\n };\n\n this.server.watcher.on(\"change\", onFileChange);\n this.server.watcher.on(\"add\", onFileChange);\n });\n }\n\n /**\n * Clear global Alepha references before reload.\n */\n protected clearAlephaRefs(): void {\n __alephaRef.alepha = undefined;\n __alephaRef.service = undefined;\n __alephaRef.parent = undefined;\n (globalThis as any).__alepha = undefined;\n }\n\n /**\n * Destroy the current Alepha instance.\n */\n protected async destroyAlepha(): Promise<void> {\n if (this.alepha) {\n await this.alepha\n .destroy()\n .catch((err) => this.log.warn(\"Error destroying Alepha\", err));\n this.alepha = null;\n }\n }\n\n /**\n * Get the loaded Alepha instance from globalThis.\n */\n protected getLoadedAlepha(): Alepha {\n const alepha: Alepha = (globalThis as any).__alepha;\n if (!alepha) {\n throw new AlephaError(\n \"Alepha instance not found after loading entry module\",\n );\n }\n return alepha;\n }\n\n /**\n * Fix stack trace using Vite's SSR stack trace fixer.\n */\n protected fixStacktrace(error: Error): void {\n this.server.ssrFixStacktrace(error);\n }\n\n /**\n * Log a formatted error with stack trace.\n */\n protected logError(title: string, err: unknown): void {\n const c = this.colors;\n\n console.log();\n console.log(c.set(\"RED\", ` ✗ ${title}`));\n this.logErrorWithCause(err);\n console.log();\n console.log(c.set(\"GREY_DARK\", \" Waiting for file changes to retry...\"));\n console.log();\n }\n\n /**\n * Log error message and stack, recursively logging cause if present.\n */\n protected logErrorWithCause(err: unknown, depth = 0): void {\n const error = err instanceof Error ? err : new Error(String(err));\n const indent = ` ${\" \".repeat(depth)}`;\n\n this.fixStacktrace(error);\n\n const name = error.name || \"Error\";\n const message = error.message || \"Unknown error\";\n const stackLines = error.stack?.split(\"\\n\").slice(1);\n\n console.log();\n if (depth > 0) {\n console.log(this.colors.set(\"GREY_DARK\", `${indent}Caused by:`));\n }\n console.log(this.colors.set(\"WHITE_BOLD\", `${indent + name}: ${message}`));\n if (stackLines?.length) {\n console.log();\n for (const line of stackLines) {\n console.log(`${indent}${this.colors.set(\"GREY_DARK\", line)}`);\n }\n }\n\n if (error.cause) {\n this.logErrorWithCause(error.cause, depth + 1);\n }\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { $inject, $state, Alepha, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { devOptions } from \"../atoms/devOptions.ts\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { ViteDevServerProvider } from \"../providers/ViteDevServerProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class DevCommand {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n protected readonly alepha = $inject(Alepha);\n protected readonly viteDevServer = $inject(ViteDevServerProvider);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly options = $state(devOptions);\n\n /**\n * Will run the project in watch mode.\n *\n * When run from a workspace root (with apps/ directory), spawns all apps in parallel.\n * When run from an app directory, starts a single Vite dev server.\n */\n public readonly dev = $command({\n name: \"dev\",\n mode: true,\n description: \"Run the project in development mode\",\n flags: t.object({\n only: t.optional(\n t.string({\n description:\n \"Run only specific apps (comma-separated: --only api,companion)\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const apps = await this.discoverApps(root);\n\n if (apps.length > 0) {\n await this.runMultiple(root, apps, flags);\n } else {\n await this.runSingle(root);\n }\n },\n });\n\n /**\n * Discover apps in the workspace root.\n *\n * Looks for directories under apps/ that contain a package.json.\n * Supports scoped directories (e.g., apps/@passeo/api).\n * Returns empty array if not in a workspace root.\n */\n protected async discoverApps(\n root: string,\n ): Promise<Array<{ name: string; path: string }>> {\n const appsDir = join(root, \"apps\");\n\n if (!(await this.fs.exists(appsDir))) {\n return [];\n }\n\n const entries = await readdir(appsDir);\n const apps: Array<{ name: string; path: string }> = [];\n\n for (const entry of entries) {\n const appPath = join(appsDir, entry);\n const pkgPath = join(appPath, \"package.json\");\n\n if (await this.fs.exists(pkgPath)) {\n apps.push({ name: entry, path: appPath });\n continue;\n }\n\n // Check scoped directories (e.g., apps/@passeo/api)\n const entryStat = await stat(appPath).catch(() => null);\n if (entryStat?.isDirectory()) {\n const scopedEntries = await readdir(appPath);\n for (const scopedEntry of scopedEntries) {\n const scopedPath = join(appPath, scopedEntry);\n const scopedPkgPath = join(scopedPath, \"package.json\");\n\n if (await this.fs.exists(scopedPkgPath)) {\n apps.push({ name: scopedEntry, path: scopedPath });\n }\n }\n }\n }\n\n return apps;\n }\n\n /**\n * Run a single app (existing behavior).\n */\n protected async runSingle(root: string): Promise<void> {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const entry = await this.boot.getAppEntry(root);\n this.log.debug(\"Entry file found\", { entry });\n\n const options = this.options;\n\n await this.viteDevServer.init({\n root,\n entry,\n noViteReactPlugin: options.noViteReactPlugin ?? false,\n });\n\n await this.viteDevServer.start();\n }\n\n /**\n * Run multiple apps in parallel with colored prefixed output.\n */\n protected async runMultiple(\n _root: string,\n apps: Array<{ name: string; path: string }>,\n flags: Record<string, unknown>,\n ): Promise<void> {\n const only = flags.only as string | undefined;\n\n if (only) {\n const filter = only.split(\",\").map((s) => s.trim().toLowerCase());\n apps = apps.filter((app) => filter.includes(app.name.toLowerCase()));\n }\n\n if (apps.length === 0) {\n this.log.warn(\"No apps found to run\");\n return;\n }\n\n this.log.debug(\n `Starting ${apps.length} apps: ${apps.map((a) => a.name).join(\", \")}`,\n );\n\n const basePort = 5173;\n const processes = apps.map((app, i) => this.spawnApp(app, basePort + i));\n\n // Handle graceful shutdown\n const cleanup = () => {\n for (const proc of processes) {\n proc.kill(\"SIGTERM\");\n }\n };\n\n process.once(\"SIGINT\", cleanup);\n process.once(\"SIGTERM\", cleanup);\n\n // Wait for all processes (they run until killed)\n await Promise.allSettled(\n processes.map(\n (proc) =>\n new Promise<void>((resolve) => {\n proc.on(\"exit\", () => resolve());\n }),\n ),\n );\n }\n\n /**\n * Spawn a single app process with inherited stdio.\n *\n * Each child process gets APP_NAME set, so the Alepha logger\n * handles prefixing automatically.\n */\n protected spawnApp(\n app: { name: string; path: string },\n port: number,\n ): ReturnType<typeof spawn> {\n const proc = spawn(\"yarn\", [\"alepha\", \"dev\"], {\n cwd: app.path,\n stdio: \"inherit\",\n env: {\n ...process.env,\n APP_NAME: app.name.toUpperCase(),\n SERVER_PORT: String(port),\n FORCE_COLOR: \"1\",\n },\n });\n\n proc.on(\"exit\", (code) => {\n if (code !== 0 && code !== null) {\n this.log.error(`${app.name} exited with code ${code}`);\n }\n });\n\n return proc;\n }\n}\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Default scopes to ignore in changelog generation.\n * Commits with these scopes won't appear in release notes.\n */\nexport const DEFAULT_IGNORE = [\n \"project\",\n \"release\",\n \"starter\",\n \"example\",\n \"chore\",\n \"ci\",\n \"build\",\n \"test\",\n \"style\",\n];\n\n/**\n * Changelog configuration atom.\n *\n * Configure in `alepha.config.ts`:\n * ```ts\n * import { changelogOptions } from \"alepha/cli\";\n *\n * alepha.set(changelogOptions, {\n * ignore: [\"project\", \"release\", \"chore\", \"docs\"],\n * });\n * ```\n */\nexport const changelogOptions = $atom({\n name: \"alepha.cli.changelog.options\",\n schema: t.object({\n /**\n * Scopes to ignore (e.g., \"project\", \"release\", \"chore\").\n * Commits like `feat(chore): ...` will be excluded from changelog.\n */\n ignore: t.optional(t.array(t.string())),\n }),\n default: {\n ignore: DEFAULT_IGNORE,\n },\n});\n\nexport type ChangelogOptions = Static<typeof changelogOptions.schema>;\n","import { $logger } from \"alepha/logger\";\nimport {\n type ChangelogOptions,\n DEFAULT_IGNORE,\n} from \"../atoms/changelogOptions.ts\";\nimport type { Commit } from \"../commands/gen/changelog.ts\";\n\n/**\n * Service for parsing git commit messages into structured format.\n *\n * Only parses **conventional commits with a scope**:\n * - `feat(scope): description` → feature\n * - `fix(scope): description` → bug fix\n * - `feat(scope)!: description` → breaking change\n *\n * Commits without scope are ignored, allowing developers to commit\n * work-in-progress changes without polluting release notes:\n * - `cli: work in progress` → ignored (no type)\n * - `fix: quick patch` → ignored (no scope)\n * - `feat(cli): add command` → included\n */\nexport class GitMessageParser {\n protected readonly log = $logger();\n\n /**\n * Parse a git commit line into a structured Commit object.\n *\n * **Format:** `type(scope): description` or `type(scope)!: description`\n *\n * **Supported types:** feat, fix, docs, refactor, perf, revert\n *\n * **Breaking changes:** Use `!` before `:` (e.g., `feat(api)!: remove endpoint`)\n *\n * @returns Commit object or null if not matching/ignored\n */\n parseCommit(line: string, config: ChangelogOptions): Commit | null {\n // Extract hash and message from git log --oneline format\n const match = line.match(/^([a-f0-9]+)\\s+(.+)$/);\n if (!match) return null;\n\n const [, hash, message] = match;\n const ignore = config.ignore ?? DEFAULT_IGNORE;\n\n // Conventional commit with REQUIRED scope: type(scope): description\n // The `!` before `:` marks a breaking change\n const conventionalMatch = message.match(\n /^(feat|fix|docs|refactor|perf|revert)\\(([^)]+)\\)(!)?:\\s*(.+)$/i,\n );\n\n if (!conventionalMatch) {\n // No match - commit doesn't follow required format\n return null;\n }\n\n const [, type, scope, breakingMark, description] = conventionalMatch;\n\n // Check if scope should be ignored\n const baseScope = scope.split(\"/\")[0];\n if (ignore.includes(baseScope) || ignore.includes(scope)) {\n return null;\n }\n\n // Breaking change detection:\n // 1. Explicit `!` marker: feat(api)!: change\n // 2. Word \"breaking\" in description: feat(api): breaking change to auth\n const breaking =\n breakingMark === \"!\" || description.toLowerCase().includes(\"breaking\");\n\n return {\n hash: hash.substring(0, 8),\n type: type.toLowerCase(),\n scope,\n description: description.trim(),\n breaking,\n };\n }\n}\n","import { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { $inject, $state, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { changelogOptions } from \"../../atoms/changelogOptions.ts\";\nimport { GitMessageParser } from \"../../services/GitMessageParser.ts\";\n\nexport {\n type ChangelogOptions,\n changelogOptions,\n DEFAULT_IGNORE,\n} from \"../../atoms/changelogOptions.ts\";\nexport { GitMessageParser } from \"../../services/GitMessageParser.ts\";\n\nconst execAsync = promisify(exec);\n\n// =============================================================================\n// GIT PROVIDER\n// =============================================================================\n\n/**\n * Git provider for executing git commands.\n * Can be substituted in tests with a mock implementation.\n */\nexport class GitProvider {\n async exec(cmd: string, cwd: string): Promise<string> {\n const { stdout } = await execAsync(`git ${cmd}`, { cwd });\n return stdout;\n }\n}\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface Commit {\n hash: string;\n type: string;\n scope: string | null;\n description: string;\n breaking: boolean;\n}\n\ninterface ChangelogEntry {\n features: Commit[];\n fixes: Commit[];\n}\n\n// =============================================================================\n// CHANGELOG COMMAND\n// =============================================================================\n\n/**\n * Changelog command for generating release notes from git commits.\n *\n * Usage:\n * - `alepha gen changelog` - Show unreleased changes since latest tag to HEAD\n * - `alepha gen changelog --from=1.0.0` - Show changes from version to HEAD\n * - `alepha gen changelog --from=1.0.0 --to=1.1.0` - Show changes between two refs\n * - `alepha gen changelog | tee -a CHANGELOG.md` - Append to file\n */\nexport class ChangelogCommand {\n protected readonly log = $logger();\n protected readonly git = $inject(GitProvider);\n protected readonly parser = $inject(GitMessageParser);\n protected readonly config = $state(changelogOptions);\n\n // ---------------------------------------------------------------------------\n // FORMATTING\n // ---------------------------------------------------------------------------\n\n /**\n * Format a single commit line.\n * Example: `- **cli**: add new command (\\`abc1234\\`)`\n * Breaking changes are flagged: `- **cli**: add new command [BREAKING] (\\`abc1234\\`)`\n */\n protected formatCommit(commit: Commit): string {\n const breaking = commit.breaking ? \" [BREAKING]\" : \"\";\n return `- **${commit.scope}**: ${commit.description}${breaking} (\\`${commit.hash}\\`)`;\n }\n\n /**\n * Format the changelog entry with sections.\n */\n protected formatEntry(entry: ChangelogEntry): string {\n const sections: string[] = [];\n\n if (entry.features.length > 0) {\n sections.push(\"### Features\\n\");\n for (const commit of entry.features) {\n sections.push(this.formatCommit(commit));\n }\n sections.push(\"\");\n }\n\n if (entry.fixes.length > 0) {\n sections.push(\"### Bug Fixes\\n\");\n for (const commit of entry.fixes) {\n sections.push(this.formatCommit(commit));\n }\n sections.push(\"\");\n }\n\n return sections.join(\"\\n\");\n }\n\n // ---------------------------------------------------------------------------\n // PARSING\n // ---------------------------------------------------------------------------\n\n /**\n * Parse git log output into a changelog entry.\n */\n protected parseCommits(commitsOutput: string): ChangelogEntry {\n const entry: ChangelogEntry = {\n features: [],\n fixes: [],\n };\n\n for (const line of commitsOutput.trim().split(\"\\n\")) {\n if (!line.trim()) continue;\n\n const commit = this.parser.parseCommit(line, this.config);\n if (!commit) {\n this.log.trace(\"Skipping commit\", { line });\n continue;\n }\n\n this.log.trace(\"Parsed commit\", { commit });\n\n // Categorize commit (breaking flag is preserved on the commit itself)\n if (commit.type === \"feat\") {\n entry.features.push(commit);\n } else if (commit.type === \"fix\") {\n entry.fixes.push(commit);\n }\n }\n\n return entry;\n }\n\n /**\n * Check if entry has any public commits.\n */\n protected hasChanges(entry: ChangelogEntry): boolean {\n return entry.features.length > 0 || entry.fixes.length > 0;\n }\n\n /**\n * Get the latest version tag.\n */\n protected async getLatestTag(\n git: (cmd: string) => Promise<string>,\n ): Promise<string | null> {\n const tagsOutput = await git(\"tag --sort=-version:refname\");\n const tags = tagsOutput\n .trim()\n .split(\"\\n\")\n .filter((tag) => tag.match(/^\\d+\\.\\d+\\.\\d+$/));\n\n return tags[0] || null;\n }\n\n // ---------------------------------------------------------------------------\n // COMMAND\n // ---------------------------------------------------------------------------\n\n public readonly command = $command({\n name: \"changelog\",\n description:\n \"Generate changelog from conventional commits (outputs to stdout)\",\n flags: t.object({\n /**\n * Show changes from this ref (tag, commit, branch).\n * Defaults to the latest version tag.\n * Example: --from=1.0.0\n */\n from: t.optional(\n t.string({\n aliases: [\"f\"],\n description: \"Starting ref (default: latest tag)\",\n }),\n ),\n /**\n * Show changes up to this ref (tag, commit, branch).\n * Defaults to HEAD.\n * Example: --to=main\n */\n to: t.optional(\n t.string({\n aliases: [\"t\"],\n description: \"Ending ref (default: HEAD)\",\n }),\n ),\n }),\n handler: async ({ flags, root }) => {\n const git = (cmd: string) => this.git.exec(cmd, root);\n\n // Determine the starting point\n let fromRef: string;\n\n if (flags.from) {\n // User specified a ref\n fromRef = flags.from;\n this.log.debug(\"Using specified from ref\", { from: fromRef });\n } else {\n // Use latest tag\n const latestTag = await this.getLatestTag(git);\n if (!latestTag) {\n process.stdout.write(\"No version tags found in repository\\n\");\n return;\n }\n fromRef = latestTag;\n this.log.debug(\"Using latest tag\", { from: fromRef });\n }\n\n // Determine the ending point\n const toRef = flags.to || \"HEAD\";\n this.log.debug(\"Using to ref\", { to: toRef });\n\n // Get commits in range\n const commitsOutput = await git(`log ${fromRef}..${toRef} --oneline`);\n\n if (!commitsOutput.trim()) {\n process.stdout.write(`No changes in range ${fromRef}..${toRef}\\n`);\n return;\n }\n\n // Parse and format\n const entry = this.parseCommits(commitsOutput);\n\n if (!this.hasChanges(entry)) {\n process.stdout.write(\n `No public changes in range ${fromRef}..${toRef}\\n`,\n );\n return;\n }\n\n // Output the formatted changelog (no header - caller adds it if needed)\n process.stdout.write(this.formatEntry(entry));\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../../services/AlephaCliUtils.ts\";\n\nexport class GenEnvCommand {\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly fs = $inject(FileSystemProvider);\n\n public readonly command = $command({\n name: \"env\",\n description: \"Extract environment variables from server entry file\",\n flags: t.object({\n out: t.optional(\n t.text({\n aliases: [\"o\"],\n description: \"Output file path (e.g., .env)\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n root,\n mode: \"development\",\n });\n\n try {\n const { env } = alepha.dump();\n\n let dotEnvFile = \"\";\n for (const [key, value] of Object.entries(env)) {\n if (value.description) {\n dotEnvFile += `# ${value.description.split(\"\\n\").join(\"\\n# \")}\\n`;\n }\n if (value.required && !value.default) {\n dotEnvFile += `# (required)\\n`;\n }\n if (value.enum) {\n dotEnvFile += `# Possible values: ${value.enum.join(\", \")}\\n`;\n }\n dotEnvFile += `#${key}=${value.default || \"\"}\\n\\n`;\n }\n\n if (flags.out) {\n await this.fs.writeFile(this.fs.join(root, flags.out), dotEnvFile);\n } else {\n this.log.info(dotEnvFile);\n }\n } catch (err) {\n this.log.error(\"Failed to extract environment variables\", err);\n }\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { ServerSwaggerProvider } from \"alepha/server/swagger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../../services/AlephaCliUtils.ts\";\n\nexport class OpenApiCommand {\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly fs = $inject(FileSystemProvider);\n\n public readonly command = $command({\n name: \"openapi\",\n description: \"Generate OpenAPI specification from actions\",\n flags: t.object({\n out: t.optional(\n t.text({\n aliases: [\"o\"],\n description: \"Output file path\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n root,\n mode: \"development\",\n });\n\n try {\n const openapiProvider = alepha.inject(\n ServerSwaggerProvider,\n ) as ServerSwaggerProvider;\n\n await alepha.events.emit(\"configure\", alepha);\n\n let json: any = openapiProvider.json;\n\n if (!json) {\n json = openapiProvider.generateSwaggerDoc({\n info: {\n title: \"API Documentation\",\n version: \"1.0.0\",\n },\n });\n }\n\n if (!json) {\n this.log.error(\"No actions found to generate OpenAPI specification.\");\n return;\n }\n\n if (flags.out) {\n await this.fs.writeFile(\n this.fs.join(root, flags.out),\n JSON.stringify(json, null, 2),\n );\n } else {\n this.log.info(JSON.stringify(json, null, 2));\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (message.includes(\"Service not found\")) {\n this.log.error(\n \"Missing $swagger() primitive in your server configuration.\",\n );\n return;\n }\n\n this.log.error(`OpenAPI generation failed - ${message}`, err);\n }\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { ChangelogCommand } from \"./gen/changelog.ts\";\nimport { GenEnvCommand } from \"./gen/env.ts\";\nimport { OpenApiCommand } from \"./gen/openapi.ts\";\n\nexport class GenCommand {\n protected readonly changelog = $inject(ChangelogCommand);\n protected readonly openapi = $inject(OpenApiCommand);\n protected readonly genEnv = $inject(GenEnvCommand);\n\n public readonly gen = $command({\n name: \"gen\",\n description: \"Generate code, documentation, ...\",\n children: [\n this.changelog.command,\n this.openapi.command,\n this.genEnv.command,\n ],\n handler: async ({ help }) => {\n help();\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class InitCommand {\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n /**\n * Ensure the project has the necessary Alepha configuration files.\n * Add the correct dependencies to package.json and install them.\n */\n public readonly init = $command({\n name: \"init\",\n description: \"Add missing Alepha configuration files to the project\",\n args: t.optional(\n t.text({\n title: \"path\",\n trim: true,\n lowercase: true,\n }),\n ),\n flags: t.object({\n pm: t.optional(\n t.enum([\"yarn\", \"npm\", \"pnpm\", \"bun\"], {\n description: \"Package manager to use\",\n }),\n ),\n // choose which modules to scaffold\n api: t.optional(\n t.boolean({\n description: \"Include API module structure (src/api/)\",\n }),\n ),\n react: t.optional(\n t.boolean({\n aliases: [\"r\"],\n description: \"Include React dependencies and web module (src/web/)\",\n }),\n ),\n ui: t.optional(\n t.boolean({\n description:\n \"Include @alepha/ui (components, auth portal, admin portal)\",\n }),\n ),\n saas: t.optional(\n t.boolean({\n description:\n \"Include authentication, admin portal, API, UI, and React. Everything you need for a SaaS app.\",\n }),\n ),\n tailwind: t.optional(\n t.boolean({\n description: \"Include Tailwind CSS with Vite plugin. Implies --react\",\n }),\n ),\n test: t.optional(\n t.boolean({ description: \"Include Vitest and create test directory\" }),\n ),\n force: t.optional(\n t.boolean({\n aliases: [\"f\"],\n description: \"Override existing files\",\n }),\n ),\n }),\n handler: async ({ run, flags, root, args }) => {\n await this.scaffolder.init({ run, flags, root, args });\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class LintCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly lint = $command({\n name: \"lint\",\n description: \"Run linter across the codebase using Biome\",\n handler: async ({ run, root }) => {\n await this.scaffolder.ensureConfig(root, {\n biomeJson: true,\n checkWorkspace: true,\n });\n\n await this.pm.ensureDependency(root, \"@biomejs/biome\", {\n checkWorkspace: true,\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n await run(\"biome check --fix\");\n },\n });\n}\n","import { $inject, Alepha, t } from \"alepha\";\nimport { $command, CliProvider } from \"alepha/command\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { version } from \"../version.ts\";\n\nexport class RootCommand {\n protected readonly log = $logger();\n protected readonly cli = $inject(CliProvider);\n protected readonly alepha = $inject(Alepha);\n protected readonly color = $inject(ConsoleColorProvider);\n\n /**\n * Called when no command is provided\n */\n public readonly root = $command({\n root: true,\n flags: t.object({\n version: t.optional(\n t.boolean({\n description: \"Show Alepha CLI version\",\n aliases: [\"v\"],\n }),\n ),\n }),\n handler: async ({ flags }) => {\n if (flags.version) {\n this.log.info(this.color.set(\"WHITE_BOLD\", `Alepha v${version}`));\n if (this.alepha.isBun()) {\n this.log.info(this.color.set(\"GREY_DARK\", `└─ Bun v${Bun.version}`));\n } else {\n this.log.info(\n this.color.set(\"GREY_DARK\", `└─ Node ${process.version}`),\n );\n }\n return;\n }\n\n this.cli.printHelp();\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TestCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly test = $command({\n name: \"test\",\n description: \"Run tests using Vitest\",\n flags: t.object({\n config: t.optional(\n t.string({\n description: \"Path to Vitest config file\",\n alias: \"c\",\n }),\n ),\n }),\n env: t.object({\n VITEST_ARGS: t.optional(\n t.string({\n default: \"\",\n description:\n \"Additional arguments to pass to Vitest. E.g., --coverage\",\n }),\n ),\n }),\n handler: async ({ run, root, flags, env }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n // Ensure vitest is installed before running\n await this.pm.ensureDependency(root, \"vitest\", {\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n const config = flags.config ? `--config=${flags.config}` : \"\";\n\n await run(`vitest run ${config} ${env.VITEST_ARGS}`);\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TypecheckCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly log = $logger();\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n /**\n * Run TypeScript type checking across the codebase with no emit.\n */\n public readonly typecheck = $command({\n name: \"typecheck\",\n aliases: [\"tc\"],\n description: \"Check TypeScript types across the codebase\",\n handler: async ({ run, root }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n checkWorkspace: true,\n });\n\n await this.pm.ensureDependency(root, \"typescript\", {\n checkWorkspace: true,\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n await run(\"tsc --noEmit\");\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\n\nexport class VerifyCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n\n /**\n * Run a series of verification commands to ensure code quality and correctness.\n *\n * This command runs the following checks in order:\n * - Clean the project\n * - Format the code\n * - Lint the code\n * - Run tests (if Vitest is a dev dependency)\n * - Check database migrations (if a migrations directory exists)\n * - Type check the code\n * - Build the project\n * - Clean the project again\n */\n public readonly verify = $command({\n name: \"verify\",\n description: \"Verify the Alepha project\",\n handler: async ({ root, run }) => {\n await run(\"alepha clean\");\n await run(\"alepha lint\");\n\n await run(\"alepha typecheck\");\n\n const pkg = await this.pm.readPackageJson(root);\n if (pkg.devDependencies?.vitest) {\n await run(\"alepha test\");\n }\n\n if (await this.utils.exists(root, \"migrations\")) {\n await run(\"alepha db migrations check\");\n }\n\n const isExpo = await this.pm.hasExpo(root);\n if (!isExpo) {\n await run(\"alepha build\");\n }\n await run(\"alepha clean\");\n },\n });\n}\n","import { pathToFileURL } from \"node:url\";\nimport { $hook, $inject, Alepha } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\n\nexport class AlephaCliExtensionProvider {\n protected readonly alepha = $inject(Alepha);\n protected readonly fs = $inject(FileSystemProvider);\n\n protected readonly onConfigure = $hook({\n on: \"configure\",\n handler: async () => {\n const root = process.cwd();\n const extensionPath = this.fs.join(root, \"alepha.config.ts\");\n const hasExtension = await this.fs.exists(extensionPath);\n if (!hasExtension) {\n return;\n }\n\n // import (use file:// URL for Windows compatibility)\n const extensionUrl = pathToFileURL(extensionPath).href;\n const { default: Extension } = await import(extensionUrl);\n if (typeof Extension !== \"function\") {\n return;\n }\n\n this.alepha.inject(Extension, {\n args: [this.alepha],\n });\n },\n });\n}\n","import { $module } from \"alepha\";\nimport { appEntryOptions } from \"./atoms/appEntryOptions.ts\";\nimport { buildOptions } from \"./atoms/buildOptions.ts\";\nimport { devOptions } from \"./atoms/devOptions.ts\";\nimport { BuildCommand } from \"./commands/build.ts\";\nimport { CleanCommand } from \"./commands/clean.ts\";\nimport { DbCommand } from \"./commands/db.ts\";\nimport { DevCommand } from \"./commands/dev.ts\";\nimport {\n changelogOptions,\n GitMessageParser,\n GitProvider,\n} from \"./commands/gen/changelog.ts\";\nimport { GenCommand } from \"./commands/gen.ts\";\nimport { InitCommand } from \"./commands/init.ts\";\nimport { LintCommand } from \"./commands/lint.ts\";\nimport { RootCommand } from \"./commands/root.ts\";\nimport { TestCommand } from \"./commands/test.ts\";\nimport { TypecheckCommand } from \"./commands/typecheck.ts\";\nimport { VerifyCommand } from \"./commands/verify.ts\";\nimport { AlephaCliExtensionProvider } from \"./providers/AlephaCliExtensionProvider.ts\";\nimport { AppEntryProvider } from \"./providers/AppEntryProvider.ts\";\nimport { ViteBuildProvider } from \"./providers/ViteBuildProvider.ts\";\nimport { ViteDevServerProvider } from \"./providers/ViteDevServerProvider.ts\";\nimport { AlephaCliUtils } from \"./services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"./services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"./services/ProjectScaffolder.ts\";\nimport { ViteUtils } from \"./services/ViteUtils.ts\";\nimport { BuildAssetsTask } from \"./tasks/BuildAssetsTask.ts\";\nimport { BuildClientTask } from \"./tasks/BuildClientTask.ts\";\nimport { BuildCloudflareTask } from \"./tasks/BuildCloudflareTask.ts\";\nimport { BuildCompressTask } from \"./tasks/BuildCompressTask.ts\";\nimport { BuildDockerTask } from \"./tasks/BuildDockerTask.ts\";\nimport { BuildPrerenderTask } from \"./tasks/BuildPrerenderTask.ts\";\nimport { BuildServerTask } from \"./tasks/BuildServerTask.ts\";\nimport { BuildSitemapTask } from \"./tasks/BuildSitemapTask.ts\";\nimport { BuildStaticTask } from \"./tasks/BuildStaticTask.ts\";\nimport { BuildVercelTask } from \"./tasks/BuildVercelTask.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./atoms/appEntryOptions.ts\";\nexport * from \"./atoms/buildOptions.ts\";\nexport * from \"./atoms/changelogOptions.ts\";\nexport * from \"./atoms/devOptions.ts\";\nexport * from \"./commands/build.ts\";\nexport * from \"./commands/clean.ts\";\nexport * from \"./commands/db.ts\";\nexport * from \"./commands/dev.ts\";\nexport * from \"./commands/gen/changelog.ts\";\nexport * from \"./commands/gen/openapi.ts\";\nexport * from \"./commands/init.ts\";\nexport * from \"./commands/lint.ts\";\nexport * from \"./commands/root.ts\";\nexport * from \"./commands/test.ts\";\nexport * from \"./commands/typecheck.ts\";\nexport * from \"./commands/verify.ts\";\nexport * from \"./providers/AlephaCliExtensionProvider.ts\";\nexport * from \"./providers/AppEntryProvider.ts\";\nexport * from \"./providers/ViteBuildProvider.ts\";\nexport * from \"./providers/ViteDevServerProvider.ts\";\nexport * from \"./services/AlephaCliUtils.ts\";\nexport * from \"./services/GitMessageParser.ts\";\nexport * from \"./services/PackageManagerUtils.ts\";\nexport * from \"./services/ProjectScaffolder.ts\";\nexport * from \"./services/ViteUtils.ts\";\nexport * from \"./tasks/BuildAssetsTask.ts\";\nexport * from \"./tasks/BuildClientTask.ts\";\nexport * from \"./tasks/BuildCloudflareTask.ts\";\nexport * from \"./tasks/BuildCompressTask.ts\";\nexport * from \"./tasks/BuildDockerTask.ts\";\nexport * from \"./tasks/BuildPrerenderTask.ts\";\nexport * from \"./tasks/BuildServerTask.ts\";\nexport * from \"./tasks/BuildSitemapTask.ts\";\nexport * from \"./tasks/BuildStaticTask.ts\";\nexport * from \"./tasks/BuildTask.ts\";\nexport * from \"./tasks/BuildVercelTask.ts\";\nexport * from \"./version.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Services, providers, and build tasks — no commands.\n * Use this module when you need CLI utilities without registering commands.\n */\nexport const AlephaCliServices = $module({\n name: \"alepha.cli.services\",\n services: [\n // Services & providers\n AlephaCliUtils,\n PackageManagerUtils,\n ViteUtils,\n ProjectScaffolder,\n AppEntryProvider,\n GitMessageParser,\n GitProvider,\n ViteDevServerProvider,\n ViteBuildProvider,\n ],\n});\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Full CLI module — all services and commands.\n */\nexport const AlephaCli = $module({\n name: \"alepha.cli\",\n atoms: [appEntryOptions, buildOptions, changelogOptions, devOptions],\n services: [\n AlephaCliExtensionProvider,\n // Commands\n BuildCommand,\n CleanCommand,\n DbCommand,\n DevCommand,\n InitCommand,\n LintCommand,\n RootCommand,\n TestCommand,\n TypecheckCommand,\n VerifyCommand,\n GenCommand,\n // Build tasks\n BuildAssetsTask,\n BuildClientTask,\n BuildCloudflareTask,\n BuildCompressTask,\n BuildDockerTask,\n BuildPrerenderTask,\n BuildServerTask,\n BuildSitemapTask,\n BuildStaticTask,\n BuildVercelTask,\n ],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA,MAAa,kBAAkB,MAAM;CACnC,MAAM;CACN,QAAQ,EAAE,OAAO;EACf,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC;EAC5B,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;EAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC;EAC5B,CAAC;CACF,SAAS,EAAE;CACZ,CAAC;;;;;;;;;ACqBF,MAAa,eAAe,MAAM;CAChC,MAAM;CACN,aAAa;CACb,QAAQ,EAAE,OAAO;EAOf,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;EAS3D,QAAQ,EAAE,SACR,EAAE,KAAK;GAAC;GAAQ;GAAU;GAAU;GAAc;GAAS,CAAC,CAC7D;EAaD,SAAS,EAAE,SAAS,EAAE,KAAK;GAAC;GAAQ;GAAO;GAAU,CAAC,CAAC;EAKvD,QAAQ,EAAE,SACR,EAAE,OAAO;GAMP,MAAM,EAAE,SAAS,EAAE,O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AW,EAC5B,MAAM,CAAC,KAAK,OAAO,EACpB,CAAC;;EAEL,CAAC;;;;;;;;ACwDJ,MAAa,oBAAoB,QAAQ;CACvC,MAAM;CACN,UAAU;EAER;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;CACF,CAAC;;;;AAOF,MAAa,YAAY,QAAQ;CAC/B,MAAM;CACN,OAAO;EAAC;EAAiB;EAAc;EAAkB;EAAW;CACpE,UAAU;EACR;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["alephaPackageJson.devDependencies","devDependencies","viteAnalyzer","gzipCb","brotliCompressCb","viteAnalyzer"],"sources":["../../../src/cli/core/atoms/appEntryOptions.ts","../../../src/cli/core/atoms/buildOptions.ts","../../../src/cli/core/atoms/devOptions.ts","../../../src/cli/core/providers/AppEntryProvider.ts","../../../src/cli/core/services/ViteUtils.ts","../../../src/cli/core/providers/ViteBuildProvider.ts","../../../src/cli/core/services/AlephaCliUtils.ts","../../../package.json","../../../src/cli/core/version.ts","../../../src/cli/core/services/PackageManagerUtils.ts","../../../src/cli/core/assets.ts","../../../src/cli/core/templates/agentMd.ts","../../../src/cli/core/templates/alephaConfigTs.ts","../../../src/cli/core/templates/apiAppSecurityTs.ts","../../../src/cli/core/templates/apiHelloControllerTs.ts","../../../src/cli/core/templates/apiHelloResponseSchemaTs.ts","../../../src/cli/core/templates/apiIndexTs.ts","../../../src/cli/core/templates/biomeJson.ts","../../../src/cli/core/templates/dummySpecTs.ts","../../../src/cli/core/templates/editorconfig.ts","../../../src/cli/core/templates/gitignore.ts","../../../src/cli/core/templates/mainBrowserTs.ts","../../../src/cli/core/templates/mainCss.ts","../../../src/cli/core/templates/mainServerTs.ts","../../../src/cli/core/templates/tsconfigJson.ts","../../../src/cli/core/templates/viteConfigTs.ts","../../../src/cli/core/templates/webAdminDashboardTsx.ts","../../../src/cli/core/templates/webAppRouterTs.ts","../../../src/cli/core/templates/webHomeComponentTsx.ts","../../../src/cli/core/templates/webIndexTs.ts","../../../src/cli/core/services/ProjectScaffolder.ts","../../../src/cli/core/tasks/BuildTask.ts","../../../src/cli/core/tasks/BuildAssetsTask.ts","../../../src/cli/core/tasks/BuildClientTask.ts","../../../src/cli/core/tasks/BuildCloudflareTask.ts","../../../src/cli/core/tasks/BuildCompressTask.ts","../../../src/cli/core/tasks/BuildDockerTask.ts","../../../src/cli/core/tasks/BuildPrerenderTask.ts","../../../src/cli/core/tasks/BuildServerTask.ts","../../../src/cli/core/tasks/BuildSitemapTask.ts","../../../src/cli/core/tasks/BuildStaticTask.ts","../../../src/cli/core/tasks/BuildVercelTask.ts","../../../src/cli/core/commands/build.ts","../../../src/cli/core/commands/clean.ts","../../../src/cli/core/commands/db.ts","../../../src/cli/core/providers/ViteDevServerProvider.ts","../../../src/cli/core/commands/dev.ts","../../../src/cli/core/atoms/changelogOptions.ts","../../../src/cli/core/services/GitMessageParser.ts","../../../src/cli/core/commands/gen/changelog.ts","../../../src/cli/core/commands/gen/env.ts","../../../src/cli/core/commands/gen/openapi.ts","../../../src/cli/core/commands/gen.ts","../../../src/cli/core/commands/init.ts","../../../src/cli/core/commands/lint.ts","../../../src/cli/core/commands/root.ts","../../../src/cli/core/commands/test.ts","../../../src/cli/core/commands/typecheck.ts","../../../src/cli/core/commands/verify.ts","../../../src/cli/core/providers/AlephaCliExtensionProvider.ts","../../../src/cli/core/index.ts"],"sourcesContent":["import { $atom, type Static, t } from \"alepha\";\n\nexport const appEntryOptions = $atom({\n name: \"alepha.cli.appEntry.options\",\n schema: t.object({\n server: t.optional(t.text()),\n browser: t.optional(t.text()),\n style: t.optional(t.text()),\n }),\n default: {},\n});\n\nexport type AppEntryOptions = Static<typeof appEntryOptions.schema>;\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Deployment target for the build output.\n *\n * - `docker` - Generate Dockerfile for containerized deployment\n * - `vercel` - Generate Vercel deployment configuration (forces node runtime)\n * - `cloudflare` - Generate Cloudflare Workers configuration (forces workerd runtime)\n */\nexport type BuildTarget =\n | \"bare\"\n | \"docker\"\n | \"vercel\"\n | \"cloudflare\"\n | \"static\";\n\n/**\n * JavaScript runtime for the build output.\n *\n * - `node` - Node.js runtime (default)\n * - `bun` - Bun runtime (uses bun export conditions)\n * - `workerd` - Cloudflare Workers runtime (auto-set with cloudflare target)\n */\nexport type BuildRuntime = \"node\" | \"bun\" | \"workerd\";\n\n/**\n * Build options atom for CLI build command.\n *\n * Defines the available build configuration options with their defaults.\n * Options can be overridden via alepha.config.ts or CLI flags.\n */\nexport const buildOptions = $atom({\n name: \"alepha.cli.build.options\",\n description: \"Build configuration options\",\n schema: t.object({\n /**\n * Generate build stats report.\n *\n * - `true` - Generate a static HTML report\n * - `\"json\"` - Generate a JSON report\n */\n stats: t.optional(t.union([t.boolean(), t.enum([\"json\"])])),\n\n /**\n * Deployment target for the build output.\n *\n * - `docker` - Generate Dockerfile for containerized deployment\n * - `vercel` - Generate Vercel deployment configuration (forces node runtime)\n * - `cloudflare` - Generate Cloudflare Workers configuration (forces workerd runtime)\n */\n target: t.optional(\n t.enum([\"bare\", \"docker\", \"vercel\", \"cloudflare\", \"static\"]),\n ),\n\n /**\n * JavaScript runtime for the build output.\n *\n * - `node` - Node.js runtime (default)\n * - `bun` - Bun runtime (uses bun export conditions)\n * - `workerd` - Cloudflare Workers runtime (auto-set with cloudflare target)\n *\n * Note: Some targets force a specific runtime:\n * - `cloudflare` always uses `workerd`\n * - `vercel` always uses `node`\n */\n runtime: t.optional(t.enum([\"node\", \"bun\", \"workerd\"])),\n\n /**\n * Output directory configuration.\n */\n output: t.optional(\n t.object({\n /**\n * Root dist directory.\n *\n * @default \"dist\"\n */\n dist: t.optional(t.string({ default: \"dist\" })),\n\n /**\n * Public/client subdirectory.\n *\n * @default \"public\"\n */\n public: t.optional(t.string({ default: \"public\" })),\n }),\n ),\n\n /**\n * Vercel-specific deployment configuration.\n *\n * Note: Set `target: \"vercel\"` to enable Vercel deployment.\n * This object is only for additional configuration.\n */\n vercel: t.optional(\n t.object({\n projectName: t.optional(t.string()),\n orgId: t.optional(t.string()),\n projectId: t.optional(t.string()),\n config: t.optional(\n t.object({\n crons: t.optional(\n t.array(\n t.object({\n path: t.string(),\n schedule: t.string(),\n }),\n ),\n ),\n }),\n ),\n }),\n ),\n\n /**\n * Cloudflare-specific deployment configuration.\n *\n * Note: Set `target: \"cloudflare\"` to enable Cloudflare deployment.\n * This object is only for additional configuration.\n */\n cloudflare: t.optional(\n t.object({\n config: t.optional(t.json()),\n }),\n ),\n\n /**\n * Docker-specific deployment configuration.\n *\n * Note: Set `target: \"docker\"` to enable Docker deployment.\n * This object is only for additional configuration.\n */\n docker: t.optional(\n t.object({\n /**\n * Base image for the Dockerfile (FROM instruction).\n *\n * @default \"node:24-alpine\" for node runtime\n * @default \"oven/bun:alpine\" for bun runtime\n */\n from: t.optional(t.string()),\n\n /**\n * Command to run in the Docker container.\n *\n * @default \"node\" for node runtime\n * @default \"bun\" for bun runtime\n */\n command: t.optional(t.string()),\n\n /**\n * Docker build options (used when --image flag is passed).\n */\n image: t.optional(\n t.object({\n /**\n * Default image tag (name without version).\n *\n * Used when --image is provided without a full override:\n * - `--image` → `tag:latest`\n * - `--image=1.3.4` → `tag:1.3.4`\n * - `--image=other/img:v1` → `other/img:v1` (full override)\n *\n * @example \"myproject/myapp\"\n * @example \"ghcr.io/myorg/myapp\"\n */\n tag: t.string(),\n\n /**\n * Additional arguments to pass to `docker build`.\n *\n * @example '--platform linux/amd64 --no-cache'\n */\n args: t.optional(t.string()),\n\n /**\n * Auto-add OCI standard labels (revision, created, version).\n *\n * Adds:\n * - org.opencontainers.image.revision (git commit SHA)\n * - org.opencontainers.image.created (build timestamp)\n * - org.opencontainers.image.version (from image tag)\n */\n oci: t.optional(t.boolean()),\n }),\n ),\n }),\n ),\n\n /**\n * Static site deployment configuration.\n *\n * Note: Set `target: \"static\"` to enable static site generation.\n */\n static: t.optional(\n t.object({\n /**\n * Surge domain for deployment.\n *\n * If set, a CNAME file is written to dist/public/.\n * If not set, a domain is auto-generated from package.json name.\n *\n * @example \"my-app.surge.sh\"\n * @example \"my-custom-domain.com\"\n */\n domain: t.optional(t.string()),\n }),\n ),\n\n /**\n * Sitemap generation configuration.\n */\n sitemap: t.optional(\n t.object({\n /**\n * Base URL for sitemap entries.\n */\n hostname: t.string(),\n }),\n ),\n }),\n default: {},\n});\n\n/**\n * Type for build options.\n */\nexport type BuildOptions = Static<typeof buildOptions.schema>;\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Dev options atom for CLI dev command.\n *\n * Defines the available dev configuration options with their defaults.\n * Options can be overridden via alepha.config.ts or CLI flags.\n */\nexport const devOptions = $atom({\n name: \"alepha.cli.dev.options\",\n description: \"Dev configuration options\",\n schema: t.object({\n /**\n * Disable Vite React plugin.\n */\n noViteReactPlugin: t.optional(t.boolean({ default: false })),\n }),\n default: {},\n});\n\n/**\n * Type for dev options.\n */\nexport type DevOptions = Static<typeof devOptions.schema>;\n","import { $inject, $state, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { appEntryOptions } from \"../atoms/appEntryOptions.ts\";\n\n/**\n * Service for locating entry files in Alepha projects.\n *\n * Resolves application entry points for the CLI build pipeline.\n */\nexport class AppEntryProvider {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly options = $state(appEntryOptions);\n\n protected readonly serverEntries = [\n \"main.server.ts\",\n \"main.server.tsx\",\n \"main.ts\",\n \"main.tsx\",\n ] as const;\n\n protected readonly browserEntries = [\n \"main.browser.ts\",\n \"main.browser.tsx\",\n \"main.ts\",\n \"main.tsx\",\n ] as const;\n\n protected readonly styleEntries = [\n \"main.css\",\n \"styles.css\",\n \"style.css\",\n ] as const;\n\n /**\n * Get application entry points.\n *\n * Server entry is required, an error is thrown if not found.\n * Browser entry is optional.\n *\n * It will first check for custom entries in options, see appEntryOptions.\n */\n public async getAppEntry(root: string): Promise<AppEntry> {\n const appEntry: AppEntry = {\n root,\n server: \"\",\n };\n\n if (this.options.server) {\n const serverPath = this.fs.join(root, this.options.server);\n const serverExists = await this.fs.exists(serverPath);\n if (!serverExists) {\n throw new AlephaError(`Custom server entry not found: ${serverPath}`);\n }\n appEntry.server = this.options.server;\n }\n\n if (this.options.browser) {\n const browserPath = this.fs.join(root, this.options.browser);\n const browserExists = await this.fs.exists(browserPath);\n if (!browserExists) {\n throw new AlephaError(`Custom browser entry not found: ${browserPath}`);\n }\n appEntry.browser = this.options.browser;\n }\n\n if (this.options.style) {\n const stylePath = this.fs.join(root, this.options.style);\n const styleExists = await this.fs.exists(stylePath);\n if (!styleExists) {\n throw new AlephaError(`Custom style entry not found: ${stylePath}`);\n }\n appEntry.style = this.options.style;\n }\n\n const srcFiles = await this.fs.ls(this.fs.join(root, \"src\"));\n\n if (!appEntry.server) {\n // find in conventional locations\n for (const entry of this.serverEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.server = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n if (!appEntry.server) {\n const srcDir = this.fs.join(root, \"src\");\n const tried = this.serverEntries\n .map((e) => this.fs.join(srcDir, e))\n .join(\", \");\n throw new AlephaError(\n `No server entry found. Tried: ${tried}. Add a main.server.ts file or configure a custom entry in alepha.config.ts.`,\n );\n }\n\n if (!appEntry.browser) {\n // find in conventional locations\n for (const entry of this.browserEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.browser = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n if (!appEntry.style) {\n // find in conventional locations\n for (const entry of this.styleEntries) {\n if (srcFiles.includes(entry)) {\n appEntry.style = this.fs.join(\"src\", entry);\n break;\n }\n }\n }\n\n return appEntry;\n }\n}\n\nexport interface AppEntry {\n root: string;\n server: string;\n browser?: string;\n style?: string;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { $hook, $inject, type Alepha, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { InlineConfig, Logger, Plugin, ViteDevServer } from \"vite\";\nimport type { AppEntry } from \"../providers/AppEntryProvider.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------------------------------------------\n\ninterface BufferedLogEntry {\n level: \"info\" | \"warn\" | \"error\";\n msg: string;\n timestamp: Date;\n}\n\nexport interface BufferedLogger extends Logger {\n /**\n * Flush all buffered log messages to console.\n * Call this on build failure to show what happened.\n */\n flush(): void;\n\n /**\n * Get all buffered log entries.\n */\n getEntries(): BufferedLogEntry[];\n\n /**\n * Clear all buffered entries without printing.\n */\n clear(): void;\n}\n\n/**\n * Preload manifest mapping short keys to source paths.\n * Generated at build time, consumed by SSRManifestProvider at runtime.\n */\nexport interface PreloadManifest {\n [key: string]: string;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n// ViteUtils\n// -----------------------------------------------------------------------------------------------------------------\n\n/**\n * Vite integration utilities for the Alepha CLI.\n *\n * Centralizes all Vite-specific code: lazy loading, plugin creation,\n * buffered logger, dev server management.\n * When Vite is replaced, only this file needs to change.\n */\nexport class ViteUtils {\n protected readonly fs = $inject(FileSystemProvider);\n protected viteDevServer?: ViteDevServer;\n\n // ---------------------------------------------------------------------------------------------------------------\n // Vite loaders\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Lazy-load Vite (with rolldown-vite fallback).\n */\n public async importVite(): Promise<typeof import(\"vite\")> {\n try {\n return createRequire(import.meta.url)(\"rolldown-vite\");\n } catch {\n try {\n return createRequire(import.meta.url)(\"vite\");\n } catch {\n throw new AlephaError(\n \"Vite is not installed. Please install it with `npm install vite`.\",\n );\n }\n }\n }\n\n /**\n * Lazy-load @vitejs/plugin-react (optional).\n */\n public async importViteReact(): Promise<any> {\n try {\n const { default: viteReact } = createRequire(import.meta.url)(\n \"@vitejs/plugin-react\",\n );\n return viteReact;\n } catch {\n // @vitejs/plugin-react not installed, skip\n }\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // Buffered logger\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Create a Vite logger that buffers all messages instead of printing them.\n * Useful for silent builds that only show output on failure.\n */\n public createBufferedLogger(): BufferedLogger {\n const entries: BufferedLogEntry[] = [];\n const loggedErrors = new WeakSet<Error>();\n const warnedMessages = new Set<string>();\n let hasWarned = false;\n\n const logger: BufferedLogger = {\n get hasWarned() {\n return hasWarned;\n },\n\n info(msg: string) {\n entries.push({ level: \"info\", msg, timestamp: new Date() });\n },\n\n warn(msg: string) {\n hasWarned = true;\n entries.push({ level: \"warn\", msg, timestamp: new Date() });\n },\n\n warnOnce(msg: string) {\n if (warnedMessages.has(msg)) {\n return;\n }\n warnedMessages.add(msg);\n hasWarned = true;\n entries.push({ level: \"warn\", msg, timestamp: new Date() });\n },\n\n error(msg: string, options?: { error?: Error | null }) {\n if (options?.error) {\n loggedErrors.add(options.error);\n }\n entries.push({ level: \"error\", msg, timestamp: new Date() });\n },\n\n clearScreen() {\n // No-op in buffered mode\n },\n\n hasErrorLogged(error: Error): boolean {\n return loggedErrors.has(error);\n },\n\n flush() {\n for (const entry of entries) {\n const prefix =\n entry.level === \"error\"\n ? \"\\x1b[31m✖\\x1b[0m\"\n : entry.level === \"warn\"\n ? \"\\x1b[33m⚠\\x1b[0m\"\n : \"\\x1b[36mℹ\\x1b[0m\";\n console.log(`${prefix} ${entry.msg}`);\n }\n },\n\n getEntries() {\n return [...entries];\n },\n\n clear() {\n entries.length = 0;\n warnedMessages.clear();\n hasWarned = false;\n },\n };\n\n return logger;\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // TSConfig paths plugin\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Vite plugin that reads tsconfig.json `compilerOptions.paths` and converts\n * them to Vite `resolve.alias` entries. Enables `@/*` → `src/*` style imports\n * with zero config beyond tsconfig.json.\n */\n public createTsconfigPathsPlugin(): Plugin {\n return {\n name: \"alepha-tsconfig-paths\",\n async config(config) {\n const root = config.root || process.cwd();\n const tsconfigPath = join(root, \"tsconfig.json\");\n\n let content: string;\n try {\n content = await readFile(tsconfigPath, \"utf-8\");\n } catch {\n return;\n }\n\n // Strip JSONC comments before parsing\n const clean = content\n .replace(/\\/\\/.*$/gm, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n\n let tsconfig: any;\n try {\n tsconfig = JSON.parse(clean);\n } catch {\n return;\n }\n\n const paths = tsconfig?.compilerOptions?.paths;\n if (!paths || typeof paths !== \"object\") return;\n\n const alias: Record<string, string> = {};\n for (const [pattern, targets] of Object.entries(paths)) {\n if (!Array.isArray(targets) || targets.length === 0) continue;\n const target = targets[0] as string;\n const aliasKey = pattern.replace(/\\*$/, \"\");\n const aliasPath = target.replace(/\\*$/, \"\").replace(/^\\.\\//, \"\");\n const resolved = resolve(root, aliasPath);\n alias[aliasKey] = aliasKey.endsWith(\"/\") ? `${resolved}/` : resolved;\n }\n\n if (Object.keys(alias).length === 0) return;\n return { resolve: { alias } };\n },\n };\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // SSR preload plugin\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * Vite plugin that generates a preload manifest for SSR module preloading.\n *\n * Collects lazy import paths from $page definitions during transform,\n * generates a manifest mapping short keys to resolved source paths,\n * and injects only the short key into $page definitions.\n */\n public createSsrPreloadPlugin(): Plugin {\n let root = \"\";\n const preloadMap = new Map<string, string>();\n\n function generateKey(sourcePath: string): string {\n return createHash(\"md5\").update(sourcePath).digest(\"hex\").slice(0, 8);\n }\n\n return {\n name: \"alepha-preload\",\n configResolved(config) {\n root = config.root;\n },\n transform(code, id) {\n if (!id.match(/\\.[tj]sx?$/)) return null;\n if (id.includes(\"node_modules\")) return null;\n if (!code.includes(\"$page\") || !code.includes(\"lazy\")) return null;\n\n const insertions: Array<{ position: number; text: string }> = [];\n const pageStartRegex = /\\$page\\s*\\(\\s*\\{/g;\n let pageMatch: RegExpExecArray | null = pageStartRegex.exec(code);\n\n while (pageMatch !== null) {\n const objectStartIndex = pageMatch.index + pageMatch[0].length - 1;\n\n let braceCount = 1;\n let i = objectStartIndex + 1;\n while (i < code.length && braceCount > 0) {\n if (code[i] === \"{\") braceCount++;\n else if (code[i] === \"}\") braceCount--;\n i++;\n }\n\n if (braceCount !== 0) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const objectEndIndex = i - 1;\n const pageContent = code.slice(objectStartIndex, objectEndIndex + 1);\n\n if (pageContent.includes(\"alepha.page.preload\")) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const lazyRegex =\n /lazy\\s*:\\s*\\(\\s*\\)\\s*=>\\s*import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/;\n const lazyMatch = lazyRegex.exec(pageContent);\n\n if (!lazyMatch) {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n const importPath = lazyMatch[1];\n const currentDir = dirname(id);\n let resolvedPath: string;\n\n if (importPath.startsWith(\".\")) {\n resolvedPath = resolve(currentDir, importPath);\n } else if (importPath.startsWith(\"/\")) {\n resolvedPath = resolve(root, importPath.slice(1));\n } else {\n pageMatch = pageStartRegex.exec(code);\n continue;\n }\n\n let relativePath = relative(root, resolvedPath);\n relativePath = relativePath.replace(/\\\\/g, \"/\");\n\n if (!relativePath.match(/\\.[tj]sx?$/)) {\n relativePath = `${relativePath}.tsx`;\n } else if (relativePath.endsWith(\".jsx\")) {\n relativePath = relativePath.replace(/\\.jsx$/, \".tsx\");\n } else if (relativePath.endsWith(\".js\")) {\n relativePath = relativePath.replace(/\\.js$/, \".ts\");\n }\n\n const key = generateKey(relativePath);\n preloadMap.set(key, relativePath);\n\n const beforeBrace = code.slice(0, objectEndIndex).trimEnd();\n const needsComma = !beforeBrace.endsWith(\",\");\n const preloadProperty = `${needsComma ? \",\" : \"\"} [Symbol.for(\"alepha.page.preload\")]: \"${key}\"`;\n\n insertions.push({ position: objectEndIndex, text: preloadProperty });\n pageMatch = pageStartRegex.exec(code);\n }\n\n if (insertions.length === 0) return null;\n\n let result = code;\n for (let j = insertions.length - 1; j >= 0; j--) {\n const { position, text } = insertions[j];\n result = result.slice(0, position) + text + result.slice(position);\n }\n\n return { code: result, map: null };\n },\n writeBundle(options) {\n const outDir = options.dir || \"\";\n if (outDir.includes(\"server\")) return;\n\n if (preloadMap.size > 0) {\n const viteDir = join(outDir, \".vite\");\n if (!existsSync(viteDir)) {\n mkdirSync(viteDir, { recursive: true });\n }\n\n const manifest: PreloadManifest = Object.fromEntries(preloadMap);\n const manifestPath = join(viteDir, \"preload-manifest.json\");\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));\n }\n },\n };\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // HTML template\n // ---------------------------------------------------------------------------------------------------------------\n\n public generateIndexHtml(entry: AppEntry): string {\n const style = entry.style;\n const browser = entry.browser ?? entry.server;\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<title>App</title>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n${style ? `<link rel=\"stylesheet\" href=\"/${style}\" />` : \"\"}\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/${browser}\"></script>\n</body>\n</html>\n`.trim();\n }\n\n // ---------------------------------------------------------------------------------------------------------------\n // Dev server management\n // ---------------------------------------------------------------------------------------------------------------\n\n /**\n * We need to close the Vite dev server after build is done.\n */\n protected onReady = $hook({\n on: \"ready\",\n priority: \"last\",\n handler: async () => {\n await this.viteDevServer?.close();\n },\n });\n\n protected onStop = $hook({\n on: \"stop\",\n handler: async () => {\n await this.viteDevServer?.close();\n },\n });\n\n public async runAlepha(opts: {\n entry: AppEntry;\n mode: \"production\" | \"development\";\n }): Promise<Alepha> {\n const { createServer } = await this.importVite();\n\n process.env.NODE_ENV = opts.mode;\n process.env.ALEPHA_CLI_IMPORT = \"true\"; // signal Alepha App about CLI import, run(alepha) won't start server\n process.env.LOG_LEVEL ??= \"warn\"; // reduce log noise\n process.env.APP_SECRET ??= \"123456\"; // avoid warning about missing secret, not used in CLI context\n\n /**\n * 01/26 Vite 7\n * \"runnerImport\" doesn't work as expected here. (e.g. build docs fail)\n * -> We still use devServer and ssrLoadModule for now.\n * -> This is clearly a bad stuff, we need to find better way.\n */\n this.viteDevServer = await createServer({\n server: { middlewareMode: true },\n appType: \"custom\",\n logLevel: \"silent\",\n plugins: [this.createTsconfigPathsPlugin()],\n } satisfies InlineConfig);\n\n await this.viteDevServer.ssrLoadModule(opts.entry.server);\n\n delete process.env.ALEPHA_CLI_IMPORT;\n\n const alepha: Alepha = (globalThis as any).__alepha;\n if (!alepha) {\n throw new AlephaError(\n \"Alepha instance not found after loading entry module\",\n );\n }\n\n return alepha;\n }\n}\n","import { $inject, type Alepha, AlephaError } from \"alepha\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport type { AppEntry } from \"./AppEntryProvider.ts\";\n\nexport class ViteBuildProvider {\n protected alepha?: Alepha;\n protected appEntry?: AppEntry;\n protected readonly viteUtils = $inject(ViteUtils);\n\n public async init(opts: { entry: AppEntry }) {\n const alepha = await this.viteUtils.runAlepha({\n entry: opts.entry,\n mode: \"production\",\n });\n\n this.alepha = alepha;\n this.appEntry = opts.entry;\n\n return alepha;\n }\n\n public hasClient(): boolean {\n if (!this.alepha) {\n throw new AlephaError(\"ViteBuildProvider not initialized\");\n }\n try {\n this.alepha.inject(\"ReactServerProvider\");\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { $inject, Alepha } from \"alepha\";\nimport { EnvUtils } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider, ShellProvider } from \"alepha/system\";\nimport {\n type AppEntry,\n AppEntryProvider,\n} from \"../providers/AppEntryProvider.ts\";\nimport { ViteUtils } from \"./ViteUtils.ts\";\n\n/**\n * Core utility service for CLI commands.\n *\n * Provides:\n * - Command execution\n * - File editing helpers\n * - Drizzle/ORM utilities\n * - Environment loading\n */\nexport class AlephaCliUtils {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly envUtils = $inject(EnvUtils);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly shell = $inject(ShellProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n protected readonly alepha = $inject(Alepha);\n\n // ===========================================\n // Command Execution\n // ===========================================\n\n /**\n * Execute a command with inherited stdio.\n */\n public async exec(\n command: string,\n options: {\n root?: string;\n env?: Record<string, string>;\n global?: boolean;\n capture?: boolean;\n } = {},\n ): Promise<void> {\n await this.shell.run(command, {\n root: options.root,\n env: options.env,\n resolve: !options.global,\n capture: options.capture,\n });\n }\n\n /**\n * Write a configuration file to node_modules/.alepha directory.\n */\n public async writeConfigFile(\n name: string,\n content: string,\n root = process.cwd(),\n ): Promise<string> {\n const dir = this.fs.join(root, \"node_modules\", \".alepha\");\n\n await this.fs.mkdir(dir, { recursive: true }).catch(() => null);\n\n const path = this.fs.join(dir, name);\n await this.fs.writeFile(path, content);\n\n this.log.debug(`Config file written: ${path}`);\n\n return path;\n }\n\n public async loadAlephaFromServerEntryFile(\n opts: {\n mode: \"production\" | \"development\";\n } & ({ entry: AppEntry } | { root: string }),\n ): Promise<Alepha> {\n let entry: AppEntry;\n if (\"root\" in opts) {\n entry = await this.boot.getAppEntry(opts.root);\n } else {\n entry = opts.entry;\n }\n\n return await this.viteUtils.runAlepha({\n entry,\n mode: opts.mode,\n });\n }\n\n // ===========================================\n // Environment\n // ===========================================\n\n /**\n * Load environment variables from a .env file.\n */\n public async loadEnv(\n root: string,\n files: string[] = [\".env\"],\n ): Promise<void> {\n await this.envUtils.loadEnv(root, files);\n }\n\n // ===========================================\n // Helpers\n // ===========================================\n\n public async exists(root: string, path: string): Promise<boolean> {\n return this.fs.exists(this.fs.join(root, path));\n }\n\n /**\n * Check if a command is installed and available in the system PATH.\n */\n public isInstalledAsync(cmd: string): Promise<boolean> {\n return this.shell.isInstalled(cmd);\n }\n\n /**\n * Get the current git revision (commit SHA).\n *\n * @returns The short commit SHA or \"unknown\" if not in a git repo\n */\n public async getGitRevision(): Promise<string> {\n try {\n const result = await this.shell.run(\"git rev-parse --short HEAD\", {\n capture: true,\n });\n return result.trim();\n } catch {\n return \"unknown\";\n }\n }\n\n /**\n * Get the user's email from git config.\n *\n * @returns The git user email or undefined if not configured\n */\n public async getGitEmail(): Promise<string | undefined> {\n try {\n const result = await this.shell.run(\"git config user.email\", {\n capture: true,\n });\n const email = result.trim();\n return email || undefined;\n } catch {\n return undefined;\n }\n }\n}\n","","import { readFileSync } from \"node:fs\";\n\nconst packageJson = JSON.parse(\n readFileSync(new URL(\"../../../package.json\", import.meta.url), \"utf-8\"),\n);\n\nexport const version = packageJson.version;\n","import { basename } from \"node:path\";\nimport { $inject, Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport alephaPackageJson from \"alepha/package.json\" with { type: \"json\" };\nimport { FileSystemProvider } from \"alepha/system\";\nimport { version } from \"../version.ts\";\n\n/**\n * Context information about a workspace root.\n * Used when initializing a package inside a monorepo.\n */\nexport interface WorkspaceContext {\n /**\n * Whether we're inside a workspace package.\n */\n isPackage: boolean;\n /**\n * The workspace root directory (e.g., ../.. from packages/my-pkg).\n */\n workspaceRoot: string | null;\n /**\n * Package manager detected at workspace root.\n */\n packageManager: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\" | null;\n /**\n * Config files present at workspace root.\n */\n config: {\n biomeJson: boolean;\n editorconfig: boolean;\n tsconfigJson: boolean;\n };\n}\n\n/**\n * Utility service for package manager operations.\n *\n * Handles detection, installation, and cleanup for:\n * - Yarn\n * - npm\n * - pnpm\n * - Bun\n */\nexport class PackageManagerUtils {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly alepha = $inject(Alepha);\n\n /**\n * Detect the package manager used in the project.\n * Checks current directory first, then workspace root if in a monorepo.\n */\n public async getPackageManager(\n root: string,\n pm?: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\",\n ): Promise<\"yarn\" | \"pnpm\" | \"npm\" | \"bun\"> {\n if (pm) return pm;\n if (this.alepha.isBun()) return \"bun\";\n\n // Check current directory first\n if (await this.fs.exists(this.fs.join(root, \"bun.lock\"))) return \"bun\";\n if (await this.fs.exists(this.fs.join(root, \"yarn.lock\"))) return \"yarn\";\n if (await this.fs.exists(this.fs.join(root, \"pnpm-lock.yaml\")))\n return \"pnpm\";\n if (await this.fs.exists(this.fs.join(root, \"package-lock.json\")))\n return \"npm\";\n\n // Check workspace root (for monorepo packages like apps/blog)\n const workspace = await this.getWorkspaceContext(root);\n if (workspace.packageManager) {\n return workspace.packageManager;\n }\n\n return \"npm\";\n }\n\n /**\n * Detect workspace context when inside a monorepo package.\n *\n * Checks if we're inside a workspace package by walking up to 3 levels\n * for workspace indicators like lockfiles and config files.\n * This covers both standard layouts (packages/my-pkg) and deeper nesting\n * (packages/scope/my-pkg).\n *\n * @param root - The current package directory\n * @returns Workspace context with root path, PM, and config presence\n */\n public async getWorkspaceContext(root: string): Promise<WorkspaceContext> {\n const noContext: WorkspaceContext = {\n isPackage: false,\n workspaceRoot: null,\n packageManager: null,\n config: { biomeJson: false, editorconfig: false, tsconfigJson: false },\n };\n\n // Walk up 2–3 levels (covers packages/pkg and packages/scope/pkg)\n for (let depth = 2; depth <= 3; depth++) {\n const segments = Array.from({ length: depth }, () => \"..\");\n const candidate = this.fs.join(root, ...segments);\n\n // Don't check above filesystem root\n if (candidate === root) break;\n\n const result = await this.checkWorkspaceRoot(candidate);\n if (result) return result;\n }\n\n return noContext;\n }\n\n protected async checkWorkspaceRoot(\n candidate: string,\n ): Promise<WorkspaceContext | null> {\n const [hasYarnLock, hasPnpmLock, hasNpmLock, hasBunLock] =\n await Promise.all([\n this.fs.exists(this.fs.join(candidate, \"yarn.lock\")),\n this.fs.exists(this.fs.join(candidate, \"pnpm-lock.yaml\")),\n this.fs.exists(this.fs.join(candidate, \"package-lock.json\")),\n this.fs.exists(this.fs.join(candidate, \"bun.lock\")),\n ]);\n\n const hasLockfile = hasYarnLock || hasPnpmLock || hasNpmLock || hasBunLock;\n if (!hasLockfile) return null;\n\n const [hasBiome, hasEditorConfig, hasTsConfig, hasPackageJson] =\n await Promise.all([\n this.fs.exists(this.fs.join(candidate, \"biome.json\")),\n this.fs.exists(this.fs.join(candidate, \".editorconfig\")),\n this.fs.exists(this.fs.join(candidate, \"tsconfig.json\")),\n this.fs.exists(this.fs.join(candidate, \"package.json\")),\n ]);\n\n if (!hasPackageJson) return null;\n\n let packageManager: \"yarn\" | \"pnpm\" | \"npm\" | \"bun\" | null = null;\n if (hasYarnLock) packageManager = \"yarn\";\n else if (hasPnpmLock) packageManager = \"pnpm\";\n else if (hasBunLock) packageManager = \"bun\";\n else if (hasNpmLock) packageManager = \"npm\";\n\n return {\n isPackage: true,\n workspaceRoot: candidate,\n packageManager,\n config: {\n biomeJson: hasBiome,\n editorconfig: hasEditorConfig,\n tsconfigJson: hasTsConfig,\n },\n };\n }\n\n /**\n * Get the install command for a package.\n */\n public async getInstallCommand(\n root: string,\n packageName: string,\n dev = true,\n ): Promise<string> {\n const pm = await this.getPackageManager(root);\n let cmd: string;\n\n switch (pm) {\n case \"yarn\":\n cmd = `yarn add ${dev ? \"-D\" : \"\"} ${packageName}`;\n break;\n case \"pnpm\":\n cmd = `pnpm add ${dev ? \"-D\" : \"\"} ${packageName}`;\n break;\n case \"bun\":\n cmd = `bun add ${dev ? \"-d\" : \"\"} ${packageName}`;\n break;\n default:\n cmd = `npm install ${dev ? \"--save-dev\" : \"\"} ${packageName}`;\n }\n\n return cmd.replace(/\\s+/g, \" \").trim();\n }\n\n /**\n * Check if a dependency is installed in the project.\n */\n public async hasDependency(\n root: string,\n packageName: string,\n ): Promise<boolean> {\n try {\n const pkg = await this.readPackageJson(root);\n return !!(\n pkg.dependencies?.[packageName] || pkg.devDependencies?.[packageName]\n );\n } catch {\n return false;\n }\n }\n\n /**\n * Check if Expo is present in the project.\n */\n public async hasExpo(root: string): Promise<boolean> {\n return this.hasDependency(root, \"expo\");\n }\n\n /**\n * Check if React is present in the project.\n */\n public async hasReact(root: string): Promise<boolean> {\n return this.hasDependency(root, \"react\");\n }\n\n /**\n * Install a dependency if it's missing from the project.\n * Optionally checks workspace root for the dependency in monorepo setups.\n */\n public async ensureDependency(\n root: string,\n packageName: string,\n options: {\n dev?: boolean;\n /**\n * Also check workspace root for the dependency (for monorepo setups).\n */\n checkWorkspace?: boolean;\n run?: RunnerMethod;\n exec?: (\n cmd: string,\n opts?: { global?: boolean; root?: string },\n ) => Promise<void>;\n } = {},\n ): Promise<void> {\n const { dev = true, checkWorkspace = false } = options;\n\n // Check current package\n if (await this.hasDependency(root, packageName)) {\n this.log.debug(`Dependency '${packageName}' is already installed`);\n return;\n }\n\n // Check workspace root (for monorepo setups)\n if (checkWorkspace) {\n const workspace = await this.getWorkspaceContext(root);\n if (workspace.workspaceRoot) {\n if (await this.hasDependency(workspace.workspaceRoot, packageName)) {\n this.log.debug(\n `Dependency '${packageName}' is already installed in workspace root`,\n );\n return;\n }\n }\n }\n\n const cmd = await this.getInstallCommand(root, packageName, dev);\n\n if (options.run) {\n await options.run(cmd, { alias: `add ${packageName}`, root });\n } else if (options.exec) {\n this.log.debug(`Installing ${packageName}`);\n await options.exec(cmd, { global: true, root });\n }\n }\n\n // ===========================================\n // Package Manager Setup & Cleanup\n // ===========================================\n\n public async ensureYarn(root: string): Promise<void> {\n const yarnrcPath = this.fs.join(root, \".yarnrc.yml\");\n if (!(await this.fs.exists(yarnrcPath))) {\n await this.fs.writeFile(yarnrcPath, \"nodeLinker: node-modules\");\n }\n await this.removeAllPmFilesExcept(root, \"yarn\");\n }\n\n public async ensureBun(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"bun\");\n }\n\n public async ensurePnpm(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"pnpm\");\n }\n\n public async ensureNpm(root: string): Promise<void> {\n await this.removeAllPmFilesExcept(root, \"npm\");\n }\n\n public async removeAllPmFilesExcept(\n root: string,\n except: string,\n ): Promise<void> {\n if (except !== \"yarn\") await this.removeYarn(root);\n if (except !== \"pnpm\") await this.removePnpm(root);\n if (except !== \"npm\") await this.removeNpm(root);\n if (except !== \"bun\") await this.removeBun(root);\n }\n\n public async removeYarn(root: string): Promise<void> {\n await this.removeFiles(root, [\".yarn\", \".yarnrc.yml\", \"yarn.lock\"]);\n await this.editPackageJson(root, (pkg) => {\n delete pkg.packageManager;\n return pkg;\n });\n }\n\n public async removePnpm(root: string): Promise<void> {\n await this.removeFiles(root, [\"pnpm-lock.yaml\", \"pnpm-workspace.yaml\"]);\n await this.editPackageJson(root, (pkg) => {\n delete pkg.packageManager;\n return pkg;\n });\n }\n\n public async removeNpm(root: string): Promise<void> {\n await this.removeFiles(root, [\"package-lock.json\"]);\n }\n\n public async removeBun(root: string): Promise<void> {\n await this.removeFiles(root, [\"bun.lockb\", \"bun.lock\"]);\n }\n\n // ===========================================\n // Package.json utilities\n // ===========================================\n\n public async readPackageJson(root: string): Promise<Record<string, any>> {\n const content = await this.fs\n .createFile({ path: this.fs.join(root, \"package.json\") })\n .text();\n return JSON.parse(content);\n }\n\n public async writePackageJson(\n root: string,\n content: Record<string, any>,\n ): Promise<void> {\n await this.fs.writeFile(\n this.fs.join(root, \"package.json\"),\n JSON.stringify(content, null, 2),\n );\n }\n\n public async editPackageJson(\n root: string,\n editFn: (pkg: Record<string, any>) => Record<string, any>,\n ): Promise<void> {\n try {\n const pkg = await this.readPackageJson(root);\n const updated = editFn(pkg);\n await this.writePackageJson(root, updated);\n } catch {\n // package.json doesn't exist, skip\n }\n }\n\n public async ensurePackageJson(\n root: string,\n modes: DependencyModes,\n ): Promise<Record<string, any>> {\n const packageJsonPath = this.fs.join(root, \"package.json\");\n\n if (!(await this.fs.exists(packageJsonPath))) {\n const dirName = basename(root) || \"app\";\n const content = {\n name: dirName,\n private: true,\n ...this.generatePackageJsonContent(modes),\n };\n await this.writePackageJson(root, content);\n return content;\n }\n\n const packageJson = await this.readPackageJson(root);\n const newContent = this.generatePackageJsonContent(modes);\n\n packageJson.type = \"module\";\n packageJson.dependencies ??= {};\n packageJson.devDependencies ??= {};\n packageJson.scripts ??= {};\n\n Object.assign(packageJson.dependencies, newContent.dependencies);\n Object.assign(packageJson.devDependencies, newContent.devDependencies);\n Object.assign(packageJson.scripts, newContent.scripts);\n\n await this.writePackageJson(root, packageJson);\n return packageJson;\n }\n\n public generatePackageJsonContent(modes: DependencyModes): {\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n scripts: Record<string, string>;\n type: \"module\";\n } {\n const alephaDeps = alephaPackageJson.devDependencies;\n\n const dependencies: Record<string, string> = {\n alepha: `^${version}`,\n };\n\n const devDependencies: Record<string, string> = {\n vite: alephaDeps.vite,\n };\n\n // Only include drizzle-kit when the project uses a database.\n // React-only projects (--react without --api/--saas) don't need it.\n const isReactOnly = modes.react && !modes.ui;\n if (!isReactOnly) {\n devDependencies[\"drizzle-kit\"] = alephaDeps[\"drizzle-kit\"];\n }\n\n // Add biome/vitest only if not a workspace package (workspace root has them)\n if (!modes.isPackage) {\n devDependencies[\"@biomejs/biome\"] = alephaDeps[\"@biomejs/biome\"];\n if (modes.test) {\n devDependencies.vitest = alephaDeps.vitest;\n }\n }\n\n const scripts: Record<string, string> = {\n dev: \"alepha dev\",\n build: \"alepha build\",\n lint: \"alepha lint\",\n typecheck: \"alepha typecheck\",\n verify: \"alepha verify\",\n };\n\n if (modes.test) {\n scripts.test = \"vitest run\";\n }\n\n if (modes.ui) {\n dependencies[\"@alepha/ui\"] = `^${version}`;\n modes.react = true;\n }\n\n if (modes.tailwind) {\n devDependencies.tailwindcss = \"^4.2.0\";\n devDependencies[\"@tailwindcss/vite\"] = \"^4.2.0\";\n }\n\n if (modes.react) {\n dependencies.react = alephaDeps.react;\n dependencies[\"react-dom\"] = alephaDeps[\"react-dom\"];\n devDependencies[\"@types/react\"] = alephaDeps[\"@types/react\"];\n }\n\n return {\n type: \"module\",\n dependencies,\n devDependencies,\n scripts,\n };\n }\n\n // ===========================================\n // Helper methods\n // ===========================================\n\n protected async removeFiles(root: string, files: string[]): Promise<void> {\n await Promise.all(\n files.map((file) =>\n this.fs.rm(this.fs.join(root, file), { force: true, recursive: true }),\n ),\n );\n }\n}\n\nexport interface DependencyModes {\n react?: boolean;\n ui?: boolean;\n expo?: boolean;\n tailwind?: boolean;\n test?: boolean;\n /**\n * Skip biome/vitest when inside a workspace package (they're at root).\n */\n isPackage?: boolean;\n}\n","import { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst packageRoot = join(fileURLToPath(import.meta.url), \"../../../..\");\n\nexport const cliAssets = {\n logo: join(packageRoot, \"assets/logo.svg\"),\n};\n","export type AgentMdType = \"claude\" | \"agents\";\n\nexport interface AgentMdOptions {\n type: AgentMdType;\n ui?: boolean;\n}\n\nexport const agentMd = (options: AgentMdOptions): string => {\n const header = options.type === \"claude\" ? `# CLAUDE.md` : `# AGENTS.md`;\n\n const docs = [`- Framework source: \\`node_modules/alepha/src/\\``];\n if (options.ui) {\n docs.push(`- UI components: \\`node_modules/@alepha/ui/src/\\``);\n }\n docs.push(`- Docs: https://alepha.dev/llms.txt`);\n\n return `${header}\n\nThis is an **Alepha** project.\n\n## Rules\n\n- Always check \\`node_modules/alepha/src/\\` before suggesting npm packages\n- Use \\`t\\` from Alepha for schemas (not Zod)\n- Use \\`protected\\` instead of \\`private\\` for class members\n- Import with file extensions: \\`import { User } from \"./User.ts\"\\`\n\n## Commands\n\n\\`\\`\\`bash\nalepha lint # Format and lint\nalepha typecheck # Type checking\nalepha test # Run tests\nalepha build # Build\n\\`\\`\\`\n\n## Documentation\n\n${docs.join(\"\\n\")}\n`.trim();\n};\n","/**\n * Template for alepha.config.ts with documented options.\n */\nexport const alephaConfigTs = () => {\n return `import { defineConfig } from \"alepha/cli/config\";\n\nexport default defineConfig({\n //\n // entry: {\n // server: \"src/main.server.ts\",\n // browser: \"src/main.browser.ts\",\n // style: \"src/main.css\",\n // },\n //\n // build: {\n // target: \"docker\",\n // runtime: \"node\",\n // },\n //\n // env: {\n // VITE_BUILD_DATE: new Date().toISOString(),\n // VITE_VERSION: pkg.version,\n // },\n});\n`;\n};\n","export const apiAppSecurityTs = (opts: { adminEmail?: string } = {}) => {\n const adminEmailsValue = opts.adminEmail ? `[\"${opts.adminEmail}\"]` : \"[]\";\n\n return `\nimport { $realm } from \"alepha/api/users\";\n\nexport class AppSecurity {\n users = $realm({\n settings: {\n // Auto-promote these users to admin on login\n adminEmails: ${adminEmailsValue},\n adminUsernames: [],\n\n // Registration & login options\n registrationAllowed: true,\n email: \"required\",\n username: \"none\",\n phoneNumber: \"none\",\n\n // Verification (requires notifications feature)\n verifyEmailRequired: false,\n verifyPhoneRequired: false,\n resetPasswordAllowed: false,\n },\n features: {\n // Enable additional features\n notifications: false,\n audits: false,\n apiKeys: false,\n sessionPurge: false,\n avatars: false,\n parameters: false,\n },\n identities: {\n // Enable authentication providers\n credentials: true,\n // google: true,\n // github: true,\n },\n });\n}\n`.trim();\n};\n","export interface ApiHelloControllerOptions {\n appName?: string;\n}\n\nexport const apiHelloControllerTs = (\n options: ApiHelloControllerOptions = {},\n) => {\n const appName = options.appName || \"my-app\";\n const appNameCapitalized = appName\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n\n return `import { $action } from \"alepha/server\";\nimport { helloResponseSchema } from \"../schemas/helloResponseSchema.ts\";\n\nexport class HelloController {\n\n hello = $action({\n path: \"/hello\",\n schema: {\n response: helloResponseSchema,\n },\n handler: () => ({\n appName: \"${appNameCapitalized}\",\n serverTime: new Date().toISOString(),\n }),\n });\n}\n`.trim();\n};\n","export const apiHelloResponseSchemaTs = () => {\n return `import { type Static, t } from \"alepha\";\n\nexport const helloResponseSchema = t.object({\n appName: t.text(),\n serverTime: t.datetime(),\n});\n\nexport type HelloResponse = Static<typeof helloResponseSchema>;\n`.trim();\n};\n","export interface ApiIndexTsOptions {\n appName?: string;\n auth?: boolean;\n}\n\nexport const apiIndexTs = (options: ApiIndexTsOptions = {}) => {\n const { appName = \"app\", auth = false } = options;\n\n const imports: string[] = ['import { $module } from \"alepha\";'];\n const services: string[] = [];\n\n if (auth) {\n imports.push('import { AppSecurity } from \"./AppSecurity.ts\";');\n services.push(\"AppSecurity\");\n }\n\n imports.push(\n 'import { HelloController } from \"./controllers/HelloController.ts\";',\n );\n services.push(\"HelloController\");\n\n return `\n${imports.join(\"\\n\")}\n\nexport const ApiModule = $module({\n name: \"${appName}.api\",\n services: [${services.join(\", \")}],\n});\n`.trim();\n};\n","export const biomeJson = () =>\n `\n{\n \"$schema\": \"https://biomejs.dev/schemas/latest/schema.json\",\n \"vcs\": {\n \"enabled\": true,\n \"clientKind\": \"git\"\n },\n \"files\": {\n \"ignoreUnknown\": true,\n \"includes\": [\"**\", \"!node_modules\", \"!dist\"]\n },\n \"formatter\": {\n \"enabled\": true,\n \"useEditorconfig\": true\n },\n \"linter\": {\n \"enabled\": true,\n \"rules\": {\n \"recommended\": true\n },\n \"domains\": {\n \"react\": \"recommended\"\n }\n },\n \"assist\": {\n \"actions\": {\n \"source\": {\n \"organizeImports\": \"on\"\n }\n }\n }\n}\n`.trim();\n","export const dummySpecTs = () =>\n `\nimport { test, expect } from \"vitest\";\n\ntest(\"dummy test\", () => {\n expect(1 + 1).toBe(2);\n});\n`.trim();\n","export const editorconfig = () =>\n `\n# https://editorconfig.org\n\nroot = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nindent_style = space\nindent_size = 2\n`.trim();\n","export const gitignore = () =>\n `\n# Dependencies\nnode_modules/\n\n# Build outputs\ndist/\n.vite/\n\n# Environment files\n.env\n.env.*\n!.env.example\n\n# IDE\n.idea/\n*.swp\n*.swo\n\n# OS\n.DS_Store\nThumbs.db\n\n# Logs\n*.log\nlogs/\n\n# Test coverage\ncoverage/\n\n# Yarn\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n`.trim();\n","export const mainBrowserTs = () =>\n `\nimport { Alepha, run } from \"alepha\";\nimport { WebModule } from \"./web/index.ts\";\n\nconst alepha = Alepha.create();\n\nalepha.with(WebModule);\n\nrun(alepha);\n`.trim();\n","export const mainCss = (opts: { ui?: boolean; tailwind?: boolean } = {}) => {\n if (opts.ui) {\n return `/**\n * Alepha UI - Based on Mantine component library\n * Mantine Docs: https://mantine.dev\n * Mantine LLM context: https://mantine.dev/llms.txt\n *\n * Switch theme index: alepha.set(alephaThemeAtom, { index: 1 })\n *\n * Custom themes (in src/web/index.ts):\n *\n * import { alephaThemeListAtom } from \"@alepha/ui\";\n *\n * export const WebModule = $module({\n * name: \"app.web\",\n * services: [AppRouter],\n * register(alepha) {\n * alepha.register(AppRouter);\n * alepha.set(alephaThemeListAtom, [{\n * name: \"My Theme\",\n * description: \"Custom theme\",\n * primaryColor: \"blue\",\n * defaultColorScheme: \"dark\",\n * // ...MantineThemeOverride options\n * }]);\n * },\n * });\n *\n * Alternatives (remove the import below):\n * - Tailwind CSS: https://tailwindcss.com/docs/installation/using-vite\n * - Raw CSS: Write your own styles\n */\n@import \"@alepha/ui/styles\";`;\n }\n\n if (opts.tailwind) {\n return `@import \"tailwindcss\";\n\n/* Add your styles here */\n`;\n }\n\n return `/**\n * Global styles for your application.\n *\n * Options:\n * - @alepha/ui: Use \\`alepha init --ui\\` to add Mantine-based components\n * - Tailwind CSS: Use \\`alepha init --tailwind\\` to add Tailwind CSS\n * - Raw CSS: Write your own styles below\n */\n\n/* Add your styles here */\n`;\n};\n","export interface MainServerTsOptions {\n api?: boolean;\n react?: boolean;\n}\n\nexport const mainServerTs = (options: MainServerTsOptions = {}) => {\n const { api = false, react = false } = options;\n\n const imports: string[] = [];\n const withs: string[] = [];\n\n if (api) {\n imports.push(`import { ApiModule } from \"./api/index.ts\";`);\n withs.push(`alepha.with(ApiModule);`);\n }\n\n if (react) {\n imports.push(`import { WebModule } from \"./web/index.ts\";`);\n withs.push(`alepha.with(WebModule);`);\n }\n\n const importsBlock = imports.length > 0 ? `${imports.join(\"\\n\")}\\n` : \"\";\n const withsBlock = withs.length > 0 ? `\\n${withs.join(\"\\n\")}` : \"\";\n\n return `\nimport { Alepha, run } from \"alepha\";\n${importsBlock}\nconst alepha = Alepha.create();\n${withsBlock}\n\nrun(alepha);\n`.trim();\n};\n","export const tsconfigJson = () =>\n `\n{\n \"extends\": \"alepha/tsconfig.base\",\n \"compilerOptions\": {\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n }\n}\n`.trim();\n","export const viteConfigTs = () => {\n return `import tailwindcss from \"@tailwindcss/vite\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n plugins: [tailwindcss()],\n});\n`;\n};\n","export const webAdminDashboardTsx = () => {\n return `import { Flex, Text } from \"@alepha/ui\";\n\nconst AdminDashboard = () => {\n return (\n <Flex direction=\"column\" align=\"center\" justify=\"center\" mih=\"60vh\" gap=\"md\">\n <Text size=\"xl\" fw={600}>\n Admin Panel\n </Text>\n <Text c=\"dimmed\">Welcome to the admin panel.</Text>\n </Flex>\n );\n};\n\nexport default AdminDashboard;\n`;\n};\n","export const webAppRouterTs = (options: {\n api?: boolean;\n ui?: boolean;\n auth?: boolean;\n admin?: boolean;\n}) => {\n const imports: string[] = [];\n const classMembers: string[] = [];\n\n // UI import and setup\n if (options.ui) {\n imports.push('import { $ui } from \"@alepha/ui\";');\n }\n\n // Auth import\n if (options.auth) {\n imports.push('import { $uiAuth } from \"@alepha/ui/auth\";');\n }\n\n // Admin imports\n if (options.admin) {\n imports.push('import { $uiAdmin } from \"@alepha/ui/admin\";');\n imports.push('import { AdminUserRouter } from \"@alepha/ui/admin-users\";');\n imports.push(\n 'import { AdminSessionRouter } from \"@alepha/ui/admin-sessions\";',\n );\n imports.push('import { $inject } from \"alepha\";');\n imports.push('import { IconLayoutDashboard } from \"@tabler/icons-react\";');\n }\n\n // Page import\n imports.push('import { $page } from \"alepha/react/router\";');\n\n // API imports (only if api flag is set)\n if (options.api) {\n imports.push('import { $client } from \"alepha/server/links\";');\n imports.push(\n 'import type { HelloController } from \"../api/controllers/HelloController.ts\";',\n );\n classMembers.push(\" api = $client<HelloController>();\");\n }\n\n // UI layout setup\n if (options.ui) {\n classMembers.push(\" ui = $ui();\");\n\n if (options.auth) {\n classMembers.push(\" uiAuth = $uiAuth();\");\n }\n\n if (options.admin) {\n classMembers.push(` // ── Admin Domain Routers ──────────────────────────\n protected users = $inject(AdminUserRouter);\n protected sessions = $inject(AdminSessionRouter);\n\n // ── Admin Panel ─────────────────────────────────\n admin = $uiAdmin({\n pages: [\n this.users.adminUsers,\n this.users.adminUserLayout,\n this.sessions.adminSessions,\n ],\n sidebarItems: [\n this.users.adminUsers,\n this.sessions.adminSessions,\n ],\n });\n\n // ── Admin Dashboard ─────────────────────────────\n adminDashboard = $page({\n parent: this.admin,\n path: \"/\",\n label: \"Dashboard\",\n icon: IconLayoutDashboard,\n lazy: () => import(\"./components/AdminDashboard.tsx\"),\n });`);\n }\n\n classMembers.push(` layout = $page({\n parent: this.ui.root,\n children: () => [this.home],\n });`);\n }\n\n // Home page - with or without loader\n if (options.api) {\n classMembers.push(` home = $page({\n path: \"/\",\n lazy: () => import(\"./components/Home.tsx\"),\n loader: () => this.api.hello(),\n });`);\n } else {\n classMembers.push(` home = $page({\n path: \"/\",\n lazy: () => import(\"./components/Home.tsx\"),\n });`);\n }\n\n return `${imports.join(\"\\n\")}\n\nexport class AppRouter {\n${classMembers.join(\"\\n\\n\")}\n}`;\n};\n","export interface WebHomeComponentOptions {\n api?: boolean;\n}\n\nexport const webHomeComponentTsx = (options: WebHomeComponentOptions = {}) => {\n if (options.api) {\n return `import { GettingStarted } from \"alepha/react/intro\";\n\ntype Props = {\n appName: string;\n serverTime: string;\n}\n\nconst Home = (props: Props) => {\n return <GettingStarted welcome={props} />;\n};\n\nexport default Home;\n`;\n }\n\n return `import { GettingStarted } from \"alepha/react/intro\";\n\nconst Home = () => {\n return <GettingStarted />;\n};\n\nexport default Home;\n`;\n};\n","export interface WebIndexTsOptions {\n appName?: string;\n}\n\nexport const webIndexTs = (options: WebIndexTsOptions = {}) => {\n const { appName = \"app\" } = options;\n return `\nimport { $module } from \"alepha\";\nimport { AppRouter } from \"./AppRouter.ts\";\n\nexport const WebModule = $module({\n name: \"${appName}.web\",\n services: [AppRouter],\n});\n`.trim();\n};\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport { $inject, AlephaError } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { cliAssets } from \"../assets.ts\";\nimport { type AgentMdOptions, agentMd } from \"../templates/agentMd.ts\";\nimport { alephaConfigTs } from \"../templates/alephaConfigTs.ts\";\nimport { apiAppSecurityTs } from \"../templates/apiAppSecurityTs.ts\";\nimport { apiHelloControllerTs } from \"../templates/apiHelloControllerTs.ts\";\nimport { apiHelloResponseSchemaTs } from \"../templates/apiHelloResponseSchemaTs.ts\";\nimport { apiIndexTs } from \"../templates/apiIndexTs.ts\";\nimport { biomeJson } from \"../templates/biomeJson.ts\";\nimport { dummySpecTs } from \"../templates/dummySpecTs.ts\";\nimport { editorconfig } from \"../templates/editorconfig.ts\";\nimport { gitignore } from \"../templates/gitignore.ts\";\nimport { mainBrowserTs } from \"../templates/mainBrowserTs.ts\";\nimport { mainCss } from \"../templates/mainCss.ts\";\nimport { mainServerTs } from \"../templates/mainServerTs.ts\";\nimport { tsconfigJson } from \"../templates/tsconfigJson.ts\";\nimport { viteConfigTs } from \"../templates/viteConfigTs.ts\";\nimport { webAdminDashboardTsx } from \"../templates/webAdminDashboardTsx.ts\";\nimport { webAppRouterTs } from \"../templates/webAppRouterTs.ts\";\nimport { webHomeComponentTsx } from \"../templates/webHomeComponentTsx.ts\";\nimport { webIndexTs } from \"../templates/webIndexTs.ts\";\nimport { AlephaCliUtils } from \"./AlephaCliUtils.ts\";\nimport {\n type DependencyModes,\n PackageManagerUtils,\n} from \"./PackageManagerUtils.ts\";\n\n/**\n * Service for scaffolding new Alepha projects.\n *\n * Handles creation of:\n * - Project structure (src/api, src/web)\n * - Configuration files (tsconfig, biome, editorconfig)\n * - Entry points (main.server.ts, main.browser.ts)\n * - Example code (HelloController, Home component)\n */\nexport class ProjectScaffolder {\n protected readonly log = $logger();\n protected readonly colors = $inject(ConsoleColorProvider);\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly utils = $inject(AlephaCliUtils);\n\n /**\n * Get the app name from the directory name.\n *\n * Converts the directory name to a valid module name:\n * - Converts to lowercase\n * - Replaces spaces, dashes, underscores with nothing\n * - Falls back to \"app\" if empty\n */\n public getAppName(root: string): string {\n const dirName = basename(root);\n const appName = dirName.toLowerCase().replace(/[\\s\\-_.\\d]/g, \"\");\n return appName || \"app\";\n }\n\n /**\n * Ensure all configuration files exist.\n */\n public async ensureConfig(\n root: string,\n opts: {\n force?: boolean;\n /**\n * Check workspace root for existing config files.\n */\n checkWorkspace?: boolean;\n packageJson?: boolean | DependencyModes;\n tsconfigJson?: boolean;\n biomeJson?: boolean;\n editorconfig?: boolean;\n agentMd?: false | AgentMdOptions;\n },\n ): Promise<void> {\n const tasks: Promise<void>[] = [];\n const force = opts.force ?? false;\n const checkWorkspace = opts.checkWorkspace ?? false;\n\n if (opts.packageJson) {\n tasks.push(\n this.pm\n .ensurePackageJson(\n root,\n typeof opts.packageJson === \"boolean\" ? {} : opts.packageJson,\n )\n .then(() => {}),\n );\n }\n if (opts.tsconfigJson) {\n tasks.push(this.ensureTsConfig(root, { force }));\n }\n if (opts.biomeJson) {\n tasks.push(this.ensureBiomeConfig(root, { force, checkWorkspace }));\n }\n if (opts.editorconfig) {\n tasks.push(this.ensureEditorConfig(root, { force, checkWorkspace }));\n }\n if (opts.agentMd) {\n tasks.push(this.ensureAgentMd(root, { ...opts.agentMd, force }));\n }\n\n await Promise.all(tasks);\n }\n\n // ===========================================\n // Config Files\n // ===========================================\n\n public async ensureTsConfig(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<void> {\n // Check if tsconfig.json exists in current or parent directories\n if (!opts.force && (await this.existsInParents(root, \"tsconfig.json\"))) {\n return;\n }\n await this.fs.writeFile(\n this.fs.join(root, \"tsconfig.json\"),\n tsconfigJson(),\n );\n }\n\n public async ensureBiomeConfig(\n root: string,\n opts: { force?: boolean; checkWorkspace?: boolean } = {},\n ): Promise<void> {\n if (\n !opts.force &&\n opts.checkWorkspace &&\n (await this.existsInParents(root, \"biome.json\"))\n ) {\n return;\n }\n await this.ensureFile(root, \"biome.json\", biomeJson(), opts.force);\n }\n\n public async ensureEditorConfig(\n root: string,\n opts: { force?: boolean; checkWorkspace?: boolean } = {},\n ): Promise<void> {\n if (\n !opts.force &&\n opts.checkWorkspace &&\n (await this.existsInParents(root, \".editorconfig\"))\n ) {\n return;\n }\n await this.ensureFile(root, \".editorconfig\", editorconfig(), opts.force);\n }\n\n /**\n * Ensure git repository is initialized with .gitignore.\n *\n * @returns true if git was initialized, false if already exists or git unavailable\n */\n public async ensureGitRepo(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<boolean> {\n const gitDir = this.fs.join(root, \".git\");\n\n // Skip if .git already exists\n if (!opts.force && (await this.fs.exists(gitDir))) {\n return false;\n }\n\n // Check if git is available\n const hasGit = await this.utils.isInstalledAsync(\"git\");\n if (!hasGit) {\n return false;\n }\n\n // Initialize git repository\n await this.utils.exec(\"git init\", { root, global: true });\n\n // Write .gitignore\n await this.ensureFile(root, \".gitignore\", gitignore(), opts.force);\n\n return true;\n }\n\n public async ensureAgentMd(\n root: string,\n options: AgentMdOptions & { force?: boolean },\n ): Promise<void> {\n const filename = options.type === \"claude\" ? \"CLAUDE.md\" : \"AGENTS.md\";\n await this.ensureFile(root, filename, agentMd(options), options.force);\n }\n\n /**\n * Ensure alepha.config.ts exists with documented options.\n */\n public async ensureAlephaConfig(\n root: string,\n opts: { force?: boolean } = {},\n ): Promise<void> {\n await this.ensureFile(\n root,\n \"alepha.config.ts\",\n alephaConfigTs(),\n opts.force,\n );\n }\n\n // ===========================================\n // Minimal Project Structure\n // ===========================================\n\n /**\n * Ensure src/main.server.ts exists with correct module imports.\n */\n public async ensureMainServerTs(\n root: string,\n opts: { api?: boolean; react?: boolean; force?: boolean } = {},\n ): Promise<void> {\n const srcDir = this.fs.join(root, \"src\");\n await this.fs.mkdir(srcDir, { recursive: true });\n await this.ensureFile(\n srcDir,\n \"main.server.ts\",\n mainServerTs({ api: opts.api, react: opts.react }),\n opts.force,\n );\n }\n\n // ===========================================\n // API Project Structure\n // ===========================================\n\n /**\n * Ensure API module structure exists.\n *\n * Creates:\n * - src/api/index.ts (API module)\n * - src/api/controllers/HelloController.ts (example controller)\n */\n public async ensureApiProject(\n root: string,\n opts: { auth?: boolean; adminEmail?: string; force?: boolean } = {},\n ): Promise<void> {\n const appName = this.getAppName(root);\n\n // Create directories\n await this.fs.mkdir(this.fs.join(root, \"src/api/controllers\"), {\n recursive: true,\n });\n await this.fs.mkdir(this.fs.join(root, \"src/api/schemas\"), {\n recursive: true,\n });\n\n // Create files\n await this.ensureFile(\n root,\n \"src/api/index.ts\",\n apiIndexTs({ appName, auth: opts.auth }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/api/controllers/HelloController.ts\",\n apiHelloControllerTs({ appName }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/api/schemas/helloResponseSchema.ts\",\n apiHelloResponseSchemaTs(),\n opts.force,\n );\n\n // Create AppSecurity if auth is enabled\n if (opts.auth) {\n await this.ensureFile(\n root,\n \"src/api/AppSecurity.ts\",\n apiAppSecurityTs({ adminEmail: opts.adminEmail }),\n opts.force,\n );\n }\n }\n\n // ===========================================\n // Web Project Structure\n // ===========================================\n\n /**\n * Ensure web/React project structure exists.\n *\n * Creates:\n * - src/main.browser.ts\n * - src/main.css\n * - src/web/index.ts, src/web/AppRouter.ts, src/web/components/Home.tsx\n */\n public async ensureWebProject(\n root: string,\n opts: {\n api?: boolean;\n ui?: boolean;\n auth?: boolean;\n admin?: boolean;\n tailwind?: boolean;\n force?: boolean;\n } = {},\n ): Promise<void> {\n const appName = this.getAppName(root);\n\n // Create directories\n await this.fs.mkdir(this.fs.join(root, \"src/web/components\"), {\n recursive: true,\n });\n\n // public/favicon.svg\n await this.fs.mkdir(this.fs.join(root, \"public\"), { recursive: true });\n const logoSvg = (await readFile(cliAssets.logo)).toString();\n await this.ensureFile(root, \"public/favicon.svg\", logoSvg, opts.force);\n\n // src/main.css\n await this.ensureFile(\n root,\n \"src/main.css\",\n mainCss({ ui: opts.ui, tailwind: opts.tailwind }),\n opts.force,\n );\n\n // vite.config.ts (Tailwind CSS plugin)\n if (opts.tailwind) {\n await this.ensureFile(root, \"vite.config.ts\", viteConfigTs(), opts.force);\n }\n\n // Web structure\n await this.ensureFile(\n root,\n \"src/web/index.ts\",\n webIndexTs({ appName }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/AppRouter.ts\",\n webAppRouterTs({\n api: opts.api,\n ui: opts.ui,\n auth: opts.auth,\n admin: opts.admin,\n }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/Home.tsx\",\n webHomeComponentTsx({ api: opts.api }),\n opts.force,\n );\n if (opts.admin) {\n await this.ensureFile(\n root,\n \"src/web/components/AdminDashboard.tsx\",\n webAdminDashboardTsx(),\n opts.force,\n );\n }\n await this.ensureFile(\n root,\n \"src/main.browser.ts\",\n mainBrowserTs(),\n opts.force,\n );\n }\n\n // ===========================================\n // Test Directory\n // ===========================================\n\n /**\n * Ensure test directory exists with a dummy test file.\n */\n public async ensureTestDir(root: string): Promise<void> {\n const testDir = this.fs.join(root, \"test\");\n const dummyPath = this.fs.join(testDir, \"dummy.spec.ts\");\n\n if (!(await this.fs.exists(testDir))) {\n await this.fs.mkdir(testDir, { recursive: true });\n await this.fs.writeFile(dummyPath, dummySpecTs());\n return;\n }\n\n const files = await this.fs.ls(testDir);\n if (files.length === 0) {\n await this.fs.writeFile(dummyPath, dummySpecTs());\n }\n }\n\n // ===========================================\n // Full Init Orchestration\n // ===========================================\n\n /**\n * Full project init — scaffolds files, installs deps, sets up PM and git.\n */\n async init({\n run,\n root,\n flags,\n args,\n }: {\n run: RunnerMethod;\n root: string;\n flags: {\n pm?: \"yarn\" | \"npm\" | \"pnpm\" | \"bun\";\n api?: boolean;\n react?: boolean;\n ui?: boolean;\n saas?: boolean;\n tailwind?: boolean;\n test?: boolean;\n force?: boolean;\n };\n args?: string;\n }) {\n if (args) {\n root = this.fs.join(root, args);\n await this.fs.mkdir(root, { force: true });\n }\n\n // Flag cascading: --saas → --api + --ui → --react\n if (flags.saas) {\n flags.api = true;\n flags.ui = true;\n }\n if (flags.ui) {\n flags.react = true;\n }\n if (flags.tailwind) {\n flags.react = true;\n }\n\n // When codegen flags are set, target directory must be empty (unless --force)\n const hasCodegenFlags =\n flags.saas || flags.api || flags.ui || flags.react || flags.tailwind;\n if (hasCodegenFlags && !flags.force) {\n const files = await this.fs.ls(root);\n // Allow a directory that only has package.json (common for monorepo packages)\n const meaningful = files.filter((f) => f !== \"package.json\");\n if (meaningful.length > 0) {\n throw new AlephaError(\n `Target directory is not empty (${root}). Use --force to overwrite existing files.`,\n );\n }\n }\n\n // Detect workspace context (are we inside packages/ or apps/ of a monorepo?)\n const workspace = await this.pm.getWorkspaceContext(root);\n\n // Detect agent type: claude CLI → CLAUDE.md, else → AGENTS.md\n let agentType: \"claude\" | \"agents\" | false = false;\n if (!workspace.isPackage) {\n const hasClaudeCli = await this.utils.isInstalledAsync(\"claude\");\n agentType = hasClaudeCli ? \"claude\" : \"agents\";\n }\n\n const isExpo = await this.pm.hasExpo(root);\n\n // Get git email for admin auto-promotion (if saas enabled)\n const adminEmail = flags.saas ? await this.utils.getGitEmail() : undefined;\n\n const force = !!flags.force;\n\n await run({\n name: \"ensuring configuration files\",\n handler: async () => {\n await this.ensureConfig(root, {\n force,\n packageJson: { ...flags, isPackage: workspace.isPackage },\n // Skip workspace-level configs if they exist at workspace root\n tsconfigJson: !workspace.config.tsconfigJson,\n biomeJson: true,\n editorconfig: !workspace.config.editorconfig,\n agentMd: agentType ? { type: agentType, ui: !!flags.ui } : false,\n });\n\n // Create alepha.config.ts with documented options\n await this.ensureAlephaConfig(root, { force });\n\n // Create project structure based on flags\n await this.ensureMainServerTs(root, {\n api: !!flags.api,\n react: !!flags.react && !isExpo,\n force,\n });\n if (flags.api) {\n await this.ensureApiProject(root, {\n auth: !!flags.saas,\n adminEmail,\n force,\n });\n }\n if (flags.react && !isExpo) {\n await this.ensureWebProject(root, {\n api: !!flags.api,\n ui: !!flags.ui,\n auth: !!flags.saas,\n admin: !!flags.saas,\n tailwind: !!flags.tailwind,\n force,\n });\n }\n },\n });\n\n // Use workspace PM if detected, otherwise detect from current root\n const pmName = await this.pm.getPackageManager(\n workspace.workspaceRoot ?? root,\n flags.pm ?? workspace.packageManager ?? undefined,\n );\n\n // Only setup PM files if not in a workspace package\n if (!workspace.isPackage) {\n if (pmName === \"yarn\") {\n await this.pm.ensureYarn(root);\n await run(\"yarn set version stable\", { root });\n } else if (pmName === \"bun\") {\n await this.pm.ensureBun(root);\n } else if (pmName === \"pnpm\") {\n await this.pm.ensurePnpm(root);\n } else {\n await this.pm.ensureNpm(root);\n }\n }\n\n // Run install from workspace root if in a package, otherwise from current root\n const installRoot = workspace.workspaceRoot ?? root;\n await run(`${pmName} install`, {\n alias: `installing dependencies with ${pmName}`,\n root: installRoot,\n });\n\n // Create test directory if --test flag is set (vitest is in package.json)\n if (flags.test) {\n await this.ensureTestDir(root);\n }\n\n await run(`${pmName} run lint`, {\n alias: \"running linter\",\n root,\n });\n\n // Initialize git repository if not in a workspace package\n if (!workspace.isPackage) {\n const gitInitialized = await this.ensureGitRepo(root, {\n force,\n });\n if (gitInitialized) {\n await run(\"git add .\", {\n alias: \"staging generated files\",\n root,\n });\n }\n }\n\n // Don't show success message if no path arg, e.g. just \"alepha init\" to re-configure current dir\n if (!args) {\n return;\n }\n\n // We must end the run context in order to log success message\n run.end();\n\n // Success message\n const projectName = args || \".\";\n const pmRun = pmName === \"npm\" ? \"npm run\" : pmName;\n const c = this.colors;\n\n this.log.info(\"\");\n this.log.info(` ${c.set(\"GREEN\", \"✓\")} Project ready!`);\n this.log.info(\"\");\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"$\")} cd ${c.set(\"CYAN\", projectName)}`,\n );\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"$\")} ${c.set(\"CYAN\", `${pmRun} dev`)}`,\n );\n\n if (adminEmail) {\n this.log.info(\"\");\n this.log.info(` Admin email: ${c.set(\"GREEN\", adminEmail)}`);\n this.log.info(\n ` ${c.set(\"GREY_DARK\", \"(from git config, change in src/api/AppSecurity.ts)\")}`,\n );\n }\n\n this.log.info(\"\");\n }\n\n // ===========================================\n // Helpers\n // ===========================================\n\n /**\n * Write a file, optionally overriding if it exists.\n */\n protected async ensureFile(\n root: string,\n relativePath: string,\n content: string,\n force?: boolean,\n ): Promise<void> {\n const fullPath = this.fs.join(root, relativePath);\n if (force || !(await this.fs.exists(fullPath))) {\n await this.fs.writeFile(fullPath, content);\n }\n }\n\n /**\n * Check if a file exists in the given directory or any parent directory.\n */\n protected async existsInParents(\n root: string,\n filename: string,\n ): Promise<boolean> {\n let current = root;\n while (true) {\n if (await this.fs.exists(this.fs.join(current, filename))) {\n return true;\n }\n const parent = dirname(current);\n if (parent === current) {\n // Reached filesystem root\n return false;\n }\n current = parent;\n }\n }\n}\n","import type { Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport type { BuildOptions } from \"../atoms/buildOptions.ts\";\nimport type { AppEntry } from \"../providers/AppEntryProvider.ts\";\n\nexport interface BuildTaskContext {\n /**\n * The user's app Alepha container (NOT the CLI container).\n * Used for metadata extraction (pages, primitives, store, etc.).\n */\n alepha: Alepha;\n\n /**\n * Resolved build options (flags merged with atom defaults).\n * BuildCommand mutates the atom before creating the context,\n * so stats, target, runtime are all resolved values.\n */\n options: BuildOptions;\n\n /**\n * CLI runner for progress logging.\n * Tasks call this when they have work to show.\n * Tasks decide IF and WHEN to call run — e.g. skip entirely if nothing to do.\n */\n run: RunnerMethod;\n\n /**\n * Project root directory.\n */\n root: string;\n\n /**\n * Application entry points resolved by AppEntryProvider.\n */\n entry: AppEntry;\n\n /**\n * Whether the app has a client-side bundle (React).\n */\n hasClient: boolean;\n\n /**\n * Raw CLI flags passed through from the command.\n * Tasks can read flags relevant to their domain.\n */\n flags?: {\n image?: boolean | string;\n };\n}\n\n/**\n * Abstract base class for build pipeline tasks.\n *\n * Each task encapsulates a step in the build pipeline.\n * Tasks control their own progress reporting via ctx.run.\n */\nexport abstract class BuildTask {\n abstract run(ctx: BuildTaskContext): Promise<void>;\n}\n","import { createRequire } from \"node:module\";\nimport { dirname, resolve } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Copy assets from Alepha packages to the build output directory.\n *\n * Reads `alepha.build.assets` state to find packages with assets,\n * and copies their `/assets` directories to the build output.\n * Used by modules like AlephaServerSwagger to distribute UI files.\n */\nexport class BuildAssetsTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const assets = ctx.alepha.store.get(\"alepha.build.assets\");\n\n if (!assets || assets.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const entry = `${distDir}/index.js`;\n\n await ctx.run({\n name: \"copy assets\",\n handler: async () => {\n const require = createRequire(this.fs.join(ctx.root, entry));\n const buildAssetsDir = this.fs.join(ctx.root, distDir, \"assets\");\n await this.fs.mkdir(buildAssetsDir);\n\n for (const pkgName of assets ?? []) {\n const pkgDir = dirname(require.resolve(`${pkgName}/package.json`));\n const assetsPkgDir = resolve(pkgDir, \"assets\");\n await this.fs.cp(assetsPkgDir, buildAssetsDir);\n }\n },\n });\n }\n}\n","import { $inject, Alepha } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { UserConfig } from \"vite\";\nimport { analyzer as viteAnalyzer } from \"vite-bundle-analyzer\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Build client-side bundle with Vite.\n *\n * Compiles the browser/client code for production,\n * including code splitting and minification.\n * Analyze step stays in BuildCommand (ViteBuildProvider).\n * This task wraps only the actual Vite client build call.\n */\nexport class BuildClientTask extends BuildTask {\n protected readonly alepha = $inject(Alepha);\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const stats = ctx.options.stats ?? false;\n const isCI = this.alepha.isCI();\n\n // Write index.html template for Vite to consume\n const template = this.viteUtils.generateIndexHtml(ctx.entry);\n await this.fs.mkdir(this.fs.join(ctx.root, \"node_modules/.alepha\"));\n const indexHtmlPath = this.fs.join(\n ctx.root,\n \"node_modules/.alepha/index.html\",\n );\n await this.fs.writeFile(indexHtmlPath, template);\n\n try {\n await ctx.run({\n name: \"build client\",\n handler: async () => {\n await this.buildClient({\n dist: `${distDir}/${publicDir}`,\n stats,\n silent: !isCI,\n });\n },\n });\n } finally {\n await this.fs.rm(indexHtmlPath);\n }\n }\n\n protected async buildClient(opts: {\n dist: string;\n stats?: boolean | \"json\";\n silent?: boolean;\n }): Promise<void> {\n const { build: viteBuild } = await this.viteUtils.importVite();\n const plugins: any[] = [];\n\n const viteReact = await this.viteUtils.importViteReact();\n if (viteReact) plugins.push(viteReact());\n\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n\n if (opts.stats) {\n plugins.push(\n viteAnalyzer({\n analyzerMode: opts.stats === \"json\" ? \"json\" : \"static\",\n }),\n );\n }\n\n const logger = opts.silent\n ? this.viteUtils.createBufferedLogger()\n : undefined;\n\n const viteBuildClientConfig: UserConfig = {\n mode: \"production\",\n logLevel: opts.silent ? \"silent\" : undefined,\n define: {\n \"process.env.NODE_ENV\": '\"production\"',\n },\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n publicDir: \"public\",\n build: {\n outDir: opts.dist,\n manifest: true,\n chunkSizeWarningLimit: 1000,\n rolldownOptions: {\n input: \"node_modules/.alepha/index.html\",\n output: {\n entryFileNames: \"entry.[hash].js\",\n chunkFileNames: \"chunk.[hash].js\",\n assetFileNames: \"asset.[hash][extname]\",\n },\n },\n },\n customLogger: logger,\n plugins,\n };\n\n try {\n await viteBuild(viteBuildClientConfig);\n await this.postBuildCleanUpForIndexHtml();\n } catch (error) {\n logger?.flush();\n throw error;\n }\n }\n\n /**\n * Weird cleanup required because we changed input from \"index.html\" to \"node_modules/.alepha/index.html\".\n */\n public async postBuildCleanUpForIndexHtml(dist = \"dist/public\") {\n const manifestPath = `${dist}/.vite/manifest.json`;\n let text = await this.fs.readTextFile(manifestPath);\n text = text.replaceAll(\"node_modules/.alepha/index.html\", \"index.html\");\n await this.fs.writeFile(manifestPath, text);\n await this.fs.cp(\n `${dist}/node_modules/.alepha/index.html`,\n `${dist}/index.html`,\n );\n await this.fs.rm(`${dist}/node_modules`, { recursive: true });\n }\n}\n","import { basename } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { KV_DEFAULT_BINDING } from \"alepha/cache\";\nimport { QUEUE_DEFAULT_BINDING } from \"alepha/queue\";\nimport type { CronProvider, WorkerdCronProvider } from \"alepha/scheduler\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\ninterface WranglerConfig {\n [key: string]: any;\n}\n\n/**\n * Generate Cloudflare Workers deployment configuration.\n *\n * Creates:\n * - wrangler.jsonc with worker configuration\n * - main.cloudflare.js entry point for Cloudflare Workers\n */\nexport class BuildCloudflareTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n protected readonly warningComment =\n \"// This file was automatically generated. DO NOT MODIFY.\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"cloudflare\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n\n await ctx.run({\n name: \"generate deploy config (cloudflare)\",\n handler: async () => {\n await this.generateCloudflare(ctx, distDir);\n },\n });\n }\n\n protected async generateCloudflare(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const root = ctx.root;\n const name = basename(root);\n const hasAssets = await this.fs.exists(\n this.fs.join(root, distDir, \"public\"),\n );\n\n const wrangler: WranglerConfig = {\n name,\n main: \"./main.cloudflare.js\",\n compatibility_flags: [\"nodejs_compat\"],\n compatibility_date: \"2025-11-17\",\n no_bundle: true,\n rules: [\n {\n type: \"ESModule\",\n globs: [\"index.js\", \"server/*.js\"],\n },\n ],\n ...ctx.options.cloudflare?.config,\n };\n\n if (hasAssets) {\n wrangler.assets ??= {\n directory: \"./public\",\n binding: \"ASSETS\",\n };\n }\n\n this.enhanceDomain(wrangler);\n this.enhanceCron(ctx, wrangler);\n this.enhanceDatabase(wrangler);\n this.enhanceR2(wrangler);\n this.enhanceKV(wrangler);\n this.enhanceQueue(wrangler);\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"wrangler.jsonc\"),\n JSON.stringify(wrangler, null, 2),\n );\n\n await this.writeWorkerEntryPoint(root, distDir);\n }\n\n protected enhanceDomain(wrangler: WranglerConfig): void {\n const domain = process.env.CLOUDFLARE_DOMAIN;\n if (!domain) {\n return;\n }\n\n wrangler.routes = [\n {\n pattern: domain,\n custom_domain: true,\n },\n ];\n }\n\n protected enhanceCron(ctx: BuildTaskContext, wrangler: WranglerConfig): void {\n if (ctx.alepha.primitives(\"scheduler\").length === 0) {\n return;\n }\n\n let cronProvider: CronProvider | undefined;\n try {\n cronProvider = ctx.alepha.inject(\"CronProvider\") as WorkerdCronProvider;\n } catch {}\n\n const crons = cronProvider?.getCronJobs();\n if (!crons || crons.length === 0) {\n return;\n }\n\n const cronExpressions = [...new Set(crons.map((c) => c.expression))];\n wrangler.triggers ??= {};\n wrangler.triggers.crons = cronExpressions;\n }\n\n protected enhanceDatabase(wrangler: WranglerConfig): void {\n if (process.env.HYPERDRIVE_ID) {\n this.enhanceHyperdrive(wrangler);\n return;\n }\n\n this.enhanceD1(wrangler);\n }\n\n protected static readonly D1_BINDING = \"DB\";\n\n protected enhanceD1(wrangler: WranglerConfig): void {\n const url = process.env.DATABASE_URL;\n if (!url?.startsWith(\"d1:\")) {\n return;\n }\n\n const [dbName, id] = url.replace(\"d1://\", \"\").replace(\"d1:\", \"\").split(\":\");\n const binding = BuildCloudflareTask.D1_BINDING;\n wrangler.d1_databases = wrangler.d1_databases || [];\n wrangler.d1_databases.push({\n binding,\n database_name: dbName,\n database_id: id,\n });\n wrangler.vars ??= {};\n wrangler.vars.DATABASE_URL = `d1://${binding}`;\n }\n\n protected enhanceHyperdrive(wrangler: WranglerConfig): void {\n const hyperdriveId = process.env.HYPERDRIVE_ID;\n if (!hyperdriveId) {\n return;\n }\n\n const binding = \"HYPERDRIVE\";\n wrangler.hyperdrive = wrangler.hyperdrive || [];\n wrangler.hyperdrive.push({\n binding,\n id: hyperdriveId,\n });\n wrangler.vars ??= {};\n wrangler.vars.DATABASE_URL = `hyperdrive://${binding}`;\n\n if (process.env.POSTGRES_SCHEMA) {\n wrangler.vars.POSTGRES_SCHEMA = process.env.POSTGRES_SCHEMA;\n }\n }\n\n protected enhanceR2(wrangler: WranglerConfig): void {\n const bucketName = process.env.R2_BUCKET_NAME;\n if (!bucketName) {\n return;\n }\n\n wrangler.r2_buckets = wrangler.r2_buckets || [];\n wrangler.r2_buckets.push({\n binding: bucketName,\n bucket_name: bucketName,\n });\n wrangler.vars ??= {};\n wrangler.vars.R2_BUCKET_NAME = bucketName;\n }\n\n protected enhanceKV(wrangler: WranglerConfig): void {\n const kvName = process.env.CLOUDFLARE_KV_NAME;\n if (!kvName) {\n return;\n }\n\n const kvId = process.env.CLOUDFLARE_KV_ID;\n\n wrangler.kv_namespaces = wrangler.kv_namespaces || [];\n wrangler.kv_namespaces.push({\n binding: KV_DEFAULT_BINDING,\n id: kvId ?? \"\",\n });\n }\n\n protected enhanceQueue(wrangler: WranglerConfig): void {\n const queueName = process.env.CLOUDFLARE_QUEUE_NAME;\n if (!queueName) {\n return;\n }\n\n wrangler.queues ??= {};\n wrangler.queues.producers = wrangler.queues.producers || [];\n wrangler.queues.producers.push({\n binding: QUEUE_DEFAULT_BINDING,\n queue: queueName,\n });\n wrangler.queues.consumers = wrangler.queues.consumers || [];\n wrangler.queues.consumers.push({\n queue: queueName,\n });\n }\n\n protected async writeWorkerEntryPoint(\n root: string,\n distDir: string,\n ): Promise<void> {\n const workerCode = `\nimport \"./index.js\";\n\nexport default {\n fetch: async (request, env) => {\n const ctx = { req: request, res: undefined };\n\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for fetch event\", err);\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n\n await __alepha.events.emit(\"web:request\", ctx);\n\n return ctx.res;\n },\n\n scheduled: async (event, env, ctx) => {\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for scheduled event\", err);\n throw err;\n }\n\n await __alepha.events.emit(\"cloudflare:scheduled\", {\n cron: event.cron,\n scheduledTime: event.scheduledTime,\n });\n },\n\n queue: async (batch, env) => {\n __alepha.set(\"cloudflare.env\", env);\n\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for queue event\", err);\n throw err;\n }\n\n for (const msg of batch.messages) {\n try {\n await __alepha.events.emit(\"cloudflare:queue\", msg.body);\n msg.ack();\n } catch (e) {\n msg.retry();\n }\n }\n },\n};\n`.trim();\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"main.cloudflare.js\"),\n `${this.warningComment}\\n${workerCode}`.trim(),\n );\n }\n}\n","import { promisify } from \"node:util\";\nimport {\n type BrotliOptions,\n brotliCompress as brotliCompressCb,\n gzip as gzipCb,\n type ZlibOptions,\n} from \"node:zlib\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\nexport interface CompressOptions {\n /**\n * Enable brotli compression. Can be true or brotli-specific options.\n *\n * @default true\n */\n brotli?: boolean | BrotliOptions;\n\n /**\n * Enable gzip compression. Can be true or gzip-specific options.\n *\n * @default false\n */\n gzip?: boolean | ZlibOptions;\n\n /**\n * Filter which files to compress.\n * Can be a RegExp or a function that returns true for files to compress.\n *\n * @default /\\.(js|mjs|cjs|css|wasm|svg|html|xml)$/\n */\n filter?: RegExp | ((fileName: string) => boolean);\n}\n\n/**\n * Compresses all matching files in the public output directory.\n *\n * Creates .gz and .br copies alongside each matching file.\n * Runs as the LAST step in the build pipeline, after all other tasks\n * have written their files.\n */\nexport class BuildCompressTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly gzipCompress = promisify(gzipCb);\n protected readonly brotliCompress = promisify(brotliCompressCb);\n protected readonly defaultFilter = /\\.(js|mjs|cjs|css|wasm|svg|html|xml)$/;\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const dist = ctx.options.output?.dist ?? \"dist\";\n const pub = ctx.options.output?.public ?? \"public\";\n const dir = this.fs.join(ctx.root, dist, pub);\n\n const hasDir = await this.fs.exists(dir);\n if (!hasDir) {\n return;\n }\n\n await ctx.run({\n name: \"compress assets\",\n handler: async () => {\n await this.compressDirectory(dir);\n },\n });\n }\n\n /**\n * Compress all matching files in a directory (recursive).\n */\n protected async compressDirectory(\n dir: string,\n options?: CompressOptions,\n ): Promise<number> {\n const filter = options?.filter ?? this.defaultFilter;\n const files = await this.fs.ls(dir, { recursive: true });\n\n const matchingFiles = files.filter((fileName) => {\n if (typeof filter === \"function\") {\n return filter(fileName);\n }\n return filter.test(fileName);\n });\n\n const tasks: Promise<void>[] = [];\n for (const fileName of matchingFiles) {\n tasks.push(this.compressFile(this.fs.join(dir, fileName), options));\n }\n\n await Promise.all(tasks);\n return matchingFiles.length;\n }\n\n /**\n * Compress a single file. Creates .gz and .br alongside original.\n */\n protected async compressFile(\n filePath: string,\n options?: CompressOptions,\n ): Promise<void> {\n const { brotli = true, gzip = false } = options ?? {};\n const tasks: Promise<void>[] = [];\n const contentPromise = this.fs.readFile(filePath);\n\n if (gzip) {\n const gzipOptions = typeof gzip === \"object\" ? gzip : { level: 9 };\n tasks.push(\n contentPromise.then(async (content) => {\n const compressed = await this.gzipCompress(content, gzipOptions);\n await this.fs.writeFile(`${filePath}.gz`, compressed);\n }),\n );\n }\n\n if (brotli) {\n const brotliOptions = typeof brotli === \"object\" ? brotli : {};\n tasks.push(\n contentPromise.then(async (content) => {\n const compressed = await this.brotliCompress(content, brotliOptions);\n await this.fs.writeFile(`${filePath}.br`, compressed);\n }),\n );\n }\n\n await Promise.all(tasks);\n }\n}\n","import { $inject, AlephaError } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate Docker deployment configuration and optionally build the image.\n *\n * Creates:\n * - Dockerfile with configurable base image\n * - Copies drizzle migrations if they exist\n * - Builds Docker image when `--image` flag is provided\n */\nexport class BuildDockerTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"docker\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const { runtime } = ctx.options;\n\n const dockerFrom =\n ctx.options.docker?.from ??\n (runtime === \"bun\" ? \"oven/bun:alpine\" : \"node:24-alpine\");\n const dockerCommand =\n ctx.options.docker?.command ?? (runtime === \"bun\" ? \"bun\" : \"node\");\n\n await ctx.run({\n name: \"generate deploy config (docker)\",\n handler: async () => {\n await this.copyDrizzleMigrations(ctx.root, distDir);\n await this.writeDockerfile(\n ctx.root,\n distDir,\n dockerFrom,\n dockerCommand,\n );\n },\n });\n\n if (ctx.flags?.image) {\n await this.buildDockerImage(ctx, distDir);\n }\n }\n\n protected async copyDrizzleMigrations(\n root: string,\n distDir: string,\n ): Promise<void> {\n const drizzleDir = this.fs.join(root, \"drizzle\");\n const hasMigrations = await this.fs.exists(drizzleDir);\n if (hasMigrations) {\n await this.fs.cp(drizzleDir, this.fs.join(root, distDir, \"drizzle\"));\n }\n }\n\n protected async writeDockerfile(\n root: string,\n distDir: string,\n image: string,\n command: string,\n ): Promise<void> {\n const dockerfile = `# This file was automatically generated. DO NOT MODIFY.\n# Changes to this file will be lost when the code is regenerated.\nFROM ${image}\nWORKDIR /app\n\nCOPY . .\n\nRUN ${command === \"bun\" ? \"bun\" : \"npm\"} install\n\nENV SERVER_HOST=0.0.0.0\n\nCMD [\"${command}\", \"index.js\"]\n`;\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"Dockerfile\"),\n dockerfile,\n );\n }\n\n protected async buildDockerImage(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const imageConfig = ctx.options.docker?.image;\n const flagValue =\n typeof ctx.flags?.image === \"string\" ? ctx.flags.image : null;\n\n let imageTag: string;\n let version: string;\n\n if (!flagValue) {\n if (!imageConfig?.tag) {\n throw new AlephaError(\n \"Flag '--image' requires 'build.docker.image.tag' in config\",\n );\n }\n version = \"latest\";\n imageTag = `${imageConfig.tag}:${version}`;\n } else if (flagValue.startsWith(\":\")) {\n if (!imageConfig?.tag) {\n throw new AlephaError(\n \"Flag '--image=:version' requires 'build.docker.image.tag' in config\",\n );\n }\n version = flagValue.slice(1);\n imageTag = `${imageConfig.tag}:${version}`;\n } else if (flagValue.includes(\":\")) {\n imageTag = flagValue;\n version = flagValue.split(\":\")[1];\n } else {\n imageTag = `${flagValue}:latest`;\n version = \"latest\";\n }\n\n const args: string[] = [];\n\n if (imageConfig?.args) {\n args.push(imageConfig.args);\n }\n\n if (imageConfig?.oci) {\n const revision = await this.utils.getGitRevision();\n const created = new Date().toISOString();\n\n args.push(`--label \"org.opencontainers.image.revision=${revision}\"`);\n args.push(`--label \"org.opencontainers.image.created=${created}\"`);\n args.push(`--label \"org.opencontainers.image.version=${version}\"`);\n }\n\n const argsStr = args.length > 0 ? `${args.join(\" \")} ` : \"\";\n const dockerCmd = `docker build ${argsStr}-t ${imageTag} ${distDir}`;\n\n await ctx.run(dockerCmd, {\n alias: `docker build ${imageTag}`,\n });\n }\n}\n","import { dirname } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Pre-render static pages defined in the Alepha application.\n *\n * Queries all page primitives with `static: true` and generates\n * static HTML files for each page. Supports pages with parameterized\n * routes via `static.entries` configuration.\n */\nexport class BuildPrerenderTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (!ctx.hasClient) {\n return;\n }\n\n const pages = this.getStaticPages(ctx);\n if (pages.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const dist = this.fs.join(ctx.root, distDir, publicDir);\n\n await ctx.run({\n name: \"pre-render pages\",\n handler: async () => {\n // TODO: running configure here is a temporary workaround\n if (!ctx.alepha.isConfigured()) {\n await ctx.alepha.events.emit(\"configure\", ctx.alepha);\n }\n await this.prerenderFromAlepha(pages, dist);\n },\n });\n }\n\n protected getStaticPages(ctx: BuildTaskContext): any[] {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n return pages.filter((page) => {\n const options = page.options;\n return options.static && !options.children;\n });\n }\n\n protected async prerenderFromAlepha(\n pages: any[],\n dist: string,\n ): Promise<number> {\n let count = 0;\n\n for (const page of pages) {\n const options = page.options;\n const config = typeof options.static === \"object\" ? options.static : {};\n\n if (!options.schema?.params) {\n count += 1;\n await this.renderFile(page, {}, dist);\n continue;\n }\n\n if (config.entries) {\n for (const entry of config.entries) {\n count += 1;\n await this.renderFile(page, entry, dist);\n }\n }\n }\n\n return count;\n }\n\n protected async renderFile(\n page: any,\n options: any,\n dist: string,\n ): Promise<void> {\n const { html, state } = await page.render({\n html: true,\n ...options,\n });\n\n const pathname = state.url.pathname;\n const filepath = `${dist}${pathname === \"/\" ? \"/index\" : pathname}.html`;\n\n await this.fs.mkdir(dirname(filepath));\n await this.fs.writeFile(filepath, html);\n }\n}\n","import { createRequire } from \"node:module\";\nimport { isAbsolute, join } from \"node:path\";\nimport { $inject, Alepha, AlephaError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type * as vite from \"vite\";\nimport type { UserConfig } from \"vite\";\nimport { analyzer as viteAnalyzer } from \"vite-bundle-analyzer\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Build server-side SSR bundle with Vite.\n *\n * Compiles the server code for production, generates the externals\n * package.json, and creates the dist/index.js entry wrapper.\n */\nexport class BuildServerTask extends BuildTask {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const stats = ctx.options.stats ?? false;\n const isCI = this.alepha.isCI();\n\n const clientIndexPath = this.fs.join(\n ctx.root,\n distDir,\n publicDir,\n \"index.html\",\n );\n const clientBuilt = await this.fs.exists(clientIndexPath);\n\n const conditions: string[] = [];\n if (ctx.options.runtime === \"bun\") {\n conditions.push(\"bun\");\n } else if (ctx.options.runtime === \"workerd\") {\n conditions.push(\"workerd\");\n }\n\n await ctx.run({\n name: \"build server\",\n handler: async () => {\n await this.buildServer({\n root: ctx.root,\n entry: ctx.entry.server,\n distDir,\n clientDir: clientBuilt ? publicDir : undefined,\n stats,\n silent: !isCI,\n conditions,\n alepha: ctx.alepha,\n });\n\n // Server will handle index.html if both client & server are built\n if (clientBuilt) {\n await this.fs.rm(clientIndexPath);\n }\n },\n });\n }\n\n protected async buildServer(opts: {\n root: string;\n entry: string;\n distDir: string;\n clientDir?: string;\n stats?: boolean | \"json\";\n silent?: boolean;\n conditions?: string[];\n alepha: Alepha;\n }): Promise<void> {\n const { build: viteBuild, resolveConfig } =\n await this.viteUtils.importVite();\n const plugins: any[] = [];\n\n const viteReact = await this.viteUtils.importViteReact();\n if (viteReact && opts.clientDir) {\n plugins.push(viteReact());\n }\n\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n\n if (opts.stats) {\n plugins.push(\n viteAnalyzer({\n analyzerMode: opts.stats === \"json\" ? \"json\" : \"static\",\n }),\n );\n }\n\n const logger = opts.silent\n ? this.viteUtils.createBufferedLogger()\n : undefined;\n\n const conditions = [\"node\", \"import\", \"module\", \"default\"];\n if (opts.conditions) {\n conditions.unshift(...opts.conditions);\n }\n\n const viteBuildServerConfig: UserConfig = {\n mode: \"production\",\n logLevel: opts.silent ? \"silent\" : undefined,\n define: {\n \"process.env.NODE_ENV\": '\"production\"',\n },\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n publicDir: false,\n ssr: {\n noExternal: true,\n resolve: { conditions },\n },\n build: {\n ssr: opts.entry,\n minify: true,\n sourcemap: true,\n chunkSizeWarningLimit: 10000,\n outDir: `${opts.distDir}/server`,\n rolldownOptions: {\n external: [/^bun(:|$)/, /^cloudflare:/],\n output: {\n entryFileNames: \"[hash].js\",\n chunkFileNames: \"[hash].js\",\n assetFileNames: \"[hash][extname]\",\n format: \"esm\",\n // Rolldown/Oxc minifier: preserve class and function names\n minify: {\n mangle: { keepNames: true },\n compress: {\n keepNames: { function: true, class: true },\n },\n },\n },\n },\n },\n customLogger: logger,\n plugins,\n };\n\n let result: vite.Rollup.RollupOutput | vite.Rollup.RollupOutput[];\n try {\n result = (await viteBuild(viteBuildServerConfig)) as\n | vite.Rollup.RollupOutput\n | vite.Rollup.RollupOutput[];\n } catch (error) {\n logger?.flush();\n throw error;\n }\n\n const resolvedConfig = await resolveConfig(viteBuildServerConfig, \"build\");\n\n const externals: string[] = [];\n if (Array.isArray(resolvedConfig?.ssr?.external)) {\n externals.push(...resolvedConfig.ssr.external);\n }\n\n await this.generateExternals(opts.distDir, externals);\n\n const entryFile = this.extractEntryFromBundle(\n opts.root,\n opts.entry,\n result,\n );\n\n let manifest = \"\";\n let manifestData:\n | {\n base?: string;\n client?: Record<string, any>;\n preload?: Record<string, string>;\n favicon?: string;\n }\n | undefined;\n\n if (opts.clientDir) {\n const viteDir = `${opts.distDir}/${opts.clientDir}/.vite`;\n const clientManifest = await this.loadJsonFile(\n `${viteDir}/manifest.json`,\n );\n const preloadManifest = await this.loadJsonFile(\n `${viteDir}/preload-manifest.json`,\n );\n\n const strippedClientManifest = this.stripClientManifest(clientManifest);\n\n let base = resolvedConfig.base || \"/\";\n if (!base.startsWith(\"/\")) {\n base = `/${base}`;\n }\n if (base.length > 1 && base.endsWith(\"/\")) {\n base = base.slice(0, -1);\n }\n\n const favicon = await this.detectFavicon(\n `${opts.distDir}/${opts.clientDir}`,\n );\n\n manifestData = {\n base: base !== \"/\" ? base : undefined,\n client: strippedClientManifest,\n preload: preloadManifest,\n favicon,\n };\n\n manifest = `__alepha.set(\"alepha.react.ssr.manifest\", ${JSON.stringify(manifestData, null, \" \")});\\n`;\n\n opts.alepha.store.set(\"alepha.react.ssr.manifest\" as any, manifestData);\n\n await this.fs.rm(viteDir, { recursive: true });\n }\n\n const warning =\n \"// This file was automatically generated. DO NOT MODIFY.\" +\n \"\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n await this.fs.writeFile(\n `${opts.distDir}/index.js`,\n `${warning}\\nimport './server/${entryFile}';\\n\\n${manifest}`.trim(),\n );\n }\n\n /**\n * Detect a favicon file in the given directory.\n * Returns \"mimeType:/path\" if found, undefined otherwise.\n */\n protected async detectFavicon(\n publicDir: string,\n ): Promise<string | undefined> {\n const candidates: [string, string][] = [\n [\"favicon.svg\", \"image/svg+xml\"],\n [\"favicon.png\", \"image/png\"],\n [\"favicon.ico\", \"image/x-icon\"],\n ];\n for (const [file, mime] of candidates) {\n if (await this.fs.exists(join(publicDir, file))) {\n return `${mime}:/${file}`;\n }\n }\n return undefined;\n }\n\n protected async generateExternals(\n distDir: string,\n externals: string[],\n ): Promise<void> {\n const require = createRequire(import.meta.filename);\n const deps: Record<string, string> = {};\n\n for (const dep of externals) {\n try {\n const requirePath = require.resolve(dep);\n const pkgPath = `${requirePath.split(`node_modules/${dep}`)[0]}node_modules/${dep}/package.json`;\n const pkg = JSON.parse((await this.fs.readFile(pkgPath)).toString());\n deps[dep] = `^${pkg.version}`;\n } catch {\n this.log.warn(`Cannot find '${dep}' in node_modules`);\n }\n }\n\n const minimalPkg = {\n type: \"module\",\n main: \"index.js\",\n dependencies: deps,\n };\n\n await this.fs.mkdir(distDir);\n await this.fs.writeFile(\n join(distDir, \"package.json\"),\n JSON.stringify(minimalPkg, null, 2),\n );\n }\n\n protected async loadJsonFile(path: string): Promise<any> {\n try {\n const content = (await this.fs.readFile(path)).toString();\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n protected stripClientManifest(\n manifest: Record<string, any> | undefined,\n ): Record<string, any> | undefined {\n if (!manifest) return undefined;\n\n const stripped: Record<string, any> = {};\n for (const [key, entry] of Object.entries(manifest)) {\n stripped[key] = {\n file: entry.file,\n ...(entry.isEntry && { isEntry: entry.isEntry }),\n ...(entry.imports?.length && { imports: entry.imports }),\n ...(entry.css?.length && { css: entry.css }),\n };\n }\n return stripped;\n }\n\n protected extractEntryFromBundle(\n root: string,\n entry: string,\n result:\n | vite.Rollup.RollupOutput\n | vite.Rollup.RollupOutput[]\n | vite.Rollup.RollupWatcher,\n ): string {\n const entryFilePath = isAbsolute(entry) ? entry : join(root, entry);\n\n const normalizedEntryPath = entryFilePath.replace(/\\\\/g, \"/\");\n\n const rollupOutput = (\n Array.isArray(result) ? result[0] : result\n ) as vite.Rollup.RollupOutput;\n\n const entryFile = rollupOutput.output.find(\n (it) =>\n \"facadeModuleId\" in it && it.facadeModuleId === normalizedEntryPath,\n )?.fileName;\n\n if (!entryFile) {\n throw new AlephaError(\n `Could not find the entry file \"${entryFilePath}\" in the build output. Please check your entry file and try again.`,\n );\n }\n\n return entryFile;\n }\n}\n","import { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate sitemap.xml from Alepha page primitives.\n *\n * Queries all page primitives and generates a sitemap.xml\n * containing URLs for all accessible pages.\n */\nexport class BuildSitemapTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n const hostname = ctx.options.sitemap?.hostname;\n if (!hostname) {\n return;\n }\n\n const pages = this.getSitemapPages(ctx);\n if (pages.length === 0) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const output = this.fs.join(ctx.root, distDir, publicDir, \"sitemap.xml\");\n\n await ctx.run({\n name: \"generate sitemap\",\n handler: async () => {\n const xml = this.generateSitemapFromPages(pages, hostname);\n await this.fs.writeFile(output, xml);\n },\n });\n }\n\n protected getSitemapPages(ctx: BuildTaskContext): any[] {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n return pages.filter((page) => {\n const options = page.options;\n if (options.children) {\n return false;\n }\n if (!options.schema?.params) {\n return true;\n }\n if (\n options.static &&\n typeof options.static === \"object\" &&\n options.static.entries\n ) {\n return true;\n }\n return false;\n });\n }\n\n protected generateSitemapFromPages(pages: any[], baseUrl: string): string {\n const urls: string[] = [];\n const normalizedBaseUrl = baseUrl.replace(/\\/$/, \"\");\n\n for (const page of pages) {\n const options = page.options;\n\n if (!options.schema?.params) {\n const path = options.path || \"\";\n const url = `${normalizedBaseUrl}${path === \"\" ? \"/\" : path}`;\n urls.push(url);\n } else if (\n options.static &&\n typeof options.static === \"object\" &&\n options.static.entries\n ) {\n for (const entry of options.static.entries) {\n const path = this.buildPathFromParams(\n options.path || \"\",\n entry.params || {},\n );\n const url = `${normalizedBaseUrl}${path}`;\n urls.push(url);\n }\n }\n }\n\n return this.buildSitemapXml(urls);\n }\n\n protected buildPathFromParams(\n pathPattern: string,\n params: Record<string, any>,\n ): string {\n let path = pathPattern;\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, String(value));\n }\n return path || \"/\";\n }\n\n protected buildSitemapXml(urls: string[]): string {\n const lastMod = new Date().toISOString().split(\"T\")[0];\n const urlEntries = urls\n .map(\n (url) =>\n ` <url>\\n <loc>${this.escapeXml(url)}</loc>\\n <lastmod>${lastMod}</lastmod>\\n </url>`,\n )\n .join(\"\\n\");\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n${urlEntries}\n</urlset>`;\n }\n\n protected escapeXml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate a static site output.\n *\n * Ensures index.html, 200.html, and 404.html exist in the client directory,\n * then removes all server artifacts from dist, keeping only the public directory.\n */\nexport class BuildStaticTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"static\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const clientDir = ctx.options.output?.public ?? \"public\";\n const publicDir = this.fs.join(ctx.root, distDir, clientDir);\n\n await ctx.run({\n name: \"generate static site\",\n handler: async () => {\n if (!ctx.alepha.isConfigured()) {\n await ctx.alepha.events.emit(\"configure\", ctx.alepha);\n }\n\n const indexPath = this.fs.join(publicDir, \"index.html\");\n const isPrerendered = await this.fs.exists(indexPath);\n if (!isPrerendered) {\n await this.renderRootPage(ctx, publicDir);\n }\n\n const indexHtml = (await this.fs.readFile(indexPath)).toString();\n const shell = this.stripRootContent(indexHtml);\n\n if (!isPrerendered) {\n await this.fs.writeFile(indexPath, shell);\n }\n\n const notFoundPath = this.fs.join(publicDir, \"404.html\");\n if (!(await this.fs.exists(notFoundPath))) {\n await this.fs.writeFile(notFoundPath, shell);\n }\n\n const spaPath = this.fs.join(publicDir, \"200.html\");\n if (!(await this.fs.exists(spaPath))) {\n await this.fs.writeFile(spaPath, shell);\n }\n\n const cnamePath = this.fs.join(publicDir, \"CNAME\");\n if (!(await this.fs.exists(cnamePath))) {\n const domain =\n ctx.options.static?.domain ?? (await this.generateDomain(ctx.root));\n await this.fs.writeFile(cnamePath, domain);\n }\n\n await this.cleanDist(this.fs.join(ctx.root, distDir), clientDir);\n },\n });\n }\n\n protected async renderRootPage(\n ctx: BuildTaskContext,\n publicDir: string,\n ): Promise<void> {\n const pages = ctx.alepha.primitives(\"page\") as any[];\n const rootPage = pages.find(\n (p) => p.options.path === \"/\" && !p.options.children,\n );\n\n if (!rootPage) {\n return;\n }\n\n const { html } = await rootPage.render({ html: true });\n const filepath = this.fs.join(publicDir, \"index.html\");\n\n await this.fs.mkdir(dirname(filepath));\n await this.fs.writeFile(filepath, html);\n }\n\n protected stripRootContent(html: string): string {\n return html.replace(\n /(<body[^>]*>)[\\s\\S]*?(<\\/body>)/,\n '$1<div id=\"root\"></div>$2',\n );\n }\n\n protected async cleanDist(distDir: string, clientDir: string): Promise<void> {\n const entries = await this.fs.ls(distDir);\n for (const entry of entries) {\n if (entry !== clientDir) {\n await this.fs.rm(this.fs.join(distDir, entry), { recursive: true });\n }\n }\n }\n\n protected async generateDomain(root: string): Promise<string> {\n let name = \"app\";\n try {\n const content = (\n await this.fs.readFile(this.fs.join(root, \"package.json\"))\n ).toString();\n const pkg = JSON.parse(content);\n if (pkg.name) {\n name = pkg.name\n .replace(/^@/, \"\")\n .replace(/\\//g, \"-\")\n .replace(/[^a-z0-9-]/g, \"\");\n }\n } catch {\n // fallback to \"app\"\n }\n\n const hash = createHash(\"sha256\").update(name).digest(\"hex\").slice(0, 6);\n return `${name}-${hash}.surge.sh`;\n }\n}\n","import { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate Vercel Build Output API v3 deployment configuration.\n *\n * Creates:\n * - .vercel/output/config.json with routes and version\n * - .vercel/output/static/ (moved from dist/public/)\n * - .vercel/output/functions/index.func/ with handler, index.js, server/, package.json\n * - .vercel/project.json if projectId and orgId are set\n */\nexport class BuildVercelTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n protected readonly warningComment =\n \"// This file was automatically generated. DO NOT MODIFY.\\n\" +\n \"// Changes to this file will be lost when the code is regenerated.\\n\";\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.options.target !== \"vercel\") {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n\n await ctx.run({\n name: \"generate deploy config (vercel)\",\n handler: async () => {\n await this.generateVercel(ctx, distDir);\n },\n });\n }\n\n protected async generateVercel(\n ctx: BuildTaskContext,\n distDir: string,\n ): Promise<void> {\n const root = ctx.root;\n const dist = this.fs.join(root, distDir);\n\n const outputDir = this.fs.join(dist, \".vercel\", \"output\");\n const funcDir = this.fs.join(outputDir, \"functions\", \"index.func\");\n const staticDir = this.fs.join(outputDir, \"static\");\n\n await this.fs.mkdir(funcDir);\n await this.fs.mkdir(staticDir);\n\n await this.writeOutputConfig(outputDir, ctx.options.vercel?.config);\n await this.writeVcConfig(funcDir);\n await this.writeHandler(funcDir);\n await this.copyServerBundle(dist, funcDir);\n await this.copyStaticAssets(dist, staticDir);\n await this.writeProjectConfig(ctx, dist);\n }\n\n /**\n * Write .vercel/output/config.json with Build Output API v3 format.\n */\n protected async writeOutputConfig(\n outputDir: string,\n config?: { crons?: { path: string; schedule: string }[] },\n ): Promise<void> {\n const outputConfig: Record<string, any> = {\n version: 3,\n routes: [{ handle: \"filesystem\" }, { src: \"/(.*)\", dest: \"/index\" }],\n };\n\n if (config?.crons && config.crons.length > 0) {\n outputConfig.crons = config.crons;\n }\n\n await this.fs.writeFile(\n this.fs.join(outputDir, \"config.json\"),\n JSON.stringify(outputConfig, null, 2),\n );\n }\n\n /**\n * Write .vc-config.json for the serverless function.\n */\n protected async writeVcConfig(funcDir: string): Promise<void> {\n await this.fs.writeFile(\n this.fs.join(funcDir, \".vc-config.json\"),\n JSON.stringify(\n {\n runtime: \"nodejs22.x\",\n handler: \"handler.js\",\n launcherType: \"Nodejs\",\n },\n null,\n 2,\n ),\n );\n }\n\n /**\n * Write the handler.js entry point that uses node:request event.\n */\n protected async writeHandler(funcDir: string): Promise<void> {\n const handlerCode = `\nimport \"./index.js\";\n\nexport default async (req, res) => {\n try {\n await __alepha.start();\n } catch (err) {\n __alepha.log.error(\"Failed to start Alepha for request\", err);\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"Internal Server Error\");\n return;\n }\n\n await __alepha.events.emit(\"node:request\", { req, res });\n};\n`.trim();\n\n await this.fs.writeFile(\n this.fs.join(funcDir, \"handler.js\"),\n `${this.warningComment}\\n${handlerCode}`,\n );\n }\n\n /**\n * Copy the server bundle (index.js, server/, package.json) into the function directory.\n */\n protected async copyServerBundle(\n dist: string,\n funcDir: string,\n ): Promise<void> {\n await this.fs.cp(\n this.fs.join(dist, \"index.js\"),\n this.fs.join(funcDir, \"index.js\"),\n );\n\n await this.fs.cp(\n this.fs.join(dist, \"package.json\"),\n this.fs.join(funcDir, \"package.json\"),\n );\n\n const serverDir = this.fs.join(dist, \"server\");\n if (await this.fs.exists(serverDir)) {\n await this.fs.cp(serverDir, this.fs.join(funcDir, \"server\"));\n }\n }\n\n /**\n * Move static assets from dist/public/ to .vercel/output/static/.\n */\n protected async copyStaticAssets(\n dist: string,\n staticDir: string,\n ): Promise<void> {\n const publicDir = this.fs.join(dist, \"public\");\n if (await this.fs.exists(publicDir)) {\n await this.fs.cp(publicDir, staticDir);\n } else {\n await this.fs.writeFile(this.fs.join(staticDir, \".keep\"), \"\");\n }\n }\n\n /**\n * Write .vercel/project.json if projectId and orgId are available.\n */\n protected async writeProjectConfig(\n ctx: BuildTaskContext,\n dist: string,\n ): Promise<void> {\n const projectId =\n process.env.VERCEL_PROJECT_ID ?? ctx.options.vercel?.projectId;\n const projectName =\n process.env.VERCEL_PROJECT_NAME ?? ctx.options.vercel?.projectName;\n const orgId = process.env.VERCEL_ORG_ID ?? ctx.options.vercel?.orgId;\n\n if (!projectId || !orgId) {\n return;\n }\n\n const vercelDir = this.fs.join(dist, \".vercel\");\n await this.fs.mkdir(vercelDir);\n\n await this.fs.writeFile(\n this.fs.join(vercelDir, \"project.json\"),\n JSON.stringify(\n {\n projectId,\n projectName,\n orgId,\n },\n null,\n 2,\n ),\n );\n }\n}\n","import { $inject, $state, Alepha, AlephaError, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport {\n type BuildRuntime,\n type BuildTarget,\n buildOptions,\n} from \"../atoms/buildOptions.ts\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { ViteBuildProvider } from \"../providers/ViteBuildProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\nimport { BuildAssetsTask } from \"../tasks/BuildAssetsTask.ts\";\nimport { BuildClientTask } from \"../tasks/BuildClientTask.ts\";\nimport { BuildCloudflareTask } from \"../tasks/BuildCloudflareTask.ts\";\nimport { BuildCompressTask } from \"../tasks/BuildCompressTask.ts\";\nimport { BuildDockerTask } from \"../tasks/BuildDockerTask.ts\";\nimport { BuildPrerenderTask } from \"../tasks/BuildPrerenderTask.ts\";\nimport { BuildServerTask } from \"../tasks/BuildServerTask.ts\";\nimport { BuildSitemapTask } from \"../tasks/BuildSitemapTask.ts\";\nimport { BuildStaticTask } from \"../tasks/BuildStaticTask.ts\";\nimport type { BuildTaskContext } from \"../tasks/BuildTask.ts\";\nimport { BuildVercelTask } from \"../tasks/BuildVercelTask.ts\";\n\nexport class BuildCommand {\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly viteBuildProvider = $inject(ViteBuildProvider);\n protected readonly options = $state(buildOptions);\n\n /**\n * Build pipeline: tasks run sequentially in this order.\n * Each task self-guards (checks target, hasClient, etc.).\n * Order matters — compress must be last.\n */\n protected readonly pipeline = [\n $inject(BuildClientTask),\n $inject(BuildServerTask),\n $inject(BuildAssetsTask),\n $inject(BuildSitemapTask),\n $inject(BuildPrerenderTask),\n $inject(BuildVercelTask),\n $inject(BuildCloudflareTask),\n $inject(BuildDockerTask),\n $inject(BuildStaticTask),\n $inject(BuildCompressTask),\n ];\n\n /**\n * Resolve the effective runtime based on target and explicit runtime flag.\n *\n * Some targets force a specific runtime:\n * - `cloudflare` always uses `workerd`\n * - `vercel` always uses `node`\n * - `docker` and bare deployments respect the runtime flag\n *\n * @throws {AlephaError} If an incompatible runtime is specified for a target\n */\n protected resolveRuntime(\n target: BuildTarget | undefined,\n runtime: BuildRuntime | undefined,\n ): BuildRuntime {\n if (target === \"cloudflare\") {\n if (runtime && runtime !== \"workerd\") {\n throw new AlephaError(\n `Target 'cloudflare' requires 'workerd' runtime, got '${runtime}'`,\n );\n }\n return \"workerd\";\n }\n\n if (target === \"vercel\") {\n if (runtime && runtime !== \"node\") {\n throw new AlephaError(\n `Target 'vercel' requires 'node' runtime, got '${runtime}'`,\n );\n }\n return \"node\";\n }\n\n return runtime ?? \"node\";\n }\n\n public readonly build = $command({\n name: \"build\",\n mode: \"production\",\n description: \"Build the project for production\",\n flags: t.object({\n stats: t.optional(\n t.union([t.boolean(), t.enum([\"json\"])], {\n description: \"Generate build stats report\",\n }),\n ),\n target: t.optional(\n t.enum([\"bare\", \"docker\", \"vercel\", \"cloudflare\", \"static\"], {\n aliases: [\"t\"],\n description: \"Deployment target\",\n }),\n ),\n runtime: t.optional(\n t.enum([\"node\", \"bun\", \"workerd\"], {\n aliases: [\"r\"],\n description: \"JavaScript runtime\",\n }),\n ),\n image: t.optional(\n t.union([t.boolean(), t.text()], {\n aliases: [\"i\"],\n description:\n \"Build Docker image. Use -i for latest, -i=<version> for specific version\",\n }),\n ),\n sitemap: t.optional(\n t.text({\n description: \"Generate sitemap.xml with base URL\",\n }),\n ),\n }),\n handler: async ({ flags, run, root }) => {\n process.env.NODE_ENV = \"production\";\n\n if (await this.pm.hasExpo(root)) {\n // will come soon\n return;\n }\n\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const entry = await this.boot.getAppEntry(root);\n this.log.trace(\"Entry file found\", { entry });\n\n // Resolve flags → mutate the atom (single source of truth)\n this.alepha.store.mut(buildOptions, (current) => ({\n ...current,\n stats: flags.stats ?? current.stats ?? false,\n target: flags.target ?? current.target,\n runtime: this.resolveRuntime(\n flags.target ?? current.target,\n flags.runtime ?? current.runtime,\n ),\n ...(flags.sitemap && {\n sitemap: { hostname: flags.sitemap },\n }),\n }));\n\n const options = this.options;\n\n const distDir = options.output?.dist ?? \"dist\";\n\n await run.rm(distDir, { alias: \"clean dist\" });\n\n const { target } = options;\n\n // Validate --image requires --target=docker\n if (flags.image && target !== \"docker\") {\n throw new AlephaError(\n `Flag '--image' requires '--target=docker', got '${target ?? \"bare\"}'`,\n );\n }\n\n this.log.trace(\"Build configuration\", {\n target,\n runtime: options.runtime,\n });\n\n let appAlepha: Alepha | undefined;\n let hasClient = false;\n\n await run({\n name: \"analyze app\",\n handler: async () => {\n appAlepha = await this.viteBuildProvider.init({ entry });\n hasClient = this.viteBuildProvider.hasClient();\n },\n });\n\n if (!appAlepha) {\n throw new AlephaError(\"Alepha instance not found\");\n }\n\n const ctx: BuildTaskContext = {\n alepha: appAlepha,\n options,\n root,\n run,\n entry,\n hasClient,\n flags: { image: flags.image },\n };\n\n for (const task of this.pipeline) {\n await task.run(ctx);\n }\n },\n });\n}\n","import { $command } from \"alepha/command\";\n\nexport class CleanCommand {\n /**\n * Clean the project, removing the \"dist\" directory\n */\n public readonly clean = $command({\n name: \"clean\",\n description: \"Clean the project\",\n handler: async ({ run }) => {\n await run.rm(\"./dist\");\n },\n });\n}\n","import { $inject, AlephaError, t } from \"alepha\";\nimport { $command, Runner } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport type {\n DatabaseProvider,\n DrizzleKitProvider,\n RepositoryProvider,\n} from \"alepha/orm\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\n\nconst drizzleCommandFlags = t.object({\n provider: t.optional(\n t.text({\n description:\n \"Database provider name to target (e.g., 'postgres', 'sqlite')\",\n }),\n ),\n});\n\nexport class DbCommand {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly entryProvider = $inject(AppEntryProvider);\n protected readonly viteUtil = $inject(ViteUtils);\n protected readonly runner = $inject(Runner);\n\n /**\n * Check if database migrations are up to date.\n */\n protected readonly check = $command({\n name: \"check\",\n mode: true,\n description: \"Check if migration files are up to date\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ args, root }) => {\n const rootDir = root;\n this.log.debug(`Using project root: ${rootDir}`);\n\n const entry = await this.entryProvider.getAppEntry(root);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n if (accepted.has(providerName)) {\n continue;\n }\n\n accepted.add(providerName);\n\n const migrationDir = this.fs.join(rootDir, \"migrations\", providerName);\n\n const journalBuffer = await this.fs\n .readFile(this.fs.join(migrationDir, \"meta\", \"_journal.json\"))\n .catch(() => null);\n\n if (!journalBuffer) {\n this.log.info(\"No migration journal found.\");\n return;\n }\n\n const journal = JSON.parse(journalBuffer.toString(\"utf-8\"));\n const lastMigration = journal.entries[journal.entries.length - 1];\n const snapshotBuffer = await this.fs.readFile(\n this.fs.join(\n migrationDir,\n \"meta\",\n `${String(lastMigration.idx).padStart(4, \"0\")}_snapshot.json`,\n ),\n );\n const lastSnapshot = JSON.parse(snapshotBuffer.toString(\"utf-8\"));\n\n const { statements: migrationStatements } =\n await drizzleKitProvider.generateMigration(provider, lastSnapshot, {\n withoutSchema: true,\n });\n\n if (migrationStatements.length === 0) {\n this.log.info(\"No changes detected.\");\n return;\n }\n\n this.log.info(\"\");\n this.log.info(\"Detected migration statements:\");\n this.log.info(\"\");\n for (const stmt of migrationStatements) {\n this.log.info(stmt);\n }\n this.log.info(\"\");\n\n this.log.info(\n `At least ${migrationStatements.length} change(s) detected.`,\n );\n this.log.info(\n \"Please, run 'alepha db migrations generate' to update the migration files.\",\n );\n this.log.info(\"\");\n\n throw new AlephaError(\"Database migrations are not up to date.\");\n }\n },\n });\n\n /**\n * Generate database migration files\n */\n protected readonly create = $command({\n name: \"create\",\n mode: true,\n description: \"Generate migration files from current schema\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: t.extend(drizzleCommandFlags, {\n custom: t.optional(\n t.boolean({\n description:\n \"Generate an empty migration file for custom SQL (e.g., for data migrations or manual adjustments)\",\n }),\n ),\n name: t.optional(\n t.text({\n description: \"Name for the generated migration file\",\n }),\n ),\n }),\n handler: async ({ args, flags, root }) => {\n const parts: string[] = [];\n if (flags.custom) parts.push(`--custom=1`);\n if (flags.name) parts.push(`--name=${flags.name}`);\n const commandFlags = parts.length > 0 ? parts.join(\" \") : undefined;\n\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"generate\",\n commandFlags,\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Generate '${providerName}' migrations (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Push database schema changes directly to the database\n */\n protected readonly push = $command({\n name: \"push\",\n mode: true,\n description: \"Push database schema changes directly to the database\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: t.extend(drizzleCommandFlags, {\n dryRun: t.optional(\n t.boolean({\n description: \"Preview SQL statements without executing them\",\n }),\n ),\n }),\n handler: async ({ root, args, flags }) => {\n if (flags.dryRun) {\n const entry = await this.entryProvider.getAppEntry(root);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n\n if (accepted.has(providerName)) continue;\n accepted.add(providerName);\n\n if (flags.provider && flags.provider !== providerName) continue;\n\n this.log.info(\"\");\n this.log.info(\n `Dry run for '${providerName}' (${provider.dialect}) ...`,\n );\n\n await (provider as any).connect();\n\n try {\n const result = await drizzleKitProvider.dryRunPush(provider);\n\n if (result.statements.length === 0) {\n this.log.info(\"No changes detected.\");\n } else {\n if (result.hasDataLoss) {\n this.log.warn(\"WARNING: These changes would cause data loss!\");\n for (const warning of result.warnings) {\n this.log.warn(` ${warning}`);\n }\n }\n\n this.log.info(\"\");\n this.log.info(\n `${result.statements.length} statement(s) would be executed:`,\n );\n this.log.info(\"\");\n for (const stmt of result.statements) {\n this.log.info(stmt);\n }\n }\n } finally {\n await (provider as any).close();\n }\n }\n return;\n }\n\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"push\",\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Push '${providerName}' schema (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Apply pending database migrations\n */\n protected readonly apply = $command({\n name: \"apply\",\n mode: true,\n description: \"Apply pending migrations to the database\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ root, run, mode }) => {\n const entry = await this.entryProvider.getAppEntry(root);\n\n await run({\n name: `db migrate (${mode || \"development\"})`,\n handler: async () => {\n process.env.MIGRATE = \"true\";\n\n if (this.runner.useDynamicLogger) {\n process.env.LOG_LEVEL = \"warn\";\n }\n\n const alepha = await this.viteUtil.runAlepha({\n entry,\n mode: \"production\",\n });\n\n await alepha.start();\n },\n });\n },\n\n // await run({\n // name: `db migrate (${mode || \"development\"})`,\n // handler: async () => {\n // await this.utils.exec(`tsx ${entry.server}`, {\n // capture: this.runner.useDynamicLogger,\n // env: {\n // ...process.env,\n // NODE_ENV: \"production\",\n // MIGRATE: \"true\",\n // },\n // });\n // },\n // });\n // },\n });\n\n /**\n * Launch Drizzle Studio database browser\n */\n protected readonly studio = $command({\n name: \"studio\",\n mode: true,\n description: \"Launch Drizzle Studio database browser\",\n args: t.optional(\n t.text({\n title: \"path\",\n description: \"Path to the Alepha server entry file\",\n }),\n ),\n flags: drizzleCommandFlags,\n handler: async ({ root, args, flags }) => {\n await this.runDrizzleKitCommand({\n root,\n args,\n command: \"studio\",\n provider: flags.provider,\n logMessage: (providerName, dialect) =>\n `Launch Studio for '${providerName}' (${dialect}) ...`,\n });\n },\n });\n\n /**\n * Parent command for migration operations.\n */\n protected readonly migrations = $command({\n name: \"migrations\",\n aliases: [\"m\"],\n description: \"Manage database migrations\",\n children: [this.check, this.create, this.apply],\n handler: async ({ help }) => {\n help();\n },\n });\n\n /**\n * Parent command for database operations.\n */\n public readonly db = $command({\n name: \"db\",\n description: \"Database management commands\",\n children: [this.migrations, this.push, this.studio],\n handler: async ({ help }) => {\n help();\n },\n });\n\n /**\n * Run a drizzle-kit command for all database providers in an Alepha instance.\n */\n public async runDrizzleKitCommand(options: {\n root: string;\n args?: string;\n command: string;\n commandFlags?: string;\n provider?: string;\n logMessage: (providerName: string, dialect: string) => string;\n }): Promise<void> {\n const rootDir = options.root;\n\n this.log.debug(`Using project root: ${rootDir}`);\n\n const entry = await this.entryProvider.getAppEntry(rootDir);\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n mode: \"development\",\n entry,\n });\n\n const drizzleKitProvider =\n alepha.inject<DrizzleKitProvider>(\"DrizzleKitProvider\");\n const repositoryProvider =\n alepha.inject<RepositoryProvider>(\"RepositoryProvider\");\n const accepted = new Set<string>([]);\n\n for (const primitive of repositoryProvider.getRepositories()) {\n const provider = primitive.provider;\n const providerName = provider.name;\n const dialect = provider.dialect;\n\n if (providerName === \"\") {\n continue;\n }\n\n if (accepted.has(providerName)) {\n continue;\n }\n accepted.add(providerName);\n\n // Skip if provider filter is set and doesn't match\n if (options.provider && options.provider !== providerName) {\n this.log.debug(\n `Skipping provider '${providerName}' (filter: ${options.provider})`,\n );\n continue;\n }\n\n this.log.info(\"\");\n this.log.info(options.logMessage(providerName, dialect));\n\n const drizzleConfigJsPath = await this.prepareDrizzleConfig({\n kit: drizzleKitProvider,\n provider,\n providerName,\n providerUrl: provider.url,\n providerDriver: provider.driver,\n dialect,\n entry: this.fs.join(rootDir, entry.server),\n rootDir,\n command: options.command,\n });\n\n const flags = options.commandFlags ? ` ${options.commandFlags}` : \"\";\n await this.utils.exec(\n `drizzle-kit ${options.command} --config=${drizzleConfigJsPath}${flags}`,\n {\n env: {\n ALEPHA_CLI_IMPORT: \"true\",\n NODE_OPTIONS: [process.env.NODE_OPTIONS, \"--import tsx\"]\n .filter(Boolean)\n .join(\" \"),\n },\n },\n );\n\n // Post-process generated SQL: strip explicit \"public\". schema qualifiers\n // from FK REFERENCES so migration files stay truly schema-free.\n // search_path handles resolution at runtime.\n if (options.command === \"generate\" && dialect === \"postgresql\") {\n await this.stripPublicSchemaFromMigrations(\n this.fs.join(rootDir, \"migrations\", providerName),\n );\n }\n }\n }\n\n /**\n * Remove `\"public\".` schema qualifiers from FK REFERENCES in SQL migration files.\n *\n * drizzle-kit generates `REFERENCES \"public\".\"table\"(...)` even for schema-free\n * models. This breaks when deploying to a non-public schema via search_path.\n */\n protected async stripPublicSchemaFromMigrations(\n migrationsDir: string,\n ): Promise<void> {\n const files = await this.fs.ls(migrationsDir).catch(() => []);\n\n for (const file of files) {\n if (!file.endsWith(\".sql\")) continue;\n\n const filePath = this.fs.join(migrationsDir, file);\n const content = await this.fs.readFile(filePath);\n const sql = content.toString(\"utf-8\");\n const cleaned = sql.replaceAll('\"public\".', \"\");\n\n if (cleaned !== sql) {\n await this.fs.writeFile(filePath, cleaned);\n this.log.debug(`Stripped \"public\". qualifiers from ${file}`);\n }\n }\n }\n\n /**\n * Prepare Drizzle configuration files for a database provider.\n */\n public async prepareDrizzleConfig(options: {\n kit: any;\n provider: DatabaseProvider;\n providerName: string;\n providerUrl: string;\n providerDriver: string;\n dialect: string;\n entry: string;\n rootDir: string;\n command?: string;\n }): Promise<string> {\n // For migration generation, use schema-free models so the SQL output\n // doesn't contain hardcoded schema qualifiers (e.g. \"myschema\".\"users\").\n // The schema is applied at runtime via search_path.\n const withoutSchema = options.command === \"generate\";\n const models = withoutSchema\n ? Object.keys(options.kit.getModelsWithoutSchema(options.provider))\n : Object.keys(options.kit.getModels(options.provider));\n const entitiesJs = this.generateEntitiesJs(\n options.entry,\n options.providerName,\n models,\n withoutSchema,\n );\n\n const entitiesJsPath = await this.utils.writeConfigFile(\n \"entities.js\",\n entitiesJs,\n options.rootDir,\n );\n\n const config: Record<string, any> = {\n schema: entitiesJsPath,\n out: `./migrations/${options.providerName}`,\n dialect: options.dialect,\n dbCredentials: {\n url: options.providerUrl,\n },\n };\n\n // Use schema-specific migration table so multiple schemas sharing\n // the same database each track their own migration history.\n if (options.dialect === \"postgresql\") {\n config.migrations = {\n table: options.provider.migrationsTable,\n };\n }\n\n // Schema filter is only needed for push/studio (introspection).\n // For generate, models are already schema-free.\n if (options.provider.schema && !withoutSchema) {\n config.schemaFilter = options.provider.schema;\n }\n\n if (options.providerDriver === \"d1\") {\n config.driver = \"d1-http\";\n }\n\n if (options.providerDriver === \"pglite\") {\n config.driver = \"pglite\";\n }\n\n if (options.dialect === \"sqlite\") {\n if (options.providerDriver === \"d1\") {\n // For D1, we need to fill D1 bindings in a way that drizzle-kit can use it, since D1 doesn't use a traditional connection URL\n } else {\n let url = options.providerUrl;\n url = url.replace(\"sqlite://\", \"\").replace(\"file://\", \"\");\n url = this.fs.join(options.rootDir, url);\n\n config.dbCredentials = {\n url,\n };\n }\n }\n\n const drizzleConfigJs = `export default ${JSON.stringify(config, null, 2)}`;\n\n return await this.utils.writeConfigFile(\n \"drizzle.config.js\",\n drizzleConfigJs,\n options.rootDir,\n );\n }\n\n // ===========================================\n // Drizzle ORM & Kit Utilities\n // ===========================================\n\n /**\n * Generate JavaScript code for Drizzle entities export.\n *\n * When `withoutSchema` is true, uses `getModelsWithoutSchema()` to produce\n * schema-free models for migration generation.\n */\n public generateEntitiesJs(\n entry: string,\n provider: string,\n models: string[] = [],\n withoutSchema = false,\n ): string {\n const getModelsCall = withoutSchema\n ? \"kit.getModelsWithoutSchema(provider)\"\n : \"kit.getModels(provider)\";\n\n return `\nimport \"${entry}\";\nimport { DrizzleKitProvider, Repository } from \"alepha/orm\";\n\nconst alepha = globalThis.__alepha;\nconst kit = alepha.inject(DrizzleKitProvider);\nconst provider = alepha.services(Repository).find((it) => it.provider.name === \"${provider}\").provider;\nconst models = ${getModelsCall};\n\n${models.map((it: string) => `export const ${it} = models[\"${it}\"];`).join(\"\\n\")}\n\n`.trim();\n }\n}\n","import { join } from \"node:path\";\nimport { __alephaRef, $inject, type Alepha, AlephaError } from \"alepha\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { ViteUtils } from \"../services/ViteUtils.ts\";\nimport type { AppEntry } from \"./AppEntryProvider.ts\";\n\nexport interface DevServerOptions {\n /**\n * Root directory of the project.\n */\n root: string;\n\n /**\n * Path to the server entry file.\n */\n entry: AppEntry;\n\n /**\n * Disable Vite React plugin.\n */\n noViteReactPlugin?: boolean;\n}\n\n/**\n * Hook called after Alepha is loaded during dev server init/reload.\n */\nexport type OnAlephaLoadedHook = (\n alepha: Alepha,\n server: ViteDevServer,\n) => Promise<void>;\n\n/**\n * Vite development server with Alepha integration.\n *\n * Architecture:\n * - Vite owns the HTTP server\n * - Alepha handles requests via Vite plugin middleware\n * - Request flow: Vite built-in (HMR, assets) → Alepha routes\n *\n * HMR Strategy:\n * - Browser-only changes (CSS, client components) → Vite HMR (React Fast Refresh)\n * - Server-only changes → Reload Alepha → Full browser reload\n * - Shared changes → Reload Alepha → Let HMR propagate\n */\nexport class ViteDevServerProvider {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly colors = $inject(ConsoleColorProvider);\n protected readonly viteUtils = $inject(ViteUtils);\n\n protected server!: ViteDevServer;\n protected options!: DevServerOptions;\n public alepha: Alepha | null = null;\n protected hasError = false;\n protected currentError: Error | null = null;\n protected changedFiles = new Set<string>();\n protected waitingForRetry = false;\n protected reloadDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n protected isReloading = false;\n protected needsBrowserReload = false;\n protected currentReloadPromise: Promise<void> | null = null;\n protected extraVitePlugins: Plugin[] = [];\n protected alephaLoadedHooks: OnAlephaLoadedHook[] = [];\n\n /**\n * Register an additional Vite plugin.\n * Must be called before init().\n */\n public addVitePlugin(plugin: Plugin): void {\n this.extraVitePlugins.push(plugin);\n }\n\n /**\n * Register a hook called after Alepha is loaded/reloaded.\n */\n public onAlephaLoaded(hook: OnAlephaLoadedHook): void {\n this.alephaLoadedHooks.push(hook);\n }\n\n /**\n * Trigger a full Alepha reload programmatically.\n */\n public reload(): void {\n this.hasError = true;\n this.needsBrowserReload = true;\n this.changedFiles.add(\"__manual_reload__\");\n this.scheduleReload();\n }\n\n /**\n * Initialize the dev server and load Alepha.\n */\n public async init(options: DevServerOptions): Promise<Alepha> {\n this.options = options;\n await this.createServer();\n\n try {\n return await this.loadAlepha(true);\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n return await this.waitForSuccessfulLoad();\n }\n }\n\n /**\n * Start the Alepha server and begin listening.\n */\n public async start(): Promise<void> {\n try {\n await this.alepha?.start();\n await this.listen();\n\n const port = this.server.config.server.port ?? 5173;\n const url = `http://localhost:${port}/`;\n const log = this.alepha?.log ?? this.log;\n log.info(`Listening on ${this.colors.set(\"CYAN\", url)}`);\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n this.alepha = await this.waitForSuccessfulLoad();\n await this.alepha.start();\n await this.listen();\n }\n }\n\n /**\n * Check if project uses React.\n */\n public hasReact(): boolean {\n try {\n this.alepha?.inject(\"ReactServerProvider\");\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Create the Vite server with Alepha plugin.\n */\n protected async createServer(): Promise<void> {\n const { createServer, resolveConfig } = await this.viteUtils.importVite();\n const viteReact = await this.viteUtils.importViteReact();\n\n const plugins: Plugin[] = [];\n if (viteReact && !this.options.noViteReactPlugin) plugins.push(viteReact());\n plugins.push(this.viteUtils.createTsconfigPathsPlugin());\n plugins.push(this.viteUtils.createSsrPreloadPlugin());\n plugins.push(...this.extraVitePlugins);\n plugins.push(this.createAlephaPlugin());\n\n // DEFAULT PORT\n // Dev: 5173\n // Prod: 3000\n\n let port: number;\n if (process.env.SERVER_PORT) {\n port = Number(process.env.SERVER_PORT);\n } else {\n const config = await resolveConfig({}, \"serve\", \"development\");\n port = config.server?.port ? Number(config.server.port) : 5173;\n }\n\n this.server = await createServer({\n root: this.options.root,\n plugins,\n appType: \"custom\",\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n server: {\n port,\n },\n optimizeDeps: {\n entries: [\n ...(this.options.entry.browser ? [this.options.entry.browser] : []),\n ],\n },\n });\n\n this.patchServerRestartForEnvReload();\n }\n\n /**\n * Intercept Vite's server.restart() to handle .env file changes.\n * Vite calls restart() when .env files change.\n */\n protected patchServerRestartForEnvReload(): void {\n this.server.restart = async () => {\n if (this.waitingForRetry || this.isReloading) return;\n\n this.isReloading = true;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Reloading ...\"));\n console.log();\n\n try {\n this.hasError = true; // Force full invalidation for env changes\n await this.loadAlepha(false);\n await this.alepha?.start();\n\n this.currentError = null;\n this.sendBrowserReload();\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Reload failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n } finally {\n this.isReloading = false;\n }\n };\n }\n\n /**\n * Start listening for connections.\n */\n protected async listen(): Promise<void> {\n await this.server.listen();\n }\n\n /**\n * Vite plugin that integrates Alepha.\n */\n protected createAlephaPlugin(): Plugin {\n return {\n name: \"alepha\",\n\n configureServer: (server) => {\n // Re-send error overlay when a new browser connects (e.g. page refresh during error state)\n server.hot.on(\"connection\", () => {\n if (this.currentError) {\n setTimeout(() => this.sendErrorOverlay(this.currentError!), 50);\n }\n });\n\n // Readiness endpoint: responds only when Alepha is fully loaded\n server.middlewares.use(async (req, res, next) => {\n if (req.url !== \"/__alepha/ready\") {\n next();\n return;\n }\n\n if (this.currentReloadPromise) {\n await this.currentReloadPromise;\n }\n\n if (this.alepha?.isReady()) {\n res.writeHead(200, { \"content-type\": \"text/plain\" });\n res.end(\"ok\");\n } else {\n res.writeHead(503, { \"content-type\": \"text/plain\" });\n res.end(\"not ready\");\n }\n });\n\n // Return function to run AFTER Vite's built-in middleware\n return () => {\n server.middlewares.use(async (req, res, next) => {\n // Skip Vite internal routes\n const url = req.url || \"/\";\n if (url.startsWith(\"/@\") || url.startsWith(\"/__vite\")) {\n next();\n return;\n }\n\n // Wait for in-progress reload to complete before serving\n if (this.currentReloadPromise) {\n await this.currentReloadPromise;\n }\n\n // In error state, serve a minimal HTML shell so the browser\n // can connect to Vite's HMR and display the error overlay\n if (this.hasError && !this.alepha) {\n if (req.headers.accept?.includes(\"text/html\")) {\n res.writeHead(200, { \"content-type\": \"text/html\" });\n res.end(\n '<!DOCTYPE html><html><head><script type=\"module\" src=\"/@vite/client\"></script></head><body></body></html>',\n );\n return;\n }\n next();\n return;\n }\n\n // Emit to Alepha's request handler\n try {\n await this.alepha?.events.emit(\"node:request\", { req, res });\n } catch (err) {\n this.log.error(\"Request handler error\", err);\n if (!res.headersSent) {\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"Internal Server Error\");\n }\n return;\n }\n\n // If Alepha didn't handle it, pass to next (404 handled by Vite)\n if (!res.headersSent && !res.writableEnded) {\n next();\n }\n });\n };\n },\n\n handleHotUpdate: async (ctx) => {\n // Ignore IDE files\n if (/[/\\\\]\\.idea[/\\\\]/.test(ctx.file)) return [];\n\n // Skip when waiting for startup retry\n if (this.waitingForRetry) return [];\n\n const firstModule = ctx.modules[0] as\n | { _ssrModule?: unknown; _clientModule?: unknown }\n | undefined;\n const isBrowserOnly = firstModule && !firstModule._ssrModule;\n\n // Browser-only: let Vite HMR handle it (React Fast Refresh)\n if (isBrowserOnly) return;\n\n // Queue Alepha reload for server-side invalidation\n this.changedFiles.add(ctx.file);\n\n // React components (.tsx/.jsx): reload Alepha BEFORE letting\n // Vite HMR reach the browser, to prevent 503 errors from\n // components that fetch data on mount during server reload.\n if (/\\.(tsx|jsx)$/.test(ctx.file)) {\n if (this.reloadDebounceTimer) {\n clearTimeout(this.reloadDebounceTimer);\n this.reloadDebounceTimer = null;\n }\n await this.performReload();\n return;\n }\n\n // Pure server files: need full browser reload after Alepha restart\n this.needsBrowserReload = true;\n this.scheduleReload();\n return [];\n },\n };\n }\n\n /**\n * Send full browser reload via Vite's HMR.\n * Uses a custom event so the client can poll for readiness before reloading.\n */\n protected sendBrowserReload(): void {\n this.server.hot.send(\"alepha:reload\", {});\n }\n\n /**\n * Send error to Vite's native error overlay.\n */\n protected sendErrorOverlay(err: Error): void {\n this.fixStacktrace(err);\n this.server.hot.send({\n type: \"error\",\n err: {\n message: err.message,\n stack: err.stack ?? \"\",\n plugin: \"alepha\",\n id: this.options.entry.server,\n },\n });\n }\n\n /**\n * Schedule a debounced reload.\n * Batches rapid file changes into a single reload operation.\n */\n protected scheduleReload(): void {\n // Clear any pending reload\n if (this.reloadDebounceTimer) {\n clearTimeout(this.reloadDebounceTimer);\n }\n\n // If already reloading, the pending changes will be picked up\n // when the current reload checks changedFiles\n if (this.isReloading) {\n return;\n }\n\n this.reloadDebounceTimer = setTimeout(() => {\n this.reloadDebounceTimer = null;\n this.performReload();\n }, 100);\n }\n\n /**\n * Perform the actual reload.\n * Returns a promise that callers can await to know when reload is done.\n * If a reload is already in progress, returns that promise.\n */\n protected performReload(): Promise<void> {\n if (this.changedFiles.size === 0) {\n return this.currentReloadPromise ?? Promise.resolve();\n }\n\n if (this.isReloading) {\n return this.currentReloadPromise ?? Promise.resolve();\n }\n\n this.currentReloadPromise = this.executeReload();\n return this.currentReloadPromise;\n }\n\n /**\n * Execute the reload work.\n */\n protected async executeReload(): Promise<void> {\n this.isReloading = true;\n\n // Snapshot files to process and clear immediately\n // New files arriving during reload will go to fresh set\n const filesToInvalidate = new Set(this.changedFiles);\n const sendReload = this.needsBrowserReload;\n const wasInError = this.hasError;\n this.changedFiles.clear();\n this.needsBrowserReload = false;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Reloading...\"));\n console.log();\n\n try {\n await this.loadAlepha(false, filesToInvalidate);\n await this.alepha?.start();\n\n this.currentError = null;\n if (sendReload || wasInError) {\n this.sendBrowserReload();\n }\n } catch (err) {\n this.hasError = true;\n this.currentError = err instanceof Error ? err : new Error(String(err));\n this.logError(\"Reload failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n } finally {\n this.isReloading = false;\n this.currentReloadPromise = null;\n\n // If more files changed during reload, schedule another\n if (this.changedFiles.size > 0) {\n this.scheduleReload();\n }\n }\n }\n\n /**\n * Load or reload the Alepha instance.\n */\n protected async loadAlepha(\n isInitialLoad = false,\n filesToInvalidate?: Set<string>,\n ): Promise<Alepha> {\n await this.destroyAlepha();\n this.clearAlephaRefs();\n\n if (isInitialLoad || this.hasError) {\n this.server.moduleGraph.invalidateAll();\n } else {\n this.invalidateModulesWithImporters(filesToInvalidate ?? new Set());\n }\n\n // Snapshot and restore process.env to isolate each reload\n const envSnapshot = { ...process.env };\n await this.setupEnvironment();\n\n try {\n await this.server.ssrLoadModule(this.options.entry.server, {\n fixStacktrace: true,\n });\n } catch (err) {\n this.hasError = true;\n process.env = envSnapshot;\n throw err;\n }\n\n const alepha = this.getLoadedAlepha();\n\n // Expose Vite server to Alepha for Logger SSR stack trace fixing\n alepha.store.set(\"alepha.vite.server\" as any, this.server);\n\n for (const hook of this.alephaLoadedHooks) {\n await hook(alepha, this.server);\n }\n\n this.alepha = alepha;\n await this.setupAlepha();\n\n this.hasError = false;\n process.env = envSnapshot;\n\n return alepha;\n }\n\n /**\n * Setup Alepha instance with dev-specific configuration.\n */\n protected async setupAlepha(): Promise<void> {\n if (!this.alepha || !this.hasReact()) {\n return;\n }\n\n const devHead = await this.generateDevHead();\n const favicon = await this.detectFavicon(join(this.options.root, \"public\"));\n this.alepha.store.set(\"alepha.react.ssr.manifest\", { devHead, favicon });\n }\n\n /**\n * Detect a favicon file in the given directory.\n * Returns \"mimeType:/path\" if found, undefined otherwise.\n */\n protected async detectFavicon(\n publicDir: string,\n ): Promise<string | undefined> {\n const candidates: [string, string][] = [\n [\"favicon.svg\", \"image/svg+xml\"],\n [\"favicon.png\", \"image/png\"],\n [\"favicon.ico\", \"image/x-icon\"],\n ];\n for (const [file, mime] of candidates) {\n if (await this.fs.exists(join(publicDir, file))) {\n return `${mime}:/${file}`;\n }\n }\n return undefined;\n }\n\n /**\n * Generate dev head content for SSR.\n *\n * IMPORTANT: We call transformIndexHtml() on an EMPTY <head> (no script/link\n * tags) to collect plugin-injected preambles — specifically the React Fast\n * Refresh runtime from @vitejs/plugin-react. We then manually append our\n * own browser entry and stylesheet tags.\n *\n * Why not include <script>/<link> tags in the HTML passed to transformIndexHtml?\n * Because Vite would pre-transform the referenced browser entry module, which\n * walks the entire client module graph and triggers dep discovery. This creates\n * a race condition with Vite's background dep scanner: both find the same deps,\n * but the scanner commits a second optimization pass that replaces the first,\n * causing \"504 Outdated Optimize Dep\" errors on cold start.\n *\n * By passing empty HTML, we get the preamble without triggering the module\n * graph walk, leaving the scanner as the single dep discovery mechanism.\n */\n protected async generateDevHead(): Promise<string> {\n const { browser, style } = this.options.entry;\n\n // Get plugin preambles (React Fast Refresh, etc.) without triggering\n // client module graph walk — see JSDoc above for why this matters.\n const emptyHtml = \"<!DOCTYPE html><html><head></head><body></body></html>\";\n const transformed = await this.server.transformIndexHtml(\"/\", emptyHtml);\n const headMatch = transformed.match(/<head>([\\s\\S]*?)<\\/head>/i);\n const preamble = headMatch?.[1]?.trim() ?? \"\";\n\n const tags: string[] = [];\n if (preamble) {\n tags.push(preamble);\n }\n\n // Reload handler: polls /__alepha/ready before reloading to avoid\n // hitting the server while it's still restarting.\n tags.push(`<script type=\"module\">\nif (import.meta.hot) {\n import.meta.hot.on(\"alepha:reload\", async () => {\n for (let i = 0; i < 50; i++) {\n try {\n const res = await fetch(\"/__alepha/ready\");\n if (res.ok) { window.location.reload(); return; }\n } catch {}\n await new Promise(r => setTimeout(r, 200));\n }\n window.location.reload();\n });\n}\n</script>`);\n\n if (style) {\n tags.push(`<link rel=\"stylesheet\" href=\"/${style}\">`);\n }\n if (browser) {\n tags.push(`<script type=\"module\" src=\"/${browser}\"></script>`);\n }\n\n return tags.join(\"\\n\");\n }\n\n /**\n * Setup environment variables for dev mode.\n */\n protected async setupEnvironment(): Promise<void> {\n const { loadEnv } = await this.viteUtils.importVite();\n\n process.env.VITE_ALEPHA_DEV = \"true\";\n process.env.NODE_ENV ??= \"development\";\n\n const mode = process.env.NODE_ENV;\n const env = loadEnv(mode, this.options.root, \"\");\n\n // Merge into process.env (only set if not already defined)\n for (const [key, value] of Object.entries(env)) {\n process.env[key] ??= value;\n }\n\n const port = this.server.config.server.port ?? 3000;\n\n process.env.SERVER_PORT ??= `${port}`;\n }\n\n /**\n * Invalidate modules and all their importers.\n */\n protected invalidateModulesWithImporters(changedFiles: Set<string>): void {\n const graph = this.server.moduleGraph;\n const invalidated = new Set<string>();\n const queue: string[] = [...changedFiles];\n\n while (queue.length > 0) {\n const file = queue.pop()!;\n if (invalidated.has(file)) continue;\n\n const mod = this.server.moduleGraph.getModuleById(file);\n if (!mod) continue;\n\n graph.invalidateModule(mod);\n invalidated.add(file);\n\n for (const importer of mod.importers) {\n if (importer.id && !invalidated.has(importer.id)) {\n queue.push(importer.id);\n }\n }\n }\n\n // Always invalidate entry module\n const entryPath = this.options.entry.server;\n const absoluteEntryPath = join(this.options.root, entryPath);\n const entryMod =\n graph.getModuleById(absoluteEntryPath) ??\n graph.getModuleById(entryPath) ??\n graph.getModuleById(`/${entryPath}`);\n if (entryMod) {\n graph.invalidateModule(entryMod);\n }\n }\n\n /**\n * Wait for file changes and retry loading until successful.\n */\n protected waitForSuccessfulLoad(): Promise<Alepha> {\n this.waitingForRetry = true;\n\n return new Promise((resolve) => {\n const onFileChange = async (file: string) => {\n if (/[/\\\\]\\.idea[/\\\\]/.test(file)) return;\n\n console.log();\n console.log(this.colors.set(\"CYAN\", \" ⟳ Retrying...\"));\n\n const filesToInvalidate = new Set([file]);\n\n try {\n const alepha = await this.loadAlepha(false, filesToInvalidate);\n this.waitingForRetry = false;\n this.currentError = null;\n this.server.watcher.off(\"change\", onFileChange);\n this.server.watcher.off(\"add\", onFileChange);\n this.sendBrowserReload();\n resolve(alepha);\n } catch (err) {\n this.hasError = true;\n this.currentError =\n err instanceof Error ? err : new Error(String(err));\n this.logError(\"Startup failed\", err);\n this.alepha = null;\n this.sendErrorOverlay(this.currentError);\n }\n };\n\n this.server.watcher.on(\"change\", onFileChange);\n this.server.watcher.on(\"add\", onFileChange);\n });\n }\n\n /**\n * Clear global Alepha references before reload.\n */\n protected clearAlephaRefs(): void {\n __alephaRef.alepha = undefined;\n __alephaRef.service = undefined;\n __alephaRef.parent = undefined;\n (globalThis as any).__alepha = undefined;\n }\n\n /**\n * Destroy the current Alepha instance.\n */\n protected async destroyAlepha(): Promise<void> {\n if (this.alepha) {\n await this.alepha\n .destroy()\n .catch((err) => this.log.warn(\"Error destroying Alepha\", err));\n this.alepha = null;\n }\n }\n\n /**\n * Get the loaded Alepha instance from globalThis.\n */\n protected getLoadedAlepha(): Alepha {\n const alepha: Alepha = (globalThis as any).__alepha;\n if (!alepha) {\n throw new AlephaError(\n \"Alepha instance not found after loading entry module\",\n );\n }\n return alepha;\n }\n\n /**\n * Fix stack trace using Vite's SSR stack trace fixer.\n */\n protected fixStacktrace(error: Error): void {\n this.server.ssrFixStacktrace(error);\n }\n\n /**\n * Log a formatted error with stack trace.\n */\n protected logError(title: string, err: unknown): void {\n const c = this.colors;\n\n console.log();\n console.log(c.set(\"RED\", ` ✗ ${title}`));\n this.logErrorWithCause(err);\n console.log();\n console.log(c.set(\"GREY_DARK\", \" Waiting for file changes to retry...\"));\n console.log();\n }\n\n /**\n * Log error message and stack, recursively logging cause if present.\n */\n protected logErrorWithCause(err: unknown, depth = 0): void {\n const error = err instanceof Error ? err : new Error(String(err));\n const indent = ` ${\" \".repeat(depth)}`;\n\n this.fixStacktrace(error);\n\n const name = error.name || \"Error\";\n const message = error.message || \"Unknown error\";\n const stackLines = error.stack?.split(\"\\n\").slice(1);\n\n console.log();\n if (depth > 0) {\n console.log(this.colors.set(\"GREY_DARK\", `${indent}Caused by:`));\n }\n console.log(this.colors.set(\"WHITE_BOLD\", `${indent + name}: ${message}`));\n if (stackLines?.length) {\n console.log();\n for (const line of stackLines) {\n console.log(`${indent}${this.colors.set(\"GREY_DARK\", line)}`);\n }\n }\n\n if (error.cause) {\n this.logErrorWithCause(error.cause, depth + 1);\n }\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { $inject, $state, Alepha, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { devOptions } from \"../atoms/devOptions.ts\";\nimport { AppEntryProvider } from \"../providers/AppEntryProvider.ts\";\nimport { ViteDevServerProvider } from \"../providers/ViteDevServerProvider.ts\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class DevCommand {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n protected readonly alepha = $inject(Alepha);\n protected readonly viteDevServer = $inject(ViteDevServerProvider);\n protected readonly boot = $inject(AppEntryProvider);\n protected readonly options = $state(devOptions);\n\n /**\n * Will run the project in watch mode.\n *\n * When run from a workspace root (with apps/ directory), spawns all apps in parallel.\n * When run from an app directory, starts a single Vite dev server.\n */\n public readonly dev = $command({\n name: \"dev\",\n mode: true,\n description: \"Run the project in development mode\",\n flags: t.object({\n only: t.optional(\n t.string({\n description:\n \"Run only specific apps (comma-separated: --only api,companion)\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const apps = await this.discoverApps(root);\n\n if (apps.length > 0) {\n await this.runMultiple(root, apps, flags);\n } else {\n await this.runSingle(root);\n }\n },\n });\n\n /**\n * Discover apps in the workspace root.\n *\n * Looks for directories under apps/ that contain a package.json.\n * Supports scoped directories (e.g., apps/@passeo/api).\n * Returns empty array if not in a workspace root.\n */\n protected async discoverApps(\n root: string,\n ): Promise<Array<{ name: string; path: string }>> {\n const appsDir = join(root, \"apps\");\n\n if (!(await this.fs.exists(appsDir))) {\n return [];\n }\n\n const entries = await readdir(appsDir);\n const apps: Array<{ name: string; path: string }> = [];\n\n for (const entry of entries) {\n const appPath = join(appsDir, entry);\n const pkgPath = join(appPath, \"package.json\");\n\n if (await this.fs.exists(pkgPath)) {\n apps.push({ name: entry, path: appPath });\n continue;\n }\n\n // Check scoped directories (e.g., apps/@passeo/api)\n const entryStat = await stat(appPath).catch(() => null);\n if (entryStat?.isDirectory()) {\n const scopedEntries = await readdir(appPath);\n for (const scopedEntry of scopedEntries) {\n const scopedPath = join(appPath, scopedEntry);\n const scopedPkgPath = join(scopedPath, \"package.json\");\n\n if (await this.fs.exists(scopedPkgPath)) {\n apps.push({ name: scopedEntry, path: scopedPath });\n }\n }\n }\n }\n\n return apps;\n }\n\n /**\n * Run a single app (existing behavior).\n */\n protected async runSingle(root: string): Promise<void> {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const entry = await this.boot.getAppEntry(root);\n this.log.debug(\"Entry file found\", { entry });\n\n const options = this.options;\n\n await this.viteDevServer.init({\n root,\n entry,\n noViteReactPlugin: options.noViteReactPlugin ?? false,\n });\n\n await this.viteDevServer.start();\n }\n\n /**\n * Run multiple apps in parallel with colored prefixed output.\n */\n protected async runMultiple(\n _root: string,\n apps: Array<{ name: string; path: string }>,\n flags: Record<string, unknown>,\n ): Promise<void> {\n const only = flags.only as string | undefined;\n\n if (only) {\n const filter = only.split(\",\").map((s) => s.trim().toLowerCase());\n apps = apps.filter((app) => filter.includes(app.name.toLowerCase()));\n }\n\n if (apps.length === 0) {\n this.log.warn(\"No apps found to run\");\n return;\n }\n\n this.log.debug(\n `Starting ${apps.length} apps: ${apps.map((a) => a.name).join(\", \")}`,\n );\n\n const basePort = 5173;\n const processes = apps.map((app, i) => this.spawnApp(app, basePort + i));\n\n // Handle graceful shutdown\n const cleanup = () => {\n for (const proc of processes) {\n proc.kill(\"SIGTERM\");\n }\n };\n\n process.once(\"SIGINT\", cleanup);\n process.once(\"SIGTERM\", cleanup);\n\n // Wait for all processes (they run until killed)\n await Promise.allSettled(\n processes.map(\n (proc) =>\n new Promise<void>((resolve) => {\n proc.on(\"exit\", () => resolve());\n }),\n ),\n );\n }\n\n /**\n * Spawn a single app process with inherited stdio.\n *\n * Each child process gets APP_NAME set, so the Alepha logger\n * handles prefixing automatically.\n */\n protected spawnApp(\n app: { name: string; path: string },\n port: number,\n ): ReturnType<typeof spawn> {\n const proc = spawn(\"yarn\", [\"alepha\", \"dev\"], {\n cwd: app.path,\n stdio: \"inherit\",\n env: {\n ...process.env,\n APP_NAME: app.name.toUpperCase(),\n SERVER_PORT: String(port),\n FORCE_COLOR: \"1\",\n },\n });\n\n proc.on(\"exit\", (code) => {\n if (code !== 0 && code !== null) {\n this.log.error(`${app.name} exited with code ${code}`);\n }\n });\n\n return proc;\n }\n}\n","import { $atom, type Static, t } from \"alepha\";\n\n/**\n * Default scopes to ignore in changelog generation.\n * Commits with these scopes won't appear in release notes.\n */\nexport const DEFAULT_IGNORE = [\n \"project\",\n \"release\",\n \"starter\",\n \"example\",\n \"chore\",\n \"ci\",\n \"build\",\n \"test\",\n \"style\",\n];\n\n/**\n * Changelog configuration atom.\n *\n * Configure in `alepha.config.ts`:\n * ```ts\n * import { changelogOptions } from \"alepha/cli\";\n *\n * alepha.set(changelogOptions, {\n * ignore: [\"project\", \"release\", \"chore\", \"docs\"],\n * });\n * ```\n */\nexport const changelogOptions = $atom({\n name: \"alepha.cli.changelog.options\",\n schema: t.object({\n /**\n * Scopes to ignore (e.g., \"project\", \"release\", \"chore\").\n * Commits like `feat(chore): ...` will be excluded from changelog.\n */\n ignore: t.optional(t.array(t.string())),\n }),\n default: {\n ignore: DEFAULT_IGNORE,\n },\n});\n\nexport type ChangelogOptions = Static<typeof changelogOptions.schema>;\n","import { $logger } from \"alepha/logger\";\nimport {\n type ChangelogOptions,\n DEFAULT_IGNORE,\n} from \"../atoms/changelogOptions.ts\";\nimport type { Commit } from \"../commands/gen/changelog.ts\";\n\n/**\n * Service for parsing git commit messages into structured format.\n *\n * Only parses **conventional commits with a scope**:\n * - `feat(scope): description` → feature\n * - `fix(scope): description` → bug fix\n * - `feat(scope)!: description` → breaking change\n *\n * Commits without scope are ignored, allowing developers to commit\n * work-in-progress changes without polluting release notes:\n * - `cli: work in progress` → ignored (no type)\n * - `fix: quick patch` → ignored (no scope)\n * - `feat(cli): add command` → included\n */\nexport class GitMessageParser {\n protected readonly log = $logger();\n\n /**\n * Parse a git commit line into a structured Commit object.\n *\n * **Format:** `type(scope): description` or `type(scope)!: description`\n *\n * **Supported types:** feat, fix, docs, refactor, perf, revert\n *\n * **Breaking changes:** Use `!` before `:` (e.g., `feat(api)!: remove endpoint`)\n *\n * @returns Commit object or null if not matching/ignored\n */\n parseCommit(line: string, config: ChangelogOptions): Commit | null {\n // Extract hash and message from git log --oneline format\n const match = line.match(/^([a-f0-9]+)\\s+(.+)$/);\n if (!match) return null;\n\n const [, hash, message] = match;\n const ignore = config.ignore ?? DEFAULT_IGNORE;\n\n // Conventional commit with REQUIRED scope: type(scope): description\n // The `!` before `:` marks a breaking change\n const conventionalMatch = message.match(\n /^(feat|fix|docs|refactor|perf|revert)\\(([^)]+)\\)(!)?:\\s*(.+)$/i,\n );\n\n if (!conventionalMatch) {\n // No match - commit doesn't follow required format\n return null;\n }\n\n const [, type, scope, breakingMark, description] = conventionalMatch;\n\n // Check if scope should be ignored\n const baseScope = scope.split(\"/\")[0];\n if (ignore.includes(baseScope) || ignore.includes(scope)) {\n return null;\n }\n\n // Breaking change detection:\n // 1. Explicit `!` marker: feat(api)!: change\n // 2. Word \"breaking\" in description: feat(api): breaking change to auth\n const breaking =\n breakingMark === \"!\" || description.toLowerCase().includes(\"breaking\");\n\n return {\n hash: hash.substring(0, 8),\n type: type.toLowerCase(),\n scope,\n description: description.trim(),\n breaking,\n };\n }\n}\n","import { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { $inject, $state, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { changelogOptions } from \"../../atoms/changelogOptions.ts\";\nimport { GitMessageParser } from \"../../services/GitMessageParser.ts\";\n\nexport {\n type ChangelogOptions,\n changelogOptions,\n DEFAULT_IGNORE,\n} from \"../../atoms/changelogOptions.ts\";\nexport { GitMessageParser } from \"../../services/GitMessageParser.ts\";\n\nconst execAsync = promisify(exec);\n\n// =============================================================================\n// GIT PROVIDER\n// =============================================================================\n\n/**\n * Git provider for executing git commands.\n * Can be substituted in tests with a mock implementation.\n */\nexport class GitProvider {\n async exec(cmd: string, cwd: string): Promise<string> {\n const { stdout } = await execAsync(`git ${cmd}`, { cwd });\n return stdout;\n }\n}\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface Commit {\n hash: string;\n type: string;\n scope: string | null;\n description: string;\n breaking: boolean;\n}\n\ninterface ChangelogEntry {\n features: Commit[];\n fixes: Commit[];\n}\n\n// =============================================================================\n// CHANGELOG COMMAND\n// =============================================================================\n\n/**\n * Changelog command for generating release notes from git commits.\n *\n * Usage:\n * - `alepha gen changelog` - Show unreleased changes since latest tag to HEAD\n * - `alepha gen changelog --from=1.0.0` - Show changes from version to HEAD\n * - `alepha gen changelog --from=1.0.0 --to=1.1.0` - Show changes between two refs\n * - `alepha gen changelog | tee -a CHANGELOG.md` - Append to file\n */\nexport class ChangelogCommand {\n protected readonly log = $logger();\n protected readonly git = $inject(GitProvider);\n protected readonly parser = $inject(GitMessageParser);\n protected readonly config = $state(changelogOptions);\n\n // ---------------------------------------------------------------------------\n // FORMATTING\n // ---------------------------------------------------------------------------\n\n /**\n * Format a single commit line.\n * Example: `- **cli**: add new command (\\`abc1234\\`)`\n * Breaking changes are flagged: `- **cli**: add new command [BREAKING] (\\`abc1234\\`)`\n */\n protected formatCommit(commit: Commit): string {\n const breaking = commit.breaking ? \" [BREAKING]\" : \"\";\n return `- **${commit.scope}**: ${commit.description}${breaking} (\\`${commit.hash}\\`)`;\n }\n\n /**\n * Format the changelog entry with sections.\n */\n protected formatEntry(entry: ChangelogEntry): string {\n const sections: string[] = [];\n\n if (entry.features.length > 0) {\n sections.push(\"### Features\\n\");\n for (const commit of entry.features) {\n sections.push(this.formatCommit(commit));\n }\n sections.push(\"\");\n }\n\n if (entry.fixes.length > 0) {\n sections.push(\"### Bug Fixes\\n\");\n for (const commit of entry.fixes) {\n sections.push(this.formatCommit(commit));\n }\n sections.push(\"\");\n }\n\n return sections.join(\"\\n\");\n }\n\n // ---------------------------------------------------------------------------\n // PARSING\n // ---------------------------------------------------------------------------\n\n /**\n * Parse git log output into a changelog entry.\n */\n protected parseCommits(commitsOutput: string): ChangelogEntry {\n const entry: ChangelogEntry = {\n features: [],\n fixes: [],\n };\n\n for (const line of commitsOutput.trim().split(\"\\n\")) {\n if (!line.trim()) continue;\n\n const commit = this.parser.parseCommit(line, this.config);\n if (!commit) {\n this.log.trace(\"Skipping commit\", { line });\n continue;\n }\n\n this.log.trace(\"Parsed commit\", { commit });\n\n // Categorize commit (breaking flag is preserved on the commit itself)\n if (commit.type === \"feat\") {\n entry.features.push(commit);\n } else if (commit.type === \"fix\") {\n entry.fixes.push(commit);\n }\n }\n\n return entry;\n }\n\n /**\n * Check if entry has any public commits.\n */\n protected hasChanges(entry: ChangelogEntry): boolean {\n return entry.features.length > 0 || entry.fixes.length > 0;\n }\n\n /**\n * Get the latest version tag.\n */\n protected async getLatestTag(\n git: (cmd: string) => Promise<string>,\n ): Promise<string | null> {\n const tagsOutput = await git(\"tag --sort=-version:refname\");\n const tags = tagsOutput\n .trim()\n .split(\"\\n\")\n .filter((tag) => tag.match(/^\\d+\\.\\d+\\.\\d+$/));\n\n return tags[0] || null;\n }\n\n // ---------------------------------------------------------------------------\n // COMMAND\n // ---------------------------------------------------------------------------\n\n public readonly command = $command({\n name: \"changelog\",\n description:\n \"Generate changelog from conventional commits (outputs to stdout)\",\n flags: t.object({\n /**\n * Show changes from this ref (tag, commit, branch).\n * Defaults to the latest version tag.\n * Example: --from=1.0.0\n */\n from: t.optional(\n t.string({\n aliases: [\"f\"],\n description: \"Starting ref (default: latest tag)\",\n }),\n ),\n /**\n * Show changes up to this ref (tag, commit, branch).\n * Defaults to HEAD.\n * Example: --to=main\n */\n to: t.optional(\n t.string({\n aliases: [\"t\"],\n description: \"Ending ref (default: HEAD)\",\n }),\n ),\n }),\n handler: async ({ flags, root }) => {\n const git = (cmd: string) => this.git.exec(cmd, root);\n\n // Determine the starting point\n let fromRef: string;\n\n if (flags.from) {\n // User specified a ref\n fromRef = flags.from;\n this.log.debug(\"Using specified from ref\", { from: fromRef });\n } else {\n // Use latest tag\n const latestTag = await this.getLatestTag(git);\n if (!latestTag) {\n process.stdout.write(\"No version tags found in repository\\n\");\n return;\n }\n fromRef = latestTag;\n this.log.debug(\"Using latest tag\", { from: fromRef });\n }\n\n // Determine the ending point\n const toRef = flags.to || \"HEAD\";\n this.log.debug(\"Using to ref\", { to: toRef });\n\n // Get commits in range\n const commitsOutput = await git(`log ${fromRef}..${toRef} --oneline`);\n\n if (!commitsOutput.trim()) {\n process.stdout.write(`No changes in range ${fromRef}..${toRef}\\n`);\n return;\n }\n\n // Parse and format\n const entry = this.parseCommits(commitsOutput);\n\n if (!this.hasChanges(entry)) {\n process.stdout.write(\n `No public changes in range ${fromRef}..${toRef}\\n`,\n );\n return;\n }\n\n // Output the formatted changelog (no header - caller adds it if needed)\n process.stdout.write(this.formatEntry(entry));\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../../services/AlephaCliUtils.ts\";\n\nexport class GenEnvCommand {\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly fs = $inject(FileSystemProvider);\n\n public readonly command = $command({\n name: \"env\",\n description: \"Extract environment variables from server entry file\",\n flags: t.object({\n out: t.optional(\n t.text({\n aliases: [\"o\"],\n description: \"Output file path (e.g., .env)\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n root,\n mode: \"development\",\n });\n\n try {\n const { env } = alepha.dump();\n\n let dotEnvFile = \"\";\n for (const [key, value] of Object.entries(env)) {\n if (value.description) {\n dotEnvFile += `# ${value.description.split(\"\\n\").join(\"\\n# \")}\\n`;\n }\n if (value.required && !value.default) {\n dotEnvFile += `# (required)\\n`;\n }\n if (value.enum) {\n dotEnvFile += `# Possible values: ${value.enum.join(\", \")}\\n`;\n }\n dotEnvFile += `#${key}=${value.default || \"\"}\\n\\n`;\n }\n\n if (flags.out) {\n await this.fs.writeFile(this.fs.join(root, flags.out), dotEnvFile);\n } else {\n this.log.info(dotEnvFile);\n }\n } catch (err) {\n this.log.error(\"Failed to extract environment variables\", err);\n }\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { ServerSwaggerProvider } from \"alepha/server/swagger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { AlephaCliUtils } from \"../../services/AlephaCliUtils.ts\";\n\nexport class OpenApiCommand {\n protected readonly log = $logger();\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly fs = $inject(FileSystemProvider);\n\n public readonly command = $command({\n name: \"openapi\",\n description: \"Generate OpenAPI specification from actions\",\n flags: t.object({\n out: t.optional(\n t.text({\n aliases: [\"o\"],\n description: \"Output file path\",\n }),\n ),\n }),\n handler: async ({ root, flags }) => {\n const alepha = await this.utils.loadAlephaFromServerEntryFile({\n root,\n mode: \"development\",\n });\n\n try {\n const openapiProvider = alepha.inject(\n ServerSwaggerProvider,\n ) as ServerSwaggerProvider;\n\n await alepha.events.emit(\"configure\", alepha);\n\n let json: any = openapiProvider.json;\n\n if (!json) {\n json = openapiProvider.generateSwaggerDoc({\n info: {\n title: \"API Documentation\",\n version: \"1.0.0\",\n },\n });\n }\n\n if (!json) {\n this.log.error(\"No actions found to generate OpenAPI specification.\");\n return;\n }\n\n if (flags.out) {\n await this.fs.writeFile(\n this.fs.join(root, flags.out),\n JSON.stringify(json, null, 2),\n );\n } else {\n this.log.info(JSON.stringify(json, null, 2));\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (message.includes(\"Service not found\")) {\n this.log.error(\n \"Missing $swagger() primitive in your server configuration.\",\n );\n return;\n }\n\n this.log.error(`OpenAPI generation failed - ${message}`, err);\n }\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { ChangelogCommand } from \"./gen/changelog.ts\";\nimport { GenEnvCommand } from \"./gen/env.ts\";\nimport { OpenApiCommand } from \"./gen/openapi.ts\";\n\nexport class GenCommand {\n protected readonly changelog = $inject(ChangelogCommand);\n protected readonly openapi = $inject(OpenApiCommand);\n protected readonly genEnv = $inject(GenEnvCommand);\n\n public readonly gen = $command({\n name: \"gen\",\n description: \"Generate code, documentation, ...\",\n children: [\n this.changelog.command,\n this.openapi.command,\n this.genEnv.command,\n ],\n handler: async ({ help }) => {\n help();\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class InitCommand {\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n /**\n * Ensure the project has the necessary Alepha configuration files.\n * Add the correct dependencies to package.json and install them.\n */\n public readonly init = $command({\n name: \"init\",\n description: \"Add missing Alepha configuration files to the project\",\n args: t.optional(\n t.text({\n title: \"path\",\n trim: true,\n lowercase: true,\n }),\n ),\n flags: t.object({\n pm: t.optional(\n t.enum([\"yarn\", \"npm\", \"pnpm\", \"bun\"], {\n description: \"Package manager to use\",\n }),\n ),\n // choose which modules to scaffold\n api: t.optional(\n t.boolean({\n description: \"Include API module structure (src/api/)\",\n }),\n ),\n react: t.optional(\n t.boolean({\n aliases: [\"r\"],\n description: \"Include React dependencies and web module (src/web/)\",\n }),\n ),\n ui: t.optional(\n t.boolean({\n description:\n \"Include @alepha/ui (components, auth portal, admin portal)\",\n }),\n ),\n saas: t.optional(\n t.boolean({\n description:\n \"Include authentication, admin portal, API, UI, and React. Everything you need for a SaaS app.\",\n }),\n ),\n tailwind: t.optional(\n t.boolean({\n description: \"Include Tailwind CSS with Vite plugin. Implies --react\",\n }),\n ),\n test: t.optional(\n t.boolean({ description: \"Include Vitest and create test directory\" }),\n ),\n force: t.optional(\n t.boolean({\n aliases: [\"f\"],\n description: \"Override existing files\",\n }),\n ),\n }),\n handler: async ({ run, flags, root, args }) => {\n await this.scaffolder.init({ run, flags, root, args });\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class LintCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly lint = $command({\n name: \"lint\",\n description: \"Run linter across the codebase using Biome\",\n handler: async ({ run, root }) => {\n await this.scaffolder.ensureConfig(root, {\n biomeJson: true,\n checkWorkspace: true,\n });\n\n await this.pm.ensureDependency(root, \"@biomejs/biome\", {\n checkWorkspace: true,\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n await run(\"biome check --fix\");\n },\n });\n}\n","import { $inject, Alepha, t } from \"alepha\";\nimport { $command, CliProvider } from \"alepha/command\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { version } from \"../version.ts\";\n\nexport class RootCommand {\n protected readonly log = $logger();\n protected readonly cli = $inject(CliProvider);\n protected readonly alepha = $inject(Alepha);\n protected readonly color = $inject(ConsoleColorProvider);\n\n /**\n * Called when no command is provided\n */\n public readonly root = $command({\n root: true,\n flags: t.object({\n version: t.optional(\n t.boolean({\n description: \"Show Alepha CLI version\",\n aliases: [\"v\"],\n }),\n ),\n }),\n handler: async ({ flags }) => {\n if (flags.version) {\n this.log.info(this.color.set(\"WHITE_BOLD\", `Alepha v${version}`));\n if (this.alepha.isBun()) {\n this.log.info(this.color.set(\"GREY_DARK\", `└─ Bun v${Bun.version}`));\n } else {\n this.log.info(\n this.color.set(\"GREY_DARK\", `└─ Node ${process.version}`),\n );\n }\n return;\n }\n\n this.cli.printHelp();\n },\n });\n}\n","import { $inject, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TestCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly test = $command({\n name: \"test\",\n description: \"Run tests using Vitest\",\n flags: t.object({\n config: t.optional(\n t.string({\n description: \"Path to Vitest config file\",\n alias: \"c\",\n }),\n ),\n }),\n env: t.object({\n VITEST_ARGS: t.optional(\n t.string({\n default: \"\",\n description:\n \"Additional arguments to pass to Vitest. E.g., --coverage\",\n }),\n ),\n }),\n handler: async ({ run, root, flags, env }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n // Ensure vitest is installed before running\n await this.pm.ensureDependency(root, \"vitest\", {\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n const config = flags.config ? `--config=${flags.config}` : \"\";\n\n await run(`vitest run ${config} ${env.VITEST_ARGS}`);\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TypecheckCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n protected readonly log = $logger();\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n /**\n * Run TypeScript type checking across the codebase with no emit.\n */\n public readonly typecheck = $command({\n name: \"typecheck\",\n aliases: [\"tc\"],\n description: \"Check TypeScript types across the codebase\",\n handler: async ({ run, root }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n checkWorkspace: true,\n });\n\n await this.pm.ensureDependency(root, \"typescript\", {\n checkWorkspace: true,\n exec: (cmd, opts) => this.utils.exec(cmd, opts),\n });\n\n await run(\"tsc --noEmit\");\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"../services/PackageManagerUtils.ts\";\n\nexport class VerifyCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly pm = $inject(PackageManagerUtils);\n\n /**\n * Run a series of verification commands to ensure code quality and correctness.\n *\n * This command runs the following checks in order:\n * - Clean the project\n * - Format the code\n * - Lint the code\n * - Run tests (if Vitest is a dev dependency)\n * - Check database migrations (if a migrations directory exists)\n * - Type check the code\n * - Build the project\n * - Clean the project again\n */\n public readonly verify = $command({\n name: \"verify\",\n description: \"Verify the Alepha project\",\n handler: async ({ root, run }) => {\n await run(\"alepha clean\");\n await run(\"alepha lint\");\n\n await run(\"alepha typecheck\");\n\n const pkg = await this.pm.readPackageJson(root);\n if (pkg.devDependencies?.vitest) {\n await run(\"alepha test\");\n }\n\n if (await this.utils.exists(root, \"migrations\")) {\n await run(\"alepha db migrations check\");\n }\n\n const isExpo = await this.pm.hasExpo(root);\n if (!isExpo) {\n await run(\"alepha build\");\n }\n await run(\"alepha clean\");\n },\n });\n}\n","import { pathToFileURL } from \"node:url\";\nimport { $hook, $inject, Alepha } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\n\nexport class AlephaCliExtensionProvider {\n protected readonly alepha = $inject(Alepha);\n protected readonly fs = $inject(FileSystemProvider);\n\n protected readonly onConfigure = $hook({\n on: \"configure\",\n handler: async () => {\n const root = process.cwd();\n const extensionPath = this.fs.join(root, \"alepha.config.ts\");\n const hasExtension = await this.fs.exists(extensionPath);\n if (!hasExtension) {\n return;\n }\n\n // import (use file:// URL for Windows compatibility)\n const extensionUrl = pathToFileURL(extensionPath).href;\n const { default: Extension } = await import(extensionUrl);\n if (typeof Extension !== \"function\") {\n return;\n }\n\n this.alepha.inject(Extension, {\n args: [this.alepha],\n });\n },\n });\n}\n","import { $module } from \"alepha\";\nimport { appEntryOptions } from \"./atoms/appEntryOptions.ts\";\nimport { buildOptions } from \"./atoms/buildOptions.ts\";\nimport { devOptions } from \"./atoms/devOptions.ts\";\nimport { BuildCommand } from \"./commands/build.ts\";\nimport { CleanCommand } from \"./commands/clean.ts\";\nimport { DbCommand } from \"./commands/db.ts\";\nimport { DevCommand } from \"./commands/dev.ts\";\nimport {\n changelogOptions,\n GitMessageParser,\n GitProvider,\n} from \"./commands/gen/changelog.ts\";\nimport { GenCommand } from \"./commands/gen.ts\";\nimport { InitCommand } from \"./commands/init.ts\";\nimport { LintCommand } from \"./commands/lint.ts\";\nimport { RootCommand } from \"./commands/root.ts\";\nimport { TestCommand } from \"./commands/test.ts\";\nimport { TypecheckCommand } from \"./commands/typecheck.ts\";\nimport { VerifyCommand } from \"./commands/verify.ts\";\nimport { AlephaCliExtensionProvider } from \"./providers/AlephaCliExtensionProvider.ts\";\nimport { AppEntryProvider } from \"./providers/AppEntryProvider.ts\";\nimport { ViteBuildProvider } from \"./providers/ViteBuildProvider.ts\";\nimport { ViteDevServerProvider } from \"./providers/ViteDevServerProvider.ts\";\nimport { AlephaCliUtils } from \"./services/AlephaCliUtils.ts\";\nimport { PackageManagerUtils } from \"./services/PackageManagerUtils.ts\";\nimport { ProjectScaffolder } from \"./services/ProjectScaffolder.ts\";\nimport { ViteUtils } from \"./services/ViteUtils.ts\";\nimport { BuildAssetsTask } from \"./tasks/BuildAssetsTask.ts\";\nimport { BuildClientTask } from \"./tasks/BuildClientTask.ts\";\nimport { BuildCloudflareTask } from \"./tasks/BuildCloudflareTask.ts\";\nimport { BuildCompressTask } from \"./tasks/BuildCompressTask.ts\";\nimport { BuildDockerTask } from \"./tasks/BuildDockerTask.ts\";\nimport { BuildPrerenderTask } from \"./tasks/BuildPrerenderTask.ts\";\nimport { BuildServerTask } from \"./tasks/BuildServerTask.ts\";\nimport { BuildSitemapTask } from \"./tasks/BuildSitemapTask.ts\";\nimport { BuildStaticTask } from \"./tasks/BuildStaticTask.ts\";\nimport { BuildVercelTask } from \"./tasks/BuildVercelTask.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./atoms/appEntryOptions.ts\";\nexport * from \"./atoms/buildOptions.ts\";\nexport * from \"./atoms/changelogOptions.ts\";\nexport * from \"./atoms/devOptions.ts\";\nexport * from \"./commands/build.ts\";\nexport * from \"./commands/clean.ts\";\nexport * from \"./commands/db.ts\";\nexport * from \"./commands/dev.ts\";\nexport * from \"./commands/gen/changelog.ts\";\nexport * from \"./commands/gen/openapi.ts\";\nexport * from \"./commands/init.ts\";\nexport * from \"./commands/lint.ts\";\nexport * from \"./commands/root.ts\";\nexport * from \"./commands/test.ts\";\nexport * from \"./commands/typecheck.ts\";\nexport * from \"./commands/verify.ts\";\nexport * from \"./providers/AlephaCliExtensionProvider.ts\";\nexport * from \"./providers/AppEntryProvider.ts\";\nexport * from \"./providers/ViteBuildProvider.ts\";\nexport * from \"./providers/ViteDevServerProvider.ts\";\nexport * from \"./services/AlephaCliUtils.ts\";\nexport * from \"./services/GitMessageParser.ts\";\nexport * from \"./services/PackageManagerUtils.ts\";\nexport * from \"./services/ProjectScaffolder.ts\";\nexport * from \"./services/ViteUtils.ts\";\nexport * from \"./tasks/BuildAssetsTask.ts\";\nexport * from \"./tasks/BuildClientTask.ts\";\nexport * from \"./tasks/BuildCloudflareTask.ts\";\nexport * from \"./tasks/BuildCompressTask.ts\";\nexport * from \"./tasks/BuildDockerTask.ts\";\nexport * from \"./tasks/BuildPrerenderTask.ts\";\nexport * from \"./tasks/BuildServerTask.ts\";\nexport * from \"./tasks/BuildSitemapTask.ts\";\nexport * from \"./tasks/BuildStaticTask.ts\";\nexport * from \"./tasks/BuildTask.ts\";\nexport * from \"./tasks/BuildVercelTask.ts\";\nexport * from \"./version.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Services, providers, and build tasks — no commands.\n * Use this module when you need CLI utilities without registering commands.\n */\nexport const AlephaCliServices = $module({\n name: \"alepha.cli.services\",\n services: [\n // Services & providers\n AlephaCliUtils,\n PackageManagerUtils,\n ViteUtils,\n ProjectScaffolder,\n AppEntryProvider,\n GitMessageParser,\n GitProvider,\n ViteDevServerProvider,\n ViteBuildProvider,\n ],\n});\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Full CLI module — all services and commands.\n */\nexport const AlephaCli = $module({\n name: \"alepha.cli\",\n atoms: [appEntryOptions, buildOptions, changelogOptions, devOptions],\n services: [\n AlephaCliExtensionProvider,\n // Commands\n BuildCommand,\n CleanCommand,\n DbCommand,\n DevCommand,\n InitCommand,\n LintCommand,\n RootCommand,\n TestCommand,\n TypecheckCommand,\n VerifyCommand,\n GenCommand,\n // Build tasks\n BuildAssetsTask,\n BuildClientTask,\n BuildCloudflareTask,\n BuildCompressTask,\n BuildDockerTask,\n BuildPrerenderTask,\n BuildServerTask,\n BuildSitemapTask,\n BuildStaticTask,\n BuildVercelTask,\n ],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA,MAAa,k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