alepha 0.21.2 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/api/audits/index.browser.js.map +1 -1
- package/dist/api/audits/index.d.ts +393 -403
- package/dist/api/audits/index.d.ts.map +1 -1
- package/dist/api/audits/index.js +25 -56
- package/dist/api/audits/index.js.map +1 -1
- package/dist/api/files/index.browser.js +31 -1
- package/dist/api/files/index.browser.js.map +1 -1
- package/dist/api/files/index.d.ts +313 -208
- package/dist/api/files/index.d.ts.map +1 -1
- package/dist/api/files/index.js +152 -42
- package/dist/api/files/index.js.map +1 -1
- package/dist/api/jobs/index.browser.js +2 -2
- package/dist/api/jobs/index.browser.js.map +1 -1
- package/dist/api/jobs/index.d.ts +289 -292
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/jobs/index.js +39 -33
- package/dist/api/jobs/index.js.map +1 -1
- package/dist/api/keys/index.d.ts +211 -216
- package/dist/api/keys/index.d.ts.map +1 -1
- package/dist/api/keys/index.js.map +1 -1
- package/dist/api/notifications/index.browser.js.map +1 -1
- package/dist/api/notifications/index.d.ts +188 -195
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/notifications/index.js.map +1 -1
- package/dist/api/oauth/index.d.ts +71 -76
- package/dist/api/oauth/index.d.ts.map +1 -1
- package/dist/api/oauth/index.js.map +1 -1
- package/dist/api/organizations/index.browser.js.map +1 -1
- package/dist/api/organizations/index.d.ts +104 -109
- package/dist/api/organizations/index.d.ts.map +1 -1
- package/dist/api/organizations/index.js.map +1 -1
- package/dist/api/parameters/index.browser.js +43 -16
- package/dist/api/parameters/index.browser.js.map +1 -1
- package/dist/api/parameters/index.d.ts +488 -344
- package/dist/api/parameters/index.d.ts.map +1 -1
- package/dist/api/parameters/index.js +175 -35
- package/dist/api/parameters/index.js.map +1 -1
- package/dist/api/payments/index.d.ts +396 -402
- package/dist/api/payments/index.d.ts.map +1 -1
- package/dist/api/payments/index.js.map +1 -1
- package/dist/api/subscriptions/index.d.ts +644 -652
- package/dist/api/subscriptions/index.d.ts.map +1 -1
- package/dist/api/subscriptions/index.js +1 -1
- package/dist/api/subscriptions/index.js.map +1 -1
- package/dist/api/users/index.browser.js +7 -0
- package/dist/api/users/index.browser.js.map +1 -1
- package/dist/api/users/index.d.ts +1073 -1006
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +283 -61
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.browser.js.map +1 -1
- package/dist/api/verifications/index.d.ts +134 -140
- package/dist/api/verifications/index.d.ts.map +1 -1
- package/dist/api/verifications/index.js.map +1 -1
- package/dist/background/index.d.ts +95 -0
- package/dist/background/index.d.ts.map +1 -0
- package/dist/background/index.js +121 -0
- package/dist/background/index.js.map +1 -0
- package/dist/background/index.workerd.js +110 -0
- package/dist/background/index.workerd.js.map +1 -0
- package/dist/batch/index.d.ts +5 -7
- package/dist/batch/index.d.ts.map +1 -1
- package/dist/batch/index.js.map +1 -1
- package/dist/bin/index.js.map +1 -1
- package/dist/bucket/index.d.ts +76 -54
- package/dist/bucket/index.d.ts.map +1 -1
- package/dist/bucket/index.js +58 -11
- package/dist/bucket/index.js.map +1 -1
- package/dist/bucket/index.workerd.js +200 -5
- package/dist/bucket/index.workerd.js.map +1 -1
- package/dist/cache/core/index.d.ts +7 -10
- package/dist/cache/core/index.d.ts.map +1 -1
- package/dist/cache/core/index.js.map +1 -1
- package/dist/cache/core/index.workerd.js.map +1 -1
- package/dist/cache/database/index.d.ts +22 -26
- package/dist/cache/database/index.d.ts.map +1 -1
- package/dist/cache/database/index.js.map +1 -1
- package/dist/cache/redis/index.d.ts +4 -7
- package/dist/cache/redis/index.d.ts.map +1 -1
- package/dist/cache/redis/index.js.map +1 -1
- package/dist/captcha/index.d.ts +3 -6
- package/dist/captcha/index.d.ts.map +1 -1
- package/dist/captcha/index.js.map +1 -1
- package/dist/cli/config/index.d.ts.map +1 -1
- package/dist/cli/config/index.js.map +1 -1
- package/dist/cli/core/index.d.ts +417 -214
- package/dist/cli/core/index.d.ts.map +1 -1
- package/dist/cli/core/index.js +325 -563
- package/dist/cli/core/index.js.map +1 -1
- package/dist/cli/devtools/index.d.ts +3 -5
- package/dist/cli/devtools/index.d.ts.map +1 -1
- package/dist/cli/devtools/index.js.map +1 -1
- package/dist/cli/i18n/index.d.ts +8 -12
- package/dist/cli/i18n/index.d.ts.map +1 -1
- package/dist/cli/i18n/index.js.map +1 -1
- package/dist/cli/platform/index.d.ts +126 -1342
- package/dist/cli/platform/index.d.ts.map +1 -1
- package/dist/cli/platform/index.js +136 -2374
- package/dist/cli/platform/index.js.map +1 -1
- package/dist/cli/platform-lib/index.d.ts +1446 -0
- package/dist/cli/platform-lib/index.d.ts.map +1 -0
- package/dist/cli/platform-lib/index.js +2597 -0
- package/dist/cli/platform-lib/index.js.map +1 -0
- package/dist/cli/vendor/index.d.ts +17 -21
- package/dist/cli/vendor/index.d.ts.map +1 -1
- package/dist/cli/vendor/index.js.map +1 -1
- package/dist/command/index.d.ts +21 -20
- package/dist/command/index.d.ts.map +1 -1
- package/dist/command/index.js +39 -10
- package/dist/command/index.js.map +1 -1
- package/dist/{containers → container}/core/index.d.ts +13 -15
- package/dist/container/core/index.d.ts.map +1 -0
- package/dist/{containers → container}/core/index.js +23 -14
- package/dist/container/core/index.js.map +1 -0
- package/dist/{containers → container}/core/index.workerd.js +37 -22
- package/dist/container/core/index.workerd.js.map +1 -0
- package/dist/core/index.browser.js +27 -1
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +48 -24
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +27 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +27 -1
- package/dist/core/index.native.js.map +1 -1
- package/dist/core/index.workerd.js +27 -1
- package/dist/core/index.workerd.js.map +1 -1
- package/dist/crypto/index.browser.js.map +1 -1
- package/dist/crypto/index.d.ts +5 -8
- package/dist/crypto/index.d.ts.map +1 -1
- package/dist/crypto/index.js.map +1 -1
- package/dist/datetime/index.d.ts +3 -4
- package/dist/datetime/index.d.ts.map +1 -1
- package/dist/datetime/index.js.map +1 -1
- package/dist/email/brevo/index.d.ts +2 -4
- package/dist/email/brevo/index.d.ts.map +1 -1
- package/dist/email/brevo/index.js.map +1 -1
- package/dist/email/cloudflare/index.d.ts +20 -7
- package/dist/email/cloudflare/index.d.ts.map +1 -1
- package/dist/email/cloudflare/index.js +46 -9
- package/dist/email/cloudflare/index.js.map +1 -1
- package/dist/email/core/index.d.ts +6 -9
- package/dist/email/core/index.d.ts.map +1 -1
- package/dist/email/core/index.js.map +1 -1
- package/dist/email/core/index.workerd.js.map +1 -1
- package/dist/email/smtp/index.d.ts +10 -13
- package/dist/email/smtp/index.d.ts.map +1 -1
- package/dist/email/smtp/index.js +107 -32
- package/dist/email/smtp/index.js.map +1 -1
- package/dist/fake/index.d.ts +1 -2
- package/dist/fake/index.d.ts.map +1 -1
- package/dist/fake/index.js.map +1 -1
- package/dist/lock/core/index.d.ts +9 -14
- package/dist/lock/core/index.d.ts.map +1 -1
- package/dist/lock/core/index.js.map +1 -1
- package/dist/lock/redis/index.d.ts +2 -4
- package/dist/lock/redis/index.d.ts.map +1 -1
- package/dist/lock/redis/index.js.map +1 -1
- package/dist/logger/index.d.ts +105 -76
- package/dist/logger/index.d.ts.map +1 -1
- package/dist/logger/index.js +196 -174
- package/dist/logger/index.js.map +1 -1
- package/dist/mcp/index.d.ts +16 -20
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/orm/core/index.browser.js.map +1 -1
- package/dist/orm/core/index.bun.js +19 -1
- package/dist/orm/core/index.bun.js.map +1 -1
- package/dist/orm/core/index.d.ts +76 -62
- package/dist/orm/core/index.d.ts.map +1 -1
- package/dist/orm/core/index.js +20 -2
- package/dist/orm/core/index.js.map +1 -1
- package/dist/orm/postgres/index.bun.js.map +1 -1
- package/dist/orm/postgres/index.d.ts +28 -20
- package/dist/orm/postgres/index.d.ts.map +1 -1
- package/dist/orm/postgres/index.js.map +1 -1
- package/dist/queue/core/index.d.ts +12 -15
- package/dist/queue/core/index.d.ts.map +1 -1
- package/dist/queue/core/index.js.map +1 -1
- package/dist/queue/core/index.workerd.js.map +1 -1
- package/dist/queue/redis/index.d.ts +3 -5
- package/dist/queue/redis/index.d.ts.map +1 -1
- package/dist/queue/redis/index.js.map +1 -1
- package/dist/react/auth/index.browser.js +9 -2
- package/dist/react/auth/index.browser.js.map +1 -1
- package/dist/react/auth/index.d.ts +14 -9
- package/dist/react/auth/index.d.ts.map +1 -1
- package/dist/react/auth/index.js +9 -2
- package/dist/react/auth/index.js.map +1 -1
- package/dist/react/core/index.d.ts +7 -8
- package/dist/react/core/index.d.ts.map +1 -1
- package/dist/react/core/index.js +6 -3
- package/dist/react/core/index.js.map +1 -1
- package/dist/react/form/index.d.ts +2 -4
- package/dist/react/form/index.d.ts.map +1 -1
- package/dist/react/form/index.js.map +1 -1
- package/dist/react/head/index.browser.js.map +1 -1
- package/dist/react/head/index.d.ts +2 -4
- package/dist/react/head/index.d.ts.map +1 -1
- package/dist/react/head/index.js.map +1 -1
- package/dist/react/i18n/index.d.ts +47 -11
- package/dist/react/i18n/index.d.ts.map +1 -1
- package/dist/react/i18n/index.js +33 -1
- package/dist/react/i18n/index.js.map +1 -1
- package/dist/react/intro/index.d.ts +1 -2
- package/dist/react/intro/index.d.ts.map +1 -1
- package/dist/react/intro/index.js +2 -2
- package/dist/react/intro/index.js.map +1 -1
- package/dist/react/router/index.browser.js +65 -19
- package/dist/react/router/index.browser.js.map +1 -1
- package/dist/react/router/index.d.ts +327 -222
- package/dist/react/router/index.d.ts.map +1 -1
- package/dist/react/router/index.js +65 -29
- package/dist/react/router/index.js.map +1 -1
- package/dist/react/testing/index.d.ts +1 -2
- package/dist/react/testing/index.d.ts.map +1 -1
- package/dist/react/testing/index.js +16 -17
- package/dist/react/testing/index.js.map +1 -1
- package/dist/react/ui/index.d.ts +20 -25
- package/dist/react/ui/index.d.ts.map +1 -1
- package/dist/react/ui/index.js.map +1 -1
- package/dist/redis/index.bun.js.map +1 -1
- package/dist/redis/index.d.ts +17 -19
- package/dist/redis/index.d.ts.map +1 -1
- package/dist/redis/index.js.map +1 -1
- package/dist/retry/index.d.ts +2 -4
- package/dist/retry/index.d.ts.map +1 -1
- package/dist/retry/index.js.map +1 -1
- package/dist/router/index.d.ts.map +1 -1
- package/dist/router/index.js.map +1 -1
- package/dist/scheduler/index.d.ts +10 -13
- package/dist/scheduler/index.d.ts.map +1 -1
- package/dist/scheduler/index.js.map +1 -1
- package/dist/scheduler/index.workerd.js.map +1 -1
- package/dist/security/index.browser.js.map +1 -1
- package/dist/security/index.d.ts +45 -48
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js.map +1 -1
- package/dist/server/auth/index.browser.js.map +1 -1
- package/dist/server/auth/index.d.ts +167 -172
- package/dist/server/auth/index.d.ts.map +1 -1
- package/dist/server/auth/index.js +4 -8
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cookies/index.browser.js.map +1 -1
- package/dist/server/cookies/index.d.ts +5 -7
- package/dist/server/cookies/index.d.ts.map +1 -1
- package/dist/server/cookies/index.js.map +1 -1
- package/dist/server/core/index.browser.js.map +1 -1
- package/dist/server/core/index.d.ts +88 -73
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +19 -0
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/cors/index.d.ts +11 -14
- package/dist/server/cors/index.d.ts.map +1 -1
- package/dist/server/cors/index.js.map +1 -1
- package/dist/server/etag/index.d.ts +6 -9
- package/dist/server/etag/index.d.ts.map +1 -1
- package/dist/server/etag/index.js.map +1 -1
- package/dist/server/health/index.d.ts +18 -21
- package/dist/server/health/index.d.ts.map +1 -1
- package/dist/server/health/index.js.map +1 -1
- package/dist/server/links/index.browser.js +2 -0
- package/dist/server/links/index.browser.js.map +1 -1
- package/dist/server/links/index.d.ts +63 -67
- package/dist/server/links/index.d.ts.map +1 -1
- package/dist/server/links/index.js +2 -0
- package/dist/server/links/index.js.map +1 -1
- package/dist/server/metrics/index.d.ts +5 -7
- package/dist/server/metrics/index.d.ts.map +1 -1
- package/dist/server/metrics/index.js.map +1 -1
- package/dist/server/proxy/index.d.ts +3 -5
- package/dist/server/proxy/index.d.ts.map +1 -1
- package/dist/server/proxy/index.js.map +1 -1
- package/dist/server/rate-limit/index.d.ts +10 -13
- package/dist/server/rate-limit/index.d.ts.map +1 -1
- package/dist/server/rate-limit/index.js.map +1 -1
- package/dist/server/static/index.d.ts +3 -5
- package/dist/server/static/index.d.ts.map +1 -1
- package/dist/server/static/index.js.map +1 -1
- package/dist/server/swagger/index.d.ts +5 -8
- package/dist/server/swagger/index.d.ts.map +1 -1
- package/dist/server/swagger/index.js.map +1 -1
- package/dist/sms/index.d.ts +3 -5
- package/dist/sms/index.d.ts.map +1 -1
- package/dist/sms/index.js.map +1 -1
- package/dist/system/index.browser.js.map +1 -1
- package/dist/system/index.d.ts +2 -4
- package/dist/system/index.d.ts.map +1 -1
- package/dist/system/index.js.map +1 -1
- package/dist/system/index.workerd.js.map +1 -1
- package/dist/topic/core/index.d.ts +4 -6
- package/dist/topic/core/index.d.ts.map +1 -1
- package/dist/topic/core/index.js.map +1 -1
- package/dist/topic/redis/index.d.ts +5 -8
- package/dist/topic/redis/index.d.ts.map +1 -1
- package/dist/topic/redis/index.js.map +1 -1
- package/package.json +45 -22
- package/src/api/audits/__tests__/AuditService.spec.ts +18 -110
- package/src/api/audits/controllers/AdminAuditController.ts +14 -0
- package/src/api/audits/services/AuditService.ts +21 -88
- package/src/api/files/__tests__/FileService.spec.ts +207 -2
- package/src/api/files/index.ts +3 -0
- package/src/api/files/schemas/fileCreatorSummarySchema.ts +22 -0
- package/src/api/files/schemas/fileResourceSchema.ts +10 -1
- package/src/api/files/services/FileService.ts +170 -72
- package/src/api/jobs/__tests__/$job.spec.ts +24 -1
- package/src/api/jobs/index.ts +4 -3
- package/src/api/jobs/primitives/$job.ts +7 -3
- package/src/api/jobs/providers/DirectJobDispatcher.ts +17 -36
- package/src/api/jobs/providers/JobProvider.ts +53 -24
- package/src/api/jobs/schemas/jobConfigAtom.ts +1 -1
- package/src/api/jobs/schemas/jobExecutionResourceSchema.ts +4 -1
- package/src/api/keys/schemas/adminApiKeyResourceSchema.ts +3 -1
- package/src/api/parameters/__tests__/$parameter.spec.ts +19 -2
- package/src/api/parameters/audits/ParameterAudits.ts +17 -0
- package/src/api/parameters/controllers/AdminParameterController.ts +95 -19
- package/src/api/parameters/index.ts +3 -0
- package/src/api/parameters/schemas/activateParameterBodySchema.ts +3 -3
- package/src/api/parameters/schemas/createParameterVersionBodySchema.ts +3 -2
- package/src/api/parameters/schemas/parameterCreatorSummarySchema.ts +25 -0
- package/src/api/parameters/schemas/parameterResponseSchema.ts +5 -0
- package/src/api/parameters/schemas/rollbackParameterBodySchema.ts +4 -2
- package/src/api/parameters/services/ParameterProvider.ts +69 -6
- package/src/api/subscriptions/jobs/SubscriptionJobs.ts +1 -1
- package/src/api/users/__tests__/AdminSessionController.spec.ts +37 -0
- package/src/api/users/audits/SessionAudits.ts +33 -0
- package/src/api/users/audits/UserAudits.ts +19 -43
- package/src/api/users/controllers/AdminUserController.ts +66 -1
- package/src/api/users/entities/sessions.ts +6 -0
- package/src/api/users/entities/users.ts +2 -0
- package/src/api/users/index.ts +9 -1
- package/src/api/users/primitives/$realm.ts +3 -0
- package/src/api/users/schemas/sessionResourceSchema.ts +16 -0
- package/src/api/users/schemas/updateUserSchema.ts +1 -8
- package/src/api/users/schemas/userQuerySchema.ts +7 -0
- package/src/api/users/services/CredentialService.ts +15 -6
- package/src/api/users/services/IdentityService.ts +2 -1
- package/src/api/users/services/RegistrationService.ts +2 -1
- package/src/api/users/services/SessionCrudService.ts +19 -2
- package/src/api/users/services/SessionService.ts +39 -19
- package/src/api/users/services/UserService.ts +106 -8
- package/src/background/__tests__/BackgroundTaskProvider.spec.ts +96 -0
- package/src/background/index.ts +37 -0
- package/src/background/index.workerd.ts +28 -0
- package/src/background/providers/BackgroundTaskProvider.ts +70 -0
- package/src/background/providers/WorkerdBackgroundTaskProvider.ts +43 -0
- package/src/bucket/__tests__/$bucket.spec.ts +18 -0
- package/src/bucket/__tests__/LocalFileStorageProvider.spec.ts +5 -0
- package/src/bucket/__tests__/MemoryFileStorageProvider.spec.ts +5 -0
- package/src/bucket/__tests__/NodeS3BucketProvider.spec.ts +23 -4
- package/src/bucket/__tests__/shared.ts +30 -0
- package/src/bucket/index.ts +5 -5
- package/src/bucket/index.workerd.ts +11 -4
- package/src/bucket/primitives/$bucket.ts +27 -0
- package/src/bucket/providers/FileStorageProvider.ts +13 -0
- package/src/bucket/providers/LocalFileStorageProvider.ts +17 -1
- package/src/bucket/providers/MemoryFileStorageProvider.ts +7 -0
- package/src/bucket/providers/{CloudflareR2Provider.ts → R2FileStorageProvider.ts} +10 -1
- package/src/bucket/providers/{NodeS3BucketProvider.ts → S3FileStorageProvider.ts} +27 -5
- package/src/cli/core/__tests__/BuildDockerTask.spec.ts +25 -1
- package/src/cli/core/__tests__/init.spec.ts +0 -219
- package/src/cli/core/commands/__tests__/BuildCommand.spec.ts +43 -0
- package/src/cli/core/commands/build.ts +108 -30
- package/src/cli/core/commands/init.ts +0 -12
- package/src/cli/core/commands/pack.ts +133 -0
- package/src/cli/core/index.ts +3 -0
- package/src/cli/core/providers/ViteDevServerProvider.ts +40 -16
- package/src/cli/core/services/PackageManagerUtils.ts +0 -16
- package/src/cli/core/services/ProjectScaffolder.ts +29 -291
- package/src/cli/core/tasks/BuildCloudflareTask.ts +353 -47
- package/src/cli/core/tasks/BuildDockerTask.ts +33 -3
- package/src/cli/core/tasks/BuildTask.ts +34 -0
- package/src/cli/core/templates/apiIndexTs.ts +1 -22
- package/src/cli/core/templates/mainCss.ts +0 -1
- package/src/cli/core/templates/webAppRouterTs.ts +0 -99
- package/src/cli/core/templates/webIndexTs.ts +1 -22
- package/src/cli/platform/__tests__/SecretsCommand.spec.ts +5 -3
- package/src/cli/platform/commands/SecretsCommand.ts +8 -6
- package/src/cli/platform/commands/platform.ts +192 -46
- package/src/cli/platform/index.ts +12 -52
- package/src/cli/{platform → platform-lib}/__tests__/CloudflareAdapter.spec.ts +426 -169
- package/src/cli/{platform → platform-lib}/__tests__/NamingService.spec.ts +91 -4
- package/src/cli/{platform → platform-lib}/__tests__/VercelAdapter.spec.ts +56 -85
- package/src/cli/{platform → platform-lib}/adapters/CloudflareAdapter.ts +402 -165
- package/src/cli/{platform → platform-lib}/adapters/PlatformAdapter.ts +62 -35
- package/src/cli/{platform → platform-lib}/adapters/VercelAdapter.ts +6 -10
- package/src/cli/{platform → platform-lib}/atoms/platformOptions.ts +34 -1
- package/src/cli/platform-lib/index.ts +67 -0
- package/src/cli/platform-lib/services/NamingService.ts +136 -0
- package/src/cli/{platform → platform-lib}/services/PlatformInspector.ts +60 -13
- package/src/cli/{platform → platform-lib}/services/PlatformOrchestrator.ts +54 -43
- package/src/cli/{platform → platform-lib}/services/WranglerApi.ts +4 -2
- package/src/command/__tests__/Runner.spec.ts +20 -0
- package/src/command/helpers/EnvUtils.ts +19 -3
- package/src/command/helpers/Runner.ts +12 -2
- package/src/command/providers/CliProvider.ts +34 -1
- package/src/{containers → container}/core/__tests__/$container.spec.ts +5 -5
- package/src/{containers → container}/core/index.ts +4 -4
- package/src/{containers → container}/core/index.workerd.ts +19 -3
- package/src/{containers → container}/core/primitives/$container.ts +1 -1
- package/src/{containers → container}/core/providers/CloudflareContainerProvider.ts +17 -19
- package/src/{containers → container}/core/providers/ContainerProvider.ts +16 -2
- package/src/{containers → container}/core/providers/MockContainerProvider.ts +1 -1
- package/src/core/Alepha.ts +49 -1
- package/src/core/__tests__/$env.spec.ts +42 -0
- package/src/core/__tests__/dump.spec.ts +47 -0
- package/src/email/cloudflare/__tests__/CloudflareEmailProvider.spec.ts +42 -10
- package/src/email/cloudflare/index.ts +14 -5
- package/src/email/cloudflare/providers/CloudflareEmailProvider.ts +54 -9
- package/src/logger/__tests__/Logger.spec.ts +55 -0
- package/src/logger/index.ts +13 -0
- package/src/logger/services/Logger.ts +31 -1
- package/src/orm/__tests__/orm-showcase-tests.ts +27 -0
- package/src/orm/__tests__/orm-showcase.spec.ts +12 -0
- package/src/orm/core/interfaces/PgQuery.ts +4 -1
- package/src/orm/core/services/Repository.ts +27 -11
- package/src/react/auth/hooks/useAuth.ts +10 -5
- package/src/react/core/__tests__/useQuery.browser.spec.tsx +25 -0
- package/src/react/core/hooks/useAction.ts +14 -3
- package/src/react/core/hooks/useQuery.ts +24 -4
- package/src/react/i18n/components/Translate.tsx +47 -0
- package/src/react/i18n/index.ts +2 -0
- package/src/react/intro/components/GettingStartedAdminSlide.tsx +2 -2
- package/src/react/router/__tests__/$page.spec.tsx +3 -2
- package/src/react/router/__tests__/page-can.spec.ts +18 -13
- package/src/react/router/hooks/useQueryParams.ts +114 -14
- package/src/react/router/primitives/$page.ts +85 -4
- package/src/react/router/providers/ReactBrowserRouterProvider.ts +3 -7
- package/src/react/router/providers/ReactServerProvider.ts +4 -13
- package/src/react/ui/services/SchemaControl.ts +3 -4
- package/src/server/core/providers/ServerMultipartProvider.ts +19 -0
- package/src/server/links/providers/LinkProvider.ts +10 -0
- package/dist/containers/core/index.d.ts.map +0 -1
- package/dist/containers/core/index.js.map +0 -1
- package/dist/containers/core/index.workerd.js.map +0 -1
- package/src/cli/core/templates/componentsJsonTs.ts +0 -39
- package/src/cli/core/templates/saasAdminLayoutTsx.ts +0 -77
- package/src/cli/core/templates/saasAdminPagesTsx.ts +0 -26
- package/src/cli/core/templates/saasAuthLayoutTsx.ts +0 -22
- package/src/cli/core/templates/saasAuthPagesTsx.ts +0 -62
- package/src/cli/core/templates/saasRealmProviderTs.ts +0 -52
- package/src/cli/platform/services/NamingService.ts +0 -54
- /package/dist/orm/core/{chunk-o8xxKEmq.js → chunk-B4FMCO8f.js} +0 -0
- /package/dist/react/testing/{chunk-6Ep1yQYe.js → chunk-BpyX8vjI.js} +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/GitHubSecretStore.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/PlatformCacheProvider.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/PlatformInspector.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/PlatformOrchestrator.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/SecretFilterService.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/__tests__/detectResources.spec.ts +0 -0
- /package/src/cli/{platform → platform-lib}/providers/GitHubSecretStore.ts +0 -0
- /package/src/cli/{platform → platform-lib}/providers/MemorySecretStore.ts +0 -0
- /package/src/cli/{platform → platform-lib}/providers/PlatformCacheProvider.ts +0 -0
- /package/src/cli/{platform → platform-lib}/providers/SecretStoreProvider.ts +0 -0
- /package/src/cli/{platform → platform-lib}/schemas/cloudflare.ts +0 -0
- /package/src/cli/{platform → platform-lib}/schemas/platform.ts +0 -0
- /package/src/cli/{platform → platform-lib}/schemas/vercel.ts +0 -0
- /package/src/cli/{platform → platform-lib}/services/CloudflareApi.ts +0 -0
- /package/src/cli/{platform → platform-lib}/services/SecretFilterService.ts +0 -0
- /package/src/cli/{platform → platform-lib}/services/VercelApi.ts +0 -0
- /package/src/cli/{platform → platform-lib}/services/VercelCli.ts +0 -0
- /package/src/{containers → container}/core/interfaces/ContainerOptions.ts +0 -0
- /package/src/{containers → container}/core/providers/NodeContainerProvider.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["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","../../../src/cli/core/alephaPackageJson.ts","../../../src/cli/core/services/PackageManagerUtils.ts","../../../src/cli/core/templates/agentMd.ts","../../../src/cli/core/templates/alephaConfigTs.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/componentsJsonTs.ts","../../../src/cli/core/templates/dummySpecTs.ts","../../../src/cli/core/templates/editorconfig.ts","../../../src/cli/core/templates/gitignore.ts","../../../src/cli/core/templates/logoSvg.ts","../../../src/cli/core/templates/mainBrowserTs.ts","../../../src/cli/core/templates/mainCss.ts","../../../src/cli/core/templates/mainServerTs.ts","../../../src/cli/core/templates/saasAdminLayoutTsx.ts","../../../src/cli/core/templates/saasAdminPagesTsx.ts","../../../src/cli/core/templates/saasAuthLayoutTsx.ts","../../../src/cli/core/templates/saasAuthPagesTsx.ts","../../../src/cli/core/templates/saasRealmProviderTs.ts","../../../src/cli/core/templates/tsconfigJson.ts","../../../src/cli/core/templates/viteConfigTs.ts","../../../src/cli/core/templates/vitestConfigTs.ts","../../../src/cli/core/templates/vscodeSettingsJson.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/BuildPwaTask.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 * Extra packages to install globally in the generated image.\n *\n * Each entry becomes a `RUN npm install --global --no-fund\n * --no-audit <pkg> …` line inserted after `FROM` and before the\n * app `COPY`. Use it for CLI tools the running app shells out to\n * — typical example is `wrangler` for a service that deploys to\n * Cloudflare on someone else's behalf.\n *\n * Ignored in `compile` mode (the distroless base has no `npm`).\n *\n * @example install: [\"wrangler\"]\n */\n install: t.optional(t.array(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 * Compile the server entry to a single static binary using\n * `bun build --compile`, then package it inside a minimal base image\n * (distroless by default). Requires `runtime: \"bun\"`.\n *\n * When enabled:\n * - the binary is produced at `<dist>/app` and the original `dist/server/`,\n * `dist/index.js` and `dist/package.json` are removed\n * - the generated Dockerfile uses a distroless base image and does not\n * run `bun install` (everything is embedded in the binary)\n * - any non-empty `dependencies` in the externals manifest causes the\n * task to fail loudly (compile requires fully-bundled output)\n *\n * Pass `true` to enable with defaults, or an object to override.\n */\n compile: t.optional(\n t.union([\n t.boolean(),\n t.object({\n /**\n * Bun target triple, e.g. `bun-linux-x64-musl`,\n * `bun-linux-arm64-musl`, or `bun-linux-x64-modern-musl`\n * (AVX2 required).\n *\n * @default derived from host arch — always linux-musl.\n */\n target: t.optional(t.string()),\n\n /**\n * Base image for the generated Dockerfile.\n *\n * @default \"gcr.io/distroless/static-debian12\"\n */\n base: t.optional(t.string()),\n\n /**\n * Minify the compiled output.\n *\n * @default true\n */\n minify: t.optional(t.boolean()),\n }),\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 * PWA (Progressive Web App) configuration.\n *\n * Generates a web app manifest and enables installability.\n * Requires a client-side bundle (React).\n */\n pwa: t.optional(\n t.object({\n /**\n * Full application name displayed on the splash screen\n * and in the OS app switcher.\n */\n name: t.string(),\n\n /**\n * Short name displayed on the home screen icon.\n * Falls back to `name` if omitted.\n */\n shortName: t.optional(t.string()),\n\n /**\n * Theme color used for the browser toolbar and OS chrome.\n *\n * @default \"#ffffff\"\n */\n themeColor: t.optional(t.string()),\n\n /**\n * Background color for the splash screen.\n *\n * @default \"#ffffff\"\n */\n backgroundColor: t.optional(t.string()),\n\n /**\n * Display mode for the installed PWA.\n *\n * - `standalone` - Looks like a native app (default)\n * - `fullscreen` - Uses entire screen (games, immersive)\n * - `minimal-ui` - Like standalone with minimal browser UI\n * - `browser` - Standard browser tab\n *\n * @default \"standalone\"\n */\n display: t.optional(\n t.enum([\"standalone\", \"fullscreen\", \"minimal-ui\", \"browser\"]),\n ),\n\n /**\n * Enable offline support via service worker.\n *\n * TODO: Not yet implemented.\n */\n offline: t.optional(t.boolean()),\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, opts?: { pwa?: boolean }): string {\n const style = entry.style;\n const browser = entry.browser ?? entry.server;\n const manifestLink = opts?.pwa\n ? '\\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />'\n : \"\";\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\"/>${manifestLink}\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 { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { $inject, Alepha, AlephaError } 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 * Resolve the absolute path to a toolchain binary that ships embedded in\n * `alepha`'s own `dependencies` (typescript, vite, vitest, @biomejs/biome,\n * drizzle-kit).\n *\n * The CLI runs the result via `node <path>` so the toolchain works under\n * every package manager — including pnpm with a strict node-linker, where\n * a transitive dependency's bin is NOT hoisted into the project's\n * `node_modules/.bin`. Resolution starts from `alepha`'s own location, so\n * the version is whatever `alepha` shipped — the project never pins it.\n *\n * @param pkg - npm package name (e.g. `\"typescript\"`)\n * @param binName - which `bin` entry to use (e.g. `\"tsc\"`); defaults to the\n * package's only/first bin\n */\n public resolveBin(pkg: string, binName?: string): string {\n const require = createRequire(import.meta.url);\n\n // Locate the package root by scanning the `node_modules` directories\n // Node would search, then reading `package.json` from disk directly.\n // We deliberately avoid `require.resolve(\"<pkg>/package.json\")` — a\n // strict `exports` map (e.g. drizzle-kit) blocks that subpath.\n let pkgDir: string | undefined;\n for (const nm of require.resolve.paths(pkg) ?? []) {\n const candidate = join(nm, pkg);\n if (existsSync(join(candidate, \"package.json\"))) {\n pkgDir = candidate;\n break;\n }\n }\n if (!pkgDir) {\n throw new AlephaError(\n `Cannot locate package '${pkg}' — is it installed alongside alepha?`,\n );\n }\n\n const meta = JSON.parse(\n readFileSync(join(pkgDir, \"package.json\"), \"utf8\"),\n ) as { bin?: string | Record<string, string> };\n const bin = meta.bin;\n if (!bin) {\n throw new AlephaError(`Package '${pkg}' declares no 'bin' entry`);\n }\n const rel =\n typeof bin === \"string\"\n ? bin\n : (bin[binName ?? pkg] ?? Object.values(bin)[0]);\n if (!rel) {\n throw new AlephaError(`Package '${pkg}' has no bin named '${binName}'`);\n }\n return join(pkgDir, rel);\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 pkg from \"alepha/package.json\" with { type: \"json\" };\n\nexport const alephaPackageJson = pkg;\nexport const version = pkg.version as string;\n","import { basename } from \"node:path\";\nimport { $inject, Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { alephaPackageJson, version } from \"../alephaPackageJson.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 pkg.packageManager = undefined;\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 pkg.packageManager = undefined;\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 // The toolchain (typescript, vite, vitest, biome, drizzle-kit) is NOT\n // pinned here — it ships embedded as `dependencies` of `alepha`, so the\n // `alepha` CLI resolves and runs it from its own install. The project\n // never declares those versions; upgrading `alepha` moves the whole\n // toolchain atomically. See `AlephaCliUtils.resolveBin`.\n const devDependencies: Record<string, string> = {};\n\n const scripts: Record<string, string> = {\n dev: \"alepha dev\",\n build: \"alepha build\",\n test: \"alepha test\",\n lint: \"alepha lint\",\n typecheck: \"alepha typecheck\",\n verify: \"alepha verify\",\n };\n\n if (modes.tailwind) {\n devDependencies.tailwindcss = alephaDeps.tailwindcss;\n devDependencies[\"@tailwindcss/vite\"] = alephaDeps[\"@tailwindcss/vite\"];\n }\n\n if (modes.shadcn) {\n // Add `shadcn` CLI as a project devDep — `alepha init --shadcn` runs\n // `yarn shadcn init` after install to scaffold components.json,\n // theme tokens, cn() helper, and runtime deps (clsx, tailwind-merge,\n // class-variance-authority, lucide-react, tw-animate-css). Keeping\n // the CLI in the project lets users re-run `yarn shadcn add ...`\n // without `npx`.\n devDependencies.shadcn = alephaDeps.shadcn;\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 expo?: boolean;\n tailwind?: boolean;\n shadcn?: boolean;\n /**\n * SaaS starter: implies `shadcn` + adds the alepha auth + admin registry\n * components on top via `shadcn add @alepha/...`.\n */\n saas?: boolean;\n /**\n * Whether the project is a workspace package inside a monorepo.\n */\n isPackage?: boolean;\n}\n","export const agentMd = (): string => {\n return `# AGENTS.md\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\nalepha platform plan # Show planned cloud topology (requires platform plugin)\nalepha platform up # Provision + deploy to a configured environment\nalepha platform status # Inspect deployed resources\n\\`\\`\\`\n\n## Testing\n\n- Specs live in \\`test/\\`, named \\`*.spec.ts\\`.\n- Run with \\`alepha test\\` (Vitest, embedded in alepha — nothing to install).\n- \\`test/dummy.spec.ts\\` is the starting example; \\`Alepha.create()\\` is the\n entry point and \\`.inject(...)\\` resolves providers.\n\n## Cloud deployment (Cloudflare Workers)\n\nAdd the \\`platform\\` plugin to \\`alepha.config.ts\\` to manage cloud\nprovisioning, deploy, secrets, and DB migrations end-to-end:\n\n\\`\\`\\`ts\nimport { defineConfig } from \"alepha/cli/config\";\nimport { platform } from \"alepha/cli/platform\";\n\nexport default defineConfig({\n plugins: [\n platform({\n environments: {\n production: {\n adapter: \"cloudflare\",\n domain: \"yourapp.com\",\n // zone: \"yourapp.com\", // required only for wildcard domains\n // jurisdiction: \"eu\", // optional: EU data residency\n },\n },\n }),\n ],\n});\n\\`\\`\\`\n\nThen: \\`alepha platform up --env production\\` (auth via \\`wrangler login\\` on first run).\n\nSupported adapters: \\`cloudflare\\`, \\`vercel\\`. The Cloudflare adapter provisions\nD1 (or Hyperdrive when \\`DATABASE_URL\\` is postgres), KV, R2, Queues, and pushes\nsecrets via \\`wrangler secret bulk\\`. Set \\`build.target: \"cloudflare\"\\` in\n\\`alepha.config.ts\\` if you only want the build artifact without the orchestrator.\n\n## Documentation\n\n- Framework source: \\`node_modules/alepha/src/\\`\n- Docs: https://alepha.dev/llms.txt\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// import { platform } from \"alepha/cli/platform\";\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 // // Deploy to Cloudflare in ~10s: \\`alepha platform up --env production\\`\n // // Requires \\`wrangler login\\` once. D1, R2, KV, Queues and cron triggers\n // // are auto-provisioned from your $repository / $bucket / $cache / $queue\n // // / $scheduler primitives — no wrangler.toml to maintain.\n // plugins: [\n // platform({\n // environments: {\n // production: { adapter: \"cloudflare\", domain: \"myapp.com\" },\n // preview: { adapter: \"cloudflare\" }, // workers.dev subdomain\n // },\n // }),\n // ],\n});\n`;\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 /**\n * Include `AlephaApiUsers` (realms, sessions, registration, identities,\n * password reset, email verification, admin endpoints) plus the local\n * `RealmProvider` that declares `$realm({ ... })`.\n */\n saas?: boolean;\n}\n\nexport const apiIndexTs = (options: ApiIndexTsOptions = {}) => {\n const { appName = \"app\", saas = false } = options;\n\n if (saas) {\n return `\nimport { $module } from \"alepha\";\nimport { AlephaApiUsers } from \"alepha/api/users\";\nimport { HelloController } from \"./controllers/HelloController.ts\";\nimport { RealmProvider } from \"./providers/RealmProvider.ts\";\n\nexport const ApiModule = $module({\n name: \"${appName}.api\",\n services: [HelloController, RealmProvider],\n imports: [AlephaApiUsers],\n});\n`.trim();\n }\n\n return `\nimport { $module } from \"alepha\";\nimport { HelloController } from \"./controllers/HelloController.ts\";\n\nexport const ApiModule = $module({\n name: \"${appName}.api\",\n services: [HelloController],\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 \"a11y\": {\n \"useFocusableInteractive\": \"off\",\n \"useSemanticElements\": \"off\",\n \"useKeyWithClickEvents\": \"off\",\n \"useAriaPropsForRole\": \"off\",\n \"noLabelWithoutControl\": \"off\"\n },\n \"correctness\": {\n \"useExhaustiveDependencies\": \"off\"\n },\n \"suspicious\": {\n \"noArrayIndexKey\": \"off\",\n \"noExplicitAny\": \"off\",\n \"noDocumentCookie\": \"off\"\n },\n \"style\": {\n \"noNonNullAssertion\": \"off\"\n }\n },\n \"domains\": {\n \"react\": \"recommended\"\n }\n },\n \"css\": {\n \"parser\": {\n \"cssModules\": false,\n \"tailwindDirectives\": true\n }\n },\n \"assist\": {\n \"actions\": {\n \"source\": {\n \"organizeImports\": \"on\"\n }\n }\n }\n}\n`.trim();\n","/**\n * `components.json` is the shadcn CLI's project config — it tells\n * `shadcn add` where to drop primitives, which tailwind tokens to use,\n * which icon library to wire up, and which custom registries to resolve.\n *\n * Aliases follow shadcn's defaults (`@/components`, `@/lib/utils`) so the\n * CLI honors them across `init` + `add` calls. Alepha app code lives at\n * `src/web/` (Home, AppRouter, …) and the shadcn primitives live at\n * `src/components/` — kept separate to make the registry components\n * trivially upgradable via `shadcn add --overwrite`.\n *\n * The `registries` block pre-wires the public Alepha registry — consumers\n * can immediately run e.g. `shadcn add @alepha/auth-login`.\n */\nexport const componentsJsonTs = () =>\n `{\n \"$schema\": \"https://ui.shadcn.com/schema.json\",\n \"style\": \"new-york\",\n \"rsc\": false,\n \"tsx\": true,\n \"tailwind\": {\n \"config\": \"\",\n \"css\": \"src/main.css\",\n \"baseColor\": \"neutral\",\n \"cssVariables\": true\n },\n \"aliases\": {\n \"components\": \"@/components\",\n \"utils\": \"@/lib/utils\",\n \"ui\": \"@/components/ui\",\n \"lib\": \"@/lib\",\n \"hooks\": \"@/hooks\"\n },\n \"iconLibrary\": \"lucide\",\n \"registries\": {\n \"@alepha\": \"https://alepha.dev/r/{name}.json\"\n }\n}\n`;\n","/**\n * Starter spec written by `alepha init`. It doubles as a worked example:\n * it shows the test location (`test/`), the `*.spec.ts` naming, and the\n * canonical Alepha entry point — `Alepha.create()` + `.inject(...)`.\n *\n * Tests run with `alepha test` (Vitest, embedded in alepha). Replace this\n * with real specs as the project grows.\n */\nexport const dummySpecTs = () =>\n `\nimport { Alepha } from \"alepha\";\nimport { expect, test } from \"vitest\";\n\ntest(\"alepha app can be created\", () => {\n const alepha = Alepha.create();\n\n expect(alepha).toBeDefined();\n expect(alepha.inject).toBeTypeOf(\"function\");\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 logoSvg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"300\" height=\"300\">\n <svg xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"b\" x1=\"142.3\" x2=\"159.6\" y1=\"123.3\" y2=\"176.7\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#33a72c\"/>\n <stop offset=\"1\" stop-color=\"#2d8d40\"/>\n </linearGradient>\n <linearGradient id=\"c\" x1=\"61.6\" x2=\"100.7\" y1=\"218.5\" y2=\"174\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#298e35\"/>\n <stop offset=\"1\" stop-color=\"#327952\"/>\n </linearGradient>\n <linearGradient id=\"d\" x1=\"262.7\" x2=\"242.2\" y1=\"178.4\" y2=\"220.1\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#32a62d\"/>\n <stop offset=\"1\" stop-color=\"#2d8d40\"/>\n </linearGradient>\n <linearGradient id=\"e\" x1=\"81.2\" x2=\"69.1\" y1=\"126.7\" y2=\"92.3\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#299a2c\"/>\n <stop offset=\"1\" stop-color=\"#51be40\"/>\n </linearGradient>\n <clipPath id=\"a\">\n <path fill=\"none\" d=\"M0 0h300v241H0z\"/>\n </clipPath>\n </defs>\n <g fill=\"none\" stroke-miterlimit=\"10\" clip-path=\"url(#a)\" font-family=\"none\" font-size=\"none\" font-weight=\"300\" style=\"mix-blend-mode:normal\" text-anchor=\"middle\">\n <path fill=\"url(#b)\" d=\"M54 174a182 182 0 0 1 106-51c19-2 37-6 54-15l16-11 3-4 1 1 1 4 1 6v9c0 6-2 12-5 18l-1 4-7 8c-5 7-12 14-19 19l-4 2-11 7v1l-1-1-3 2a120 120 0 0 1-30 8l-8 1-20-1c-21-3-44-10-64 0-5 2-9 4-12 8l-9 9h1l14-9c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-5 1h-8l-7-1H15c0-3 4-7 5-9l7-11 5-8c6-10 14-19 22-28z\"/>\n <path fill=\"#1d524a\" d=\"M178 141c9-1 17-4 24-8l8-4-6 4c-9 7-20 11-32 13l-39 5h-5l-15 3 16 13 18 15-20-1c-21-3-44-10-64 0-5 2-9 4-12 8l-9 9h1l14-9c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-5 1h-8l-7-1H15c0-3 4-7 5-9l7-11 5-8c6-10 14-19 22-28l4-2 23-14 11-5c21-7 43-9 65-9l21-3z\"/>\n <path fill=\"url(#c)\" d=\"M57 189c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-4-9-2-5 5-2 9-4 10-5 10-4c5-2 10-3 14-6l3-1h-1a1136 1136 0 0 0-43 14c1-6 6-14 9-19 1 0 0 0 0 0z\"/>\n <path fill=\"#2d6f4d\" d=\"m41 216 5-2 9-4 5 3c9 4 18 6 27 4h4c-12 8-25 12-39 13h-5l-4-9-2-5zm16-27s1 0 0 0c-3 5-8 13-9 19l-15 8c0-3 1-9 3-11l3-3 4-4 14-9z\"/>\n <path fill=\"#49b63b\" d=\"M42 198h1l-4 4 3-4z\"/>\n <path fill=\"#2d6f4d\" d=\"m113 154 15-3 11 2 18 8c11 6 23 8 35 5l8-2-11 7v1l-1-1-3 2a120 120 0 0 1-30 8l-8 1-18-15-16-13z\"/>\n <path fill=\"#49b63b\" d=\"M81 158c2-4 11-7 15-8 18-6 36-7 55-8l12-1h15l-21 3c-22 0-44 2-65 9l-11 5z\"/>\n <path fill=\"#2d913b\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1 1 5v6l6 12 5 10 12 26 2 5 4 10 7 17 4 8c-9 5-20 9-30 12l-16 3-7-14-6-14-5-10-1-3-4 7-13 27-6 11-6 2-24 9 2-4c11-16 14-36 11-56l-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#2d6f4d\" d=\"m175 17 6 12 5 10 12 26 2 5 4 10 7 17 4 8c-9 5-20 9-30 12l-16 3-7-14-6-14-5-10-1-3c0-2 5-8 6-10l1-2c9-13 17-28 18-45v-5z\"/>\n <path fill=\"#1d524a\" d=\"m175 17 6 12 5 10 12 26 2 5-3-1-13-8-7 4 3 7-4 1-2-3-5-12-5 7a136 136 0 0 1-10 15l-3 2-1-3c0-2 5-8 6-10l1-2c9-13 17-28 18-45v-5z\"/>\n <path fill=\"#2d6f4d\" d=\"m186 39 12 26 2 5-3-1-13-8-7 4-6-12 8-7 7-7z\"/>\n <path fill=\"#2d913b\" d=\"m177 65 7-4 13 8 3 1 4 10-3 7-7 14-2 8-1-4-6-19a99 99 0 0 0-8-21zm-3 5 2 3 12 32h-1l-8 5c-4 1-9 0-13-2l-1-1c-1-8 2-15 4-22 1-5 2-10 5-15z\"/>\n <path fill=\"#1d524a\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1c-3 1-3 2-4 4l-11 14-5 5v1c-11 11-22 24-31 37l-5 6-6 11h1l6 12c3 7 8 13 14 17l-6 11-6 2-24 9 2-4c11-16 14-36 11-56l-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#49b63b\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1c-3 1-3 2-4 4l-11 14-5 5-8 7-13 11-5 6c-5-2-10-5-15-3l-3 2z\"/>\n <path fill=\"#2d913b\" d=\"m110 52 3-2c5-2 10 1 15 3l-12 13-6 9-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#2d6f4d\" d=\"M121 92c10-5 19-9 28-17l7-6c-1 2-6 8-6 10l-4 7-13 27c-6-4-11-10-14-17l-6-12 4-5 4 13z\"/>\n <path fill=\"#49b63b\" d=\"m154 30-1 11c0 4-3 9-6 12-6 9-19 10-25 19-1 0-3 2-4 1l5-6c9-13 20-26 31-37z\"/>\n <path fill=\"url(#d)\" d=\"m230 135 3 6 11 17 2 5 4 5 3 6 9 14 19 36 4 5c-2 2-19 2-22 2l-5-1h-2c-12 0-25-4-35-10l-4-3c-10-8-15-16-21-27l-7-18v-1l11-7 4-2c7-5 14-12 19-19l7-8z\"/>\n <path fill=\"#1d524a\" d=\"m230 135 3 6 11 17 2 5 4 5 3 6h-1c-10-8-20-9-32-4l23 23 13 12 1 2-20-14-13-12-4-3-5-6c-2 0-2 3-2 5l-1 10c-1 8-2 11 1 19l2 6 2 5c-10-8-15-16-21-27l-7-18v-1l11-7 4-2c7-5 14-12 19-19l7-8z\"/>\n <path fill=\"#2d6f4d\" d=\"m233 141 11 17 2 5 4 5 3 6h-1c-10-8-20-9-32-4l-7-9 15-15 5-5zm-16 76-2-5-2-6c-3-8-2-11-1-19l1-10c0-2 0-5 2-5l5 6 4 3h-1c0 4 8 22 11 26 6 10 15 18 25 22 2 0 3 0 4 2l-5-1h-2c-12 0-25-4-35-10l-4-3z\"/>\n <path fill=\"#2d913b\" d=\"M110 75c3 20 0 40-11 56l-2 4a145 145 0 0 0-43 31l-5 4-11 15v-7l-1-10a143 143 0 0 1 5-29l9-20c13-18 32-29 52-37l4-3 3-4z\"/>\n <path fill=\"url(#e)\" d=\"m42 139 9-20c13-18 32-29 52-37l4-3-3 7c-4 5-8 11-13 15l-3 3c-6 6-13 12-18 19l-8 11-20 5z\"/>\n <path fill=\"#1d524a\" d=\"M91 101c0 2-4 6-6 8-5 5-10 11-14 18l-9 13-4 9 5 1c4 0 16-9 19-7-10 7-20 14-28 23l-5 4-11 15v-7l-1-10a143 143 0 0 1 5-29l20-5 8-11c5-7 12-13 18-19l3-3z\"/>\n <path fill=\"#2d6f4d\" d=\"m62 134-9 16-3 7-2 4c-3 3-8 5-10 8l-1-1a143 143 0 0 1 5-29l20-5zm0 6 11-5 7-4c5-1 14-2 19 0l-2 4-15 8c-3-2-15 7-19 7l-5-1 4-9z\"/>\n </g>\n </svg>\n</svg>\n`;\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: { tailwind?: boolean } = {}) => {\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 * - Tailwind CSS: Use \\`alepha init --tailwind\\` to add Tailwind CSS\n * - shadcn/ui: Use \\`alepha init --shadcn\\` to add shadcn/ui setup\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","/**\n * SaaS admin layout — full AppShell on /admin with a sidebar, breadcrumbs,\n * a Sonner toaster, and a confirm provider. The page list grows with\n * whatever `admin-*` registry components the user adds.\n *\n * All UI primitives come from `src/components/*` where `shadcn add` drops\n * them; alepha app code lives in `src/web/*` and references them via the\n * `@/components/*` alias.\n */\nexport const saasAdminLayoutTsx = () =>\n `import { AppShell } from \"@/components/app-shell/app-shell\";\nimport { Toaster } from \"@/components/ui/sonner\";\nimport { TooltipProvider } from \"@/components/ui/tooltip\";\nimport { DialogProvider } from \"@/components/use-dialog/use-dialog\";\nimport { NestedView, useRouterState } from \"alepha/react/router\";\nimport { ShieldCheck, Users } from \"lucide-react\";\n\nconst NAV = [\n {\n label: \"Identity\",\n items: [\n { href: \"/admin/users\", label: \"Users\", icon: Users },\n { href: \"/admin/sessions\", label: \"Sessions\", icon: ShieldCheck },\n ],\n },\n] as const;\n\nconst findCrumbs = (pathname: string): { label: string; href?: string }[] => {\n for (const group of NAV) {\n const match = group.items.find((it) => it.href === pathname);\n if (match) return [{ label: group.label }, { label: match.label }];\n }\n return [];\n};\n\nconst AdminLayout = () => {\n const state = useRouterState();\n const crumbs = findCrumbs(state.url.pathname);\n\n return (\n <TooltipProvider>\n <DialogProvider>\n <AppShell\n brand={\n <a\n href=\"/admin\"\n className=\"flex items-center gap-2 px-2 py-2 font-semibold group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0\"\n >\n <span className=\"bg-primary text-primary-foreground flex size-7 shrink-0 items-center justify-center rounded\">\n α\n </span>\n <span className=\"truncate group-data-[collapsible=icon]:hidden\">\n Admin\n </span>\n </a>\n }\n nav={NAV.map((group) => ({\n label: group.label,\n items: group.items.map((it) => ({\n href: it.href,\n label: it.label,\n icon: it.icon,\n active: it.href === state.url.pathname,\n })),\n }))}\n breadcrumbs={crumbs.length ? crumbs : undefined}\n >\n <NestedView />\n </AppShell>\n <Toaster />\n </DialogProvider>\n </TooltipProvider>\n );\n};\n\nexport default AdminLayout;\n`;\n","/**\n * Admin pages — each is a thin wrapper around the matching `admin-*`\n * registry component (placed at `src/components/admin/*`). The starter\n * ships with Users + Sessions; add more by `shadcn add @alepha/admin-…`\n * and a matching `$page(...)` in AppRouter.\n */\n\nexport const saasAdminUsersTsx = () =>\n `import { AdminUsers } from \"@/components/admin/admin-users\";\n\nconst AdminUsersPage = () => {\n return <AdminUsers />;\n};\n\nexport default AdminUsersPage;\n`;\n\nexport const saasAdminSessionsTsx = () =>\n `import { AdminSessions } from \"@/components/admin/admin-sessions\";\n\nconst AdminSessionsPage = () => {\n return <AdminSessions />;\n};\n\nexport default AdminSessionsPage;\n`;\n","/**\n * SaaS auth layout — route parent for every /auth/* page (login, register,\n * reset-password, verify-email), mounted as children so they share it.\n *\n * The auth-* blocks from the registry are self-contained full-page layouts\n * (they own their own min-height, centering and padding), so this layout is\n * just a passthrough — wrapping them in another centered, padded, full-height\n * box would overflow the viewport and add a scrollbar.\n */\nexport const saasAuthLayoutTsx = () =>\n `import { NestedView } from \"alepha/react/router\";\n\nconst AuthLayout = () => {\n return (\n <div className=\"bg-background\">\n <NestedView />\n </div>\n );\n};\n\nexport default AuthLayout;\n`;\n","/**\n * Per-page wrapper around the registry components. The registry component\n * receives the realm config from the page loader; the page itself stays a\n * thin shell so apps can layer their branding around it.\n *\n * Registry components land at `src/components/auth/*` (shadcn defaults).\n */\n\nexport const saasAuthLoginTsx = () =>\n `import { AuthLogin } from \"@/components/auth/auth-login\";\nimport type { RealmConfig } from \"alepha/api/users\";\n\nexport interface AuthLoginPageProps {\n realmConfig: RealmConfig;\n}\n\nconst AuthLoginPage = (props: AuthLoginPageProps) => {\n return <AuthLogin realmConfig={props.realmConfig} />;\n};\n\nexport default AuthLoginPage;\n`;\n\nexport const saasAuthRegisterTsx = () =>\n `import { AuthRegister } from \"@/components/auth/auth-register\";\nimport type { RealmConfig } from \"alepha/api/users\";\n\nexport interface AuthRegisterPageProps {\n realmConfig: RealmConfig;\n}\n\nconst AuthRegisterPage = (props: AuthRegisterPageProps) => {\n return <AuthRegister realmConfig={props.realmConfig} />;\n};\n\nexport default AuthRegisterPage;\n`;\n\nexport const saasAuthResetPasswordTsx = () =>\n `import { AuthResetPassword } from \"@/components/auth/auth-reset-password\";\nimport type { RealmConfig } from \"alepha/api/users\";\n\nexport interface AuthResetPasswordPageProps {\n realmConfig: RealmConfig;\n}\n\nconst AuthResetPasswordPage = (props: AuthResetPasswordPageProps) => {\n return <AuthResetPassword realmConfig={props.realmConfig} />;\n};\n\nexport default AuthResetPasswordPage;\n`;\n\nexport const saasAuthVerifyEmailTsx = () =>\n `import { AuthVerifyEmail } from \"@/components/auth/auth-verify-email\";\n\nconst AuthVerifyEmailPage = () => {\n return <AuthVerifyEmail />;\n};\n\nexport default AuthVerifyEmailPage;\n`;\n","/**\n * Realm provider scaffolded by `alepha init --saas`.\n *\n * Minimal hello-world setup: credentials login with email, admins seeded\n * from the `ADMIN_EMAILS` env var, and an `admin:ui` permission used by the\n * AppRouter to gate `/admin/*`. The default `admin` role grants `*` (so it\n * inherits `admin:ui`); the default `user` role excludes `admin:*` (so\n * non-admins get a 403 before the shell renders).\n *\n * Admin emails are read from the environment, never hard-coded — they are\n * deployment config (different per environment, and personal data) and\n * belong in `.env`, not in committed source.\n */\nexport const saasRealmProviderTs = () => {\n return `import { $env, t } from \"alepha\";\nimport { $realm } from \"alepha/api/users\";\nimport { $permission } from \"alepha/security\";\n\nexport class RealmProvider {\n /**\n * Permission required to open the admin UI. Wired into AppRouter.adminLayout\n * via \\`$secure({ permissions: [\"admin:ui\"] })\\`.\n */\n adminUi = $permission({\n group: \"admin\",\n name: \"ui\",\n description: \"Access to the admin UI shell\",\n });\n\n /**\n * Admin emails — set \\`ADMIN_EMAILS\\` in \\`.env\\` (comma-separated for\n * several). Keep emails out of source: they are config, not code.\n */\n protected readonly env = $env(\n t.object({\n ADMIN_EMAILS: t.text({ default: \"\" }),\n }),\n );\n\n realm = $realm({\n settings: {\n adminEmails: this.env.ADMIN_EMAILS.split(\",\")\n .map((email) => email.trim())\n .filter(Boolean),\n },\n identities: {\n credentials: true,\n },\n });\n}\n`;\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","/**\n * Minimal Vitest config for a freshly scaffolded Alepha project.\n *\n * Defines `test.root` explicitly so Vitest doesn't walk up the directory\n * tree and inherit a parent monorepo config (which can pull in unrelated\n * setup files, database connections, etc.).\n */\nexport const vitestConfigTs = () =>\n `import { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n test: {\n root: \".\",\n globals: true,\n },\n});\n`;\n","/**\n * `.vscode/settings.json` — points the editor's TypeScript language server\n * at the `typescript` copy embedded in `alepha`'s dependencies, so the IDE\n * type-checks with the exact same compiler version as `alepha typecheck`.\n *\n * Without this, VS Code falls back to its own bundled TypeScript, which\n * drifts from whatever `alepha` ships — the classic \"green in CI, red\n * squiggles in the editor\" skew.\n *\n * The path assumes a hoisting package manager (yarn node-modules / npm /\n * bun), where `alepha`'s `typescript` dependency lands at the project's\n * top-level `node_modules/typescript`. Since the project no longer declares\n * its own `typescript`, that is the only copy present.\n */\nexport const vscodeSettingsJson = () =>\n `\n{\n \"typescript.tsdk\": \"node_modules/typescript/lib\",\n \"typescript.enablePromptUseWorkspaceTsdk\": true\n}\n`.trim();\n","export interface WebAppRouterOptions {\n api?: boolean;\n saas?: boolean;\n}\n\nexport const webAppRouterTs = (options: WebAppRouterOptions) => {\n if (options.saas) {\n return saasAppRouterTs();\n }\n return basicAppRouterTs(options);\n};\n\nconst basicAppRouterTs = (options: WebAppRouterOptions) => {\n const imports: string[] = ['import { $page } from \"alepha/react/router\";'];\n const classMembers: string[] = [];\n\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 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\n/**\n * SaaS router wires three trees onto the app:\n * / → Home\n * /auth/* → AuthLayout + login / register / reset / verify\n * /admin/* → AdminLayout + users / sessions / api-keys / parameters / audits\n *\n * Each auth page resolves the realm config from its loader, so the registry\n * components render with everything they need on first paint.\n */\nconst saasAppRouterTs =\n () => `import type { RealmController } from \"alepha/api/users\";\nimport { $page, NotFound } from \"alepha/react/router\";\nimport { $secure } from \"alepha/security\";\nimport { $client } from \"alepha/server/links\";\nimport type { HelloController } from \"../api/controllers/HelloController.ts\";\n\nexport class AppRouter {\n protected readonly api = $client<HelloController>();\n protected readonly realmApi = $client<RealmController>();\n\n home = $page({\n path: \"/\",\n lazy: () => import(\"./components/Home.tsx\"),\n loader: () => this.api.hello(),\n });\n\n // ── /auth — login, register, reset, verify ─────────────────────────────\n authLayout = $page({\n path: \"/auth\",\n lazy: () => import(\"./components/auth/AuthLayout.tsx\"),\n });\n\n login = $page({\n parent: this.authLayout,\n path: \"/login\",\n name: \"login\",\n head: { title: \"Sign in\" },\n lazy: () => import(\"./components/auth/Login.tsx\"),\n loader: async () => ({ realmConfig: await this.realmApi.getRealmConfig() }),\n });\n\n register = $page({\n parent: this.authLayout,\n path: \"/register\",\n name: \"register\",\n head: { title: \"Sign up\" },\n lazy: () => import(\"./components/auth/Register.tsx\"),\n loader: async () => ({ realmConfig: await this.realmApi.getRealmConfig() }),\n });\n\n resetPassword = $page({\n parent: this.authLayout,\n path: \"/reset-password\",\n head: { title: \"Reset password\" },\n lazy: () => import(\"./components/auth/ResetPassword.tsx\"),\n loader: async () => ({ realmConfig: await this.realmApi.getRealmConfig() }),\n });\n\n verifyEmail = $page({\n parent: this.authLayout,\n path: \"/verify-email\",\n head: { title: \"Verify email\" },\n lazy: () => import(\"./components/auth/VerifyEmail.tsx\"),\n });\n\n // ── /admin — gated by 'admin:ui' permission, declared in RealmProvider.\n // Children inherit the gate via the parent chain.\n adminLayout = $page({\n path: \"/admin\",\n use: [$secure({ permissions: [\"admin:ui\"] })],\n lazy: () => import(\"./components/admin/AdminLayout.tsx\"),\n });\n\n adminUsers = $page({\n parent: this.adminLayout,\n path: \"/users\",\n head: { title: \"Users\" },\n lazy: () => import(\"./components/admin/Users.tsx\"),\n });\n\n adminSessions = $page({\n parent: this.adminLayout,\n path: \"/sessions\",\n head: { title: \"Sessions\" },\n lazy: () => import(\"./components/admin/Sessions.tsx\"),\n });\n\n notFound = $page({ path: \"/*\", component: NotFound });\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 * SaaS bundle: auth pages need `useAuth()` (ReactAuth) which lives in the\n * `alepha.react.auth` module. Importing it here registers ReactAuth in the\n * container so the auth-* registry components can inject it.\n */\n saas?: boolean;\n}\n\nexport const webIndexTs = (options: WebIndexTsOptions = {}) => {\n const { appName = \"app\", saas = false } = options;\n\n if (saas) {\n return `\nimport { $module } from \"alepha\";\nimport { AlephaReactAuth } from \"alepha/react/auth\";\nimport { AlephaReactI18n } from \"alepha/react/i18n\";\nimport { AppRouter } from \"./AppRouter.ts\";\n\nexport const WebModule = $module({\n name: \"${appName}.web\",\n services: [AppRouter],\n imports: [AlephaReactAuth, AlephaReactI18n],\n});\n`.trim();\n }\n\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 { basename, dirname } from \"node:path\";\nimport { $inject, AlephaError } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger, ConsoleColorProvider } from \"alepha/logger\";\nimport { FileSystemProvider, ShellProvider } from \"alepha/system\";\nimport { agentMd } from \"../templates/agentMd.ts\";\nimport { alephaConfigTs } from \"../templates/alephaConfigTs.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 { componentsJsonTs } from \"../templates/componentsJsonTs.ts\";\nimport { dummySpecTs } from \"../templates/dummySpecTs.ts\";\nimport { editorconfig } from \"../templates/editorconfig.ts\";\nimport { gitignore } from \"../templates/gitignore.ts\";\nimport { logoSvg } from \"../templates/logoSvg.ts\";\nimport { mainBrowserTs } from \"../templates/mainBrowserTs.ts\";\nimport { mainCss } from \"../templates/mainCss.ts\";\nimport { mainServerTs } from \"../templates/mainServerTs.ts\";\nimport { saasAdminLayoutTsx } from \"../templates/saasAdminLayoutTsx.ts\";\nimport {\n saasAdminSessionsTsx,\n saasAdminUsersTsx,\n} from \"../templates/saasAdminPagesTsx.ts\";\nimport { saasAuthLayoutTsx } from \"../templates/saasAuthLayoutTsx.ts\";\nimport {\n saasAuthLoginTsx,\n saasAuthRegisterTsx,\n saasAuthResetPasswordTsx,\n saasAuthVerifyEmailTsx,\n} from \"../templates/saasAuthPagesTsx.ts\";\nimport { saasRealmProviderTs } from \"../templates/saasRealmProviderTs.ts\";\nimport { tsconfigJson } from \"../templates/tsconfigJson.ts\";\nimport { viteConfigTs } from \"../templates/viteConfigTs.ts\";\nimport { vitestConfigTs } from \"../templates/vitestConfigTs.ts\";\nimport { vscodeSettingsJson } from \"../templates/vscodeSettingsJson.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 shell = $inject(ShellProvider);\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 /**\n * `true` writes a tsconfig.json if one doesn't already exist (parent\n * dirs included). `\"local\"` writes one when none exists *in this\n * directory* — used by shadcn since the CLI reads the local\n * tsconfig directly for import-alias detection.\n */\n tsconfigJson?: boolean | \"local\";\n biomeJson?: boolean;\n editorconfig?: boolean;\n agentMd?: boolean;\n /**\n * Write `.vscode/settings.json` pointing the editor's TypeScript\n * server at the `typescript` copy embedded in `alepha`.\n */\n vscodeSettings?: boolean;\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(\n this.ensureTsConfig(root, {\n force,\n localOnly: opts.tsconfigJson === \"local\",\n }),\n );\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, { force }));\n }\n if (opts.vscodeSettings) {\n tasks.push(this.ensureVscodeSettings(root, { force, checkWorkspace }));\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; localOnly?: boolean } = {},\n ): Promise<void> {\n // Check if tsconfig.json exists in current or parent directories.\n // `localOnly: true` skips the parent walk — needed when a tool reads the\n // local tsconfig directly (shadcn does this for import-alias detection).\n const exists = opts.localOnly\n ? await this.fs.exists(this.fs.join(root, \"tsconfig.json\"))\n : await this.existsInParents(root, \"tsconfig.json\");\n if (!opts.force && exists) {\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 `.vscode/settings.json` exists, pointing the editor's TypeScript\n * language server at the `typescript` copy embedded in `alepha`. Keeps the\n * IDE on the same compiler version as `alepha typecheck` — see\n * `vscodeSettingsJson`.\n */\n public async ensureVscodeSettings(\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, \".vscode\"))\n ) {\n return;\n }\n const target = this.fs.join(root, \".vscode\", \"settings.json\");\n if (!opts.force && (await this.fs.exists(target))) {\n return;\n }\n await this.fs.mkdir(this.fs.join(root, \".vscode\"), { recursive: true });\n await this.fs.writeFile(target, vscodeSettingsJson());\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 /**\n * Ensure AGENTS.md (cross-tool standard, canonical source) exists, with a\n * CLAUDE.md stub that imports it via Claude Code's `@` syntax. Single\n * source of truth, cross-platform, no symlink needed.\n */\n public async ensureAgentMd(\n root: string,\n options: { force?: boolean } = {},\n ): Promise<void> {\n await Promise.all([\n this.ensureFile(root, \"AGENTS.md\", agentMd(), options.force),\n this.ensureFile(root, \"CLAUDE.md\", \"@AGENTS.md\\n\", options.force),\n ]);\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: { saas?: boolean; 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, saas: opts.saas }),\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 if (opts.saas) {\n await this.fs.mkdir(this.fs.join(root, \"src/api/providers\"), {\n recursive: true,\n });\n await this.ensureFile(\n root,\n \"src/api/providers/RealmProvider.ts\",\n saasRealmProviderTs(),\n opts.force,\n );\n // Seed the admin email into .env (gitignored) — never into source.\n // Detected from `git config user.email`; neutral fallback otherwise.\n const adminEmail = (await this.detectGitEmail()) ?? \"admin@alepha.dev\";\n await this.ensureFile(\n root,\n \".env\",\n `ADMIN_EMAILS=${adminEmail}\\n`,\n opts.force,\n );\n }\n }\n\n /**\n * Best-effort lookup for the developer's git email — seeded as\n * `ADMIN_EMAILS` in the SaaS project's `.env`. Returns undefined if git\n * isn't available or `user.email` isn't configured; the caller then falls\n * back to the neutral `admin@alepha.dev`.\n */\n protected async detectGitEmail(): Promise<string | undefined> {\n try {\n const stdout = (await this.shell.run(\"git config --get user.email\", {\n capture: true,\n })) as unknown as string;\n const email = (stdout ?? \"\").trim();\n if (!email || !email.includes(\"@\")) return undefined;\n return email;\n } catch {\n return undefined;\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 tailwind?: boolean;\n shadcn?: boolean;\n saas?: 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 if (opts.saas) {\n await this.fs.mkdir(this.fs.join(root, \"src/web/components/auth\"), {\n recursive: true,\n });\n await this.fs.mkdir(this.fs.join(root, \"src/web/components/admin\"), {\n recursive: true,\n });\n }\n\n // public/favicon.svg\n await this.fs.mkdir(this.fs.join(root, \"public\"), { recursive: true });\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({ 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 // shadcn/ui: write components.json before running `shadcn init` — the\n // CLI respects an existing config and skips its interactive prompts,\n // which lets us pin our aliases (`@/web/*`) and the `@alepha` registry.\n // The CLI itself writes the cn() helper, theme tokens, and installs\n // runtime deps (clsx, tailwind-merge, class-variance-authority,\n // lucide-react, tw-animate-css) — see runShadcnInit below.\n if (opts.shadcn) {\n await this.ensureFile(\n root,\n \"components.json\",\n componentsJsonTs(),\n opts.force,\n );\n }\n\n // Web structure\n await this.ensureFile(\n root,\n \"src/web/index.ts\",\n webIndexTs({ appName, saas: opts.saas }),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/AppRouter.ts\",\n webAppRouterTs({ api: opts.api, saas: opts.saas }),\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 await this.ensureFile(\n root,\n \"src/main.browser.ts\",\n mainBrowserTs(),\n opts.force,\n );\n\n if (opts.saas) {\n // Auth — layout + 4 pages, each a thin wrapper around the registry\n // component that `shadcn add @alepha/auth-*` drops at\n // src/web/components/auth-*.tsx.\n await this.ensureFile(\n root,\n \"src/web/components/auth/AuthLayout.tsx\",\n saasAuthLayoutTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/auth/Login.tsx\",\n saasAuthLoginTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/auth/Register.tsx\",\n saasAuthRegisterTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/auth/ResetPassword.tsx\",\n saasAuthResetPasswordTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/auth/VerifyEmail.tsx\",\n saasAuthVerifyEmailTsx(),\n opts.force,\n );\n\n // Admin — AppShell layout + 5 admin-* pages\n await this.ensureFile(\n root,\n \"src/web/components/admin/AdminLayout.tsx\",\n saasAdminLayoutTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/admin/Users.tsx\",\n saasAdminUsersTsx(),\n opts.force,\n );\n await this.ensureFile(\n root,\n \"src/web/components/admin/Sessions.tsx\",\n saasAdminSessionsTsx(),\n opts.force,\n );\n }\n }\n\n // ===========================================\n // Test Directory\n // ===========================================\n\n /**\n * Ensure test directory exists with a dummy test file + a self-contained\n * `vitest.config.ts`. Pinning `test.root` prevents Vitest from walking up\n * to a parent monorepo config (e.g. one that boots a Postgres container).\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 const vitestConfigPath = this.fs.join(root, \"vitest.config.ts\");\n\n if (!(await this.fs.exists(vitestConfigPath))) {\n await this.fs.writeFile(vitestConfigPath, vitestConfigTs());\n }\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 tailwind?: boolean;\n /** boolean toggle, or a string preset id (default `b0` when bare). */\n shadcn?: boolean | string;\n /** boolean toggle, or a string preset id (default `b0` when bare). */\n saas?: boolean | string;\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 // `--shadcn` / `--saas` are union flags: bare → true, string → preset.\n // Capture the preset string (default `b0`), then normalize both flags\n // to plain booleans so the rest of the pipeline keeps its boolean\n // contract with PackageManagerUtils + ensureWebProject etc.\n const shadcnPreset =\n (typeof flags.saas === \"string\" && flags.saas) ||\n (typeof flags.shadcn === \"string\" && flags.shadcn) ||\n \"b0\";\n\n // Cast to a narrower view so downstream sees pure booleans.\n const f = flags as Omit<typeof flags, \"shadcn\" | \"saas\"> & {\n shadcn?: boolean;\n saas?: boolean;\n };\n f.shadcn = !!flags.shadcn;\n f.saas = !!flags.saas;\n\n // Flag cascading:\n // --saas → --shadcn + --api\n // --shadcn → --tailwind\n // --tailwind→ --react\n if (f.saas) {\n f.shadcn = true;\n f.api = true;\n }\n if (f.shadcn) {\n f.tailwind = 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.api || flags.react || flags.tailwind || flags.shadcn || flags.saas;\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 // Always emit both AGENTS.md and CLAUDE.md at project roots (skip for\n // monorepo sub-packages where agent files live at workspace root).\n const writeAgentMd = !workspace.isPackage;\n\n const isExpo = await this.pm.hasExpo(root);\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: { ...f, isPackage: workspace.isPackage },\n // Skip workspace-level configs if they exist at workspace root —\n // unless --shadcn is set: the shadcn CLI reads the local\n // tsconfig.json directly to detect import aliases (it doesn't\n // follow `extends`), so we must ensure one exists in the package.\n tsconfigJson: f.shadcn ? \"local\" : !workspace.config.tsconfigJson,\n biomeJson: true,\n editorconfig: !workspace.config.editorconfig,\n agentMd: writeAgentMd,\n // Editor TS-server pointer at a project root only; monorepo\n // sub-packages inherit the workspace-root `.vscode/`.\n vscodeSettings: writeAgentMd,\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, { saas: !!flags.saas, force });\n }\n if (flags.react && !isExpo) {\n await this.ensureWebProject(root, {\n api: !!flags.api,\n tailwind: !!flags.tailwind,\n shadcn: !!flags.shadcn,\n saas: !!flags.saas,\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 // Always scaffold the test setup — Vitest ships embedded in `alepha`, so\n // `alepha test` works in every project. The dummy spec doubles as a\n // worked example for both humans and AI agents.\n await this.ensureTestDir(root);\n\n // shadcn/ui: run `<pm> shadcn init` against the components.json we wrote\n // earlier. shadcn detects the existing config, respects our aliases,\n // injects theme tokens into src/main.css, writes src/web/lib/utils.ts,\n // and installs runtime deps (clsx, tailwind-merge, etc.).\n //\n // Flags chosen to keep this fully non-interactive:\n // --yes skip confirmation prompts (default in shadcn v4 but\n // passed explicitly so older versions also behave)\n // --no-monorepo skip the monorepo prompt — we ship a single-app\n // layout; users opt into monorepo via `--monorepo`\n // on the alepha side later\n //\n // We deliberately do NOT pass `--defaults` (would force Next.js +\n // base-nova preset) or `--template` (only applies to scratch projects;\n // ours already has main.server.ts / main.browser.ts).\n // Each PM has a different way to exec a project-local binary.\n const exec = pmExecPrefix(pmName);\n\n if (flags.shadcn) {\n // Fully non-interactive shadcn init. The `--preset` arg is what makes\n // this work — without it shadcn falls back to interactive prompts even\n // with --yes/--force. Defaults: vite template + radix base + reinstall\n // (so the components.json we pre-wrote stays canonical).\n await run(\n `${exec} shadcn init --no-monorepo --base radix -t vite --yes --force --reinstall --preset ${escapeShellArg(shadcnPreset)}`,\n { alias: `running shadcn init (preset ${shadcnPreset})`, root },\n );\n // Re-pin our aliases + alepha registry — `shadcn init --force`\n // overwrites components.json with the template defaults.\n await this.fs.writeFile(\n this.fs.join(root, \"components.json\"),\n componentsJsonTs(),\n );\n }\n\n // SaaS preset: pull in the auth + admin registry components from the\n // public alepha registry (already wired via components.json's\n // `registries: { \"@alepha\": \"https://alepha.dev/r/{name}.json\" }`).\n // Each `shadcn add` writes the component into src/web/components/* and\n // pulls its peer primitives + dependencies (sonner, etc.).\n if (flags.saas) {\n // Pull the public SaaS bundle in one shot — it aggregates control,\n // auto-form, alepha-table, use-dialog, app-shell, every auth-*, and\n // every admin-* block. Definition lives at\n // https://alepha.dev/r/saas.json (see @alepha/ui-registry).\n // `--yes --overwrite` is the only combo that works non-interactively\n // when registry items would replace files we pre-wrote (auth-login etc.\n // overlap with shadcn primitives like button/input).\n await run(`${exec} shadcn add @alepha/saas --yes --overwrite`, {\n alias: \"adding alepha saas registry bundle\",\n root,\n });\n }\n\n // Best-effort lint: shadcn-imported registry components occasionally\n // trip biome rules (e.g. noArrayIndexKey on a Fragment loop). The user\n // can fix or silence these later — don't block the whole init.\n try {\n await run(`${pmName} run lint`, {\n alias: \"running linter\",\n root,\n });\n } catch (err) {\n this.log.warn(\n \"Linter reported issues during init — continuing. Run `lint` again later to inspect.\",\n { error: err instanceof Error ? err.message : String(err) },\n );\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 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\n/**\n * Map a package manager name to the command that runs a project-local binary.\n *\n * - npm: `npx`\n * - yarn: `yarn` (yarn auto-resolves binary names; `yarn shadcn ...` works)\n * - pnpm: `pnpm exec`\n * - bun: `bunx`\n *\n * Used to invoke `shadcn init` / `shadcn add` regardless of the user's PM —\n * `npm shadcn ...` is invalid (it tries to run a script named `shadcn`).\n */\n/** Quote a value so it survives shell parsing. */\nconst escapeShellArg = (value: string): string => {\n if (/^[A-Za-z0-9_./@:-]+$/.test(value)) return value;\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n};\n\nconst pmExecPrefix = (pmName: string): string => {\n switch (pmName) {\n case \"npm\":\n return \"npx\";\n case \"pnpm\":\n return \"pnpm exec\";\n case \"bun\":\n return \"bunx\";\n default:\n return \"yarn\";\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 * Skip the slow build steps (Vite client + Vite server + asset\n * compression). Only runs the deploy-config generation\n * (wrangler.jsonc, etc.) — useful when the caller already has a\n * built `dist/` and just needs the wrangler config refreshed for\n * per-tenant overrides.\n */\n prebuilt?: boolean;\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 if (ctx.flags?.prebuilt) {\n return;\n }\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.flags?.prebuilt) {\n return;\n }\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 pwa: !!ctx.options.pwa,\n });\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 { $container, type ContainerPrimitive } from \"alepha/containers\";\nimport { EmailProvider } from \"alepha/email\";\nimport {\n CloudflareEmailProvider,\n SEND_EMAIL_DEFAULT_BINDING,\n} from \"alepha/email/cloudflare\";\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 wrangler.observability ??= {\n enabled: true,\n head_sampling_rate: 1,\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 this.enhanceEmail(ctx, wrangler);\n const containers = this.enhanceContainers(ctx, 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, containers);\n }\n\n protected enhanceDomain(wrangler: WranglerConfig): void {\n const domain = process.env.CLOUDFLARE_DOMAIN;\n if (!domain) {\n return;\n }\n\n if (domain.includes(\"*\")) {\n const zone = process.env.CLOUDFLARE_ZONE;\n if (!zone) {\n throw new Error(\n `Wildcard domain \"${domain}\" requires CLOUDFLARE_ZONE to be set (the parent zone name, e.g. \"alepha.dev\").`,\n );\n }\n wrangler.routes = [\n {\n pattern: domain.endsWith(\"/*\") ? domain : `${domain}/*`,\n zone_name: zone,\n },\n ];\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 const jurisdiction = process.env.CLOUDFLARE_JURISDICTION;\n wrangler.d1_databases = wrangler.d1_databases || [];\n wrangler.d1_databases.push({\n binding,\n database_name: dbName,\n database_id: id,\n ...(jurisdiction ? { jurisdiction } : {}),\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 const jurisdiction = process.env.CLOUDFLARE_JURISDICTION;\n wrangler.r2_buckets = wrangler.r2_buckets || [];\n wrangler.r2_buckets.push({\n binding: bucketName,\n bucket_name: bucketName,\n ...(jurisdiction ? { jurisdiction } : {}),\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 enhanceEmail(\n ctx: BuildTaskContext,\n wrangler: WranglerConfig,\n ): void {\n let provider: EmailProvider | undefined;\n try {\n provider = ctx.alepha.inject(EmailProvider);\n } catch {\n return;\n }\n\n if (!(provider instanceof CloudflareEmailProvider)) {\n return;\n }\n\n wrangler.send_email = wrangler.send_email || [];\n if (\n wrangler.send_email.some(\n (b: { name: string }) => b.name === SEND_EMAIL_DEFAULT_BINDING,\n )\n ) {\n return;\n }\n\n const entry: Record<string, unknown> = { name: SEND_EMAIL_DEFAULT_BINDING };\n const destination = process.env.EMAIL_FROM;\n if (destination) {\n entry.destination_address = destination;\n }\n\n wrangler.send_email.push(entry);\n }\n\n /**\n * Discover `$container` primitives and emit the matching Cloudflare\n * Containers bindings, Durable Object bindings, and migrations into\n * `wrangler.jsonc`. The DO class declarations are added later, when\n * the worker entry point is written.\n *\n * Returns the list of container descriptors so\n * `writeWorkerEntryPoint` can emit `export class <NAME> extends\n * Container` declarations referencing them.\n */\n protected enhanceContainers(\n ctx: BuildTaskContext,\n wrangler: WranglerConfig,\n ): ContainerDescriptor[] {\n const primitives = ctx.alepha.primitives(\n $container,\n ) as ContainerPrimitive[];\n if (primitives.length === 0) {\n return [];\n }\n\n const descriptors: ContainerDescriptor[] = primitives.map((p) => ({\n name: p.name.toUpperCase(),\n className: p.name\n .split(/[^a-zA-Z0-9]/)\n .filter(Boolean)\n .map((s) => s[0]!.toUpperCase() + s.slice(1))\n .join(\"\"),\n image: p.options.image,\n port: p.options.port ?? 3000,\n sleepAfter:\n typeof p.options.sleepAfter === \"string\" ? p.options.sleepAfter : \"15m\",\n instanceType: p.options.instanceType ?? \"dev\",\n maxInstances: p.options.maxInstances ?? 5,\n envVars: p.options.envVars,\n }));\n\n wrangler.containers = wrangler.containers || [];\n wrangler.durable_objects = wrangler.durable_objects || {};\n wrangler.durable_objects.bindings = wrangler.durable_objects.bindings || [];\n wrangler.migrations = wrangler.migrations || [];\n\n const newSqliteClasses: string[] = [];\n for (const d of descriptors) {\n wrangler.containers.push({\n class_name: d.className,\n image: d.image,\n instance_type: d.instanceType,\n max_instances: d.maxInstances,\n });\n wrangler.durable_objects.bindings.push({\n name: d.name,\n class_name: d.className,\n });\n newSqliteClasses.push(d.className);\n }\n\n if (newSqliteClasses.length > 0) {\n wrangler.migrations.push({\n tag: \"containers-v1\",\n new_sqlite_classes: newSqliteClasses,\n });\n }\n\n return descriptors;\n }\n\n protected async writeWorkerEntryPoint(\n root: string,\n distDir: string,\n containers: ContainerDescriptor[] = [],\n ): Promise<void> {\n const containerDeclarations = containers\n .map((c) => {\n const envVars = c.envVars\n ? ` envVars = ${JSON.stringify(c.envVars)};\\n`\n : \"\";\n return `export class ${c.className} extends Container {\\n defaultPort = ${c.port};\\n sleepAfter = \"${c.sleepAfter}\";\\n${envVars}}`;\n })\n .join(\"\\n\\n\");\n\n const containerImport =\n containers.length > 0\n ? `import { Container } from \"@cloudflare/containers\";\\n\\n${containerDeclarations}\\n\\n`\n : \"\";\n\n const workerCode = `\nimport \"./index.js\";\n\n// Stash the per-invocation \\`executionCtx.waitUntil\\` in the Alepha store\n// so background work (notably $job direct dispatch) can keep the isolate\n// alive past the response.\nconst setWaitUntil = (executionCtx) => {\n if (executionCtx && typeof executionCtx.waitUntil === \"function\") {\n __alepha.set(\"cloudflare.waitUntil\", (p) => executionCtx.waitUntil(p));\n } else {\n __alepha.set(\"cloudflare.waitUntil\", undefined);\n }\n};\n\nexport default {\n fetch: async (request, env, executionCtx) => {\n const ctx = { req: request, res: undefined };\n\n __alepha.set(\"cloudflare.env\", env);\n setWaitUntil(executionCtx);\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, executionCtx) => {\n __alepha.set(\"cloudflare.env\", env);\n setWaitUntil(executionCtx);\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, executionCtx) => {\n __alepha.set(\"cloudflare.env\", env);\n setWaitUntil(executionCtx);\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${containerImport}${workerCode}`.trim(),\n );\n }\n}\n\ninterface ContainerDescriptor {\n name: string;\n className: string;\n image: string;\n port: number;\n sleepAfter: string;\n instanceType: \"dev\" | \"basic\" | \"standard\";\n maxInstances: number;\n envVars?: Record<string, string>;\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.flags?.prebuilt) {\n return;\n }\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 * Resolved compile options after merging config + flag defaults.\n */\ninterface ResolvedCompile {\n target: string;\n base: string;\n minify: boolean;\n}\n\n/**\n * Generate Docker deployment configuration and optionally build the image.\n *\n * Two modes:\n *\n * 1. Standard (default) - copies the bundled JS + `package.json` and runs\n * `bun install` (or `npm install`) inside the container.\n * 2. Compile - runs `bun build --compile` to produce a single static binary\n * and packages it inside a minimal distroless image. No `node_modules`\n * are ever installed; all dependencies must be bundled by Vite. Requires\n * `runtime: \"bun\"`.\n *\n * Creates:\n * - Dockerfile (compile or standard variant)\n * - Copies migrations directory if it exists\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 const compile = this.resolveCompile(ctx);\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 if (compile) {\n await ctx.run({\n name: \"assert no externals (compile mode)\",\n handler: async () => {\n await this.assertNoExternals(ctx.root, distDir);\n },\n });\n\n await ctx.run(this.buildCompileCommand(compile), {\n alias: `bun build --compile (${compile.target})`,\n root: this.fs.join(ctx.root, distDir),\n });\n\n await ctx.run({\n name: \"cleanup pre-compile artifacts\",\n handler: async () => {\n await this.cleanupPreCompileArtifacts(ctx.root, distDir);\n },\n });\n }\n\n await ctx.run({\n name: \"generate deploy config (docker)\",\n handler: async () => {\n const migrationsCopied = await this.copyMigrations(ctx.root, distDir);\n await this.writeDockerfile(ctx.root, distDir, {\n compile,\n standard: { image: dockerFrom, command: dockerCommand },\n hasMigrations: migrationsCopied,\n install: ctx.options.docker?.install ?? [],\n });\n },\n });\n\n if (ctx.flags?.image) {\n await this.buildDockerImage(ctx, distDir);\n }\n }\n\n /**\n * Merge the user-supplied compile config with sensible defaults.\n * Returns null when compile mode is disabled.\n */\n protected resolveCompile(ctx: BuildTaskContext): ResolvedCompile | null {\n const raw = ctx.options.docker?.compile;\n if (!raw) {\n return null;\n }\n\n if (ctx.options.runtime !== \"bun\") {\n throw new AlephaError(\n `Compile mode requires runtime 'bun', got '${ctx.options.runtime}'`,\n );\n }\n\n const config = typeof raw === \"object\" ? raw : {};\n\n return {\n target: config.target ?? this.defaultBunTarget(),\n base: config.base ?? \"gcr.io/distroless/static-debian12\",\n minify: config.minify ?? true,\n };\n }\n\n /**\n * Resolve the default Bun target triple for the current host arch.\n * Always targets linux-musl (the container OS), regardless of build host.\n */\n protected defaultBunTarget(): string {\n switch (process.arch) {\n case \"x64\":\n return \"bun-linux-x64-musl\";\n case \"arm64\":\n return \"bun-linux-arm64-musl\";\n default:\n throw new AlephaError(\n `No bun linux-musl target available for host arch '${process.arch}'. ` +\n \"Set `build.docker.compile.target` explicitly.\",\n );\n }\n }\n\n /**\n * Build the `bun build --compile` invocation. Runs from `<root>/<dist>` so\n * the entry path stays relative and the output lands next to the migrations.\n */\n protected buildCompileCommand(compile: ResolvedCompile): string {\n const parts = [\n \"bun build\",\n \"--compile\",\n `--target=${compile.target}`,\n compile.minify ? \"--minify\" : \"\",\n \"--outfile=app\",\n \"index.js\",\n ].filter(Boolean);\n return parts.join(\" \");\n }\n\n /**\n * Compile mode requires fully-bundled output. If Vite left anything in\n * `dist/package.json`'s `dependencies`, fail loudly so the user can\n * either bundle the dep or disable compile.\n */\n protected async assertNoExternals(\n root: string,\n distDir: string,\n ): Promise<void> {\n const pkgPath = this.fs.join(root, distDir, \"package.json\");\n if (!(await this.fs.exists(pkgPath))) {\n return;\n }\n let pkg: { dependencies?: Record<string, string> };\n try {\n pkg = JSON.parse((await this.fs.readFile(pkgPath)).toString());\n } catch {\n return;\n }\n const deps = pkg.dependencies ?? {};\n const names = Object.keys(deps);\n if (names.length > 0) {\n throw new AlephaError(\n `Cannot use compile mode: the following dependencies were not bundled by Vite: ${names.join(\", \")}. ` +\n \"All dependencies must be bundleable to produce a single-binary build.\",\n );\n }\n }\n\n /**\n * Remove artifacts that are no longer needed once the binary exists.\n * The binary embeds the JS bundle and runtime; the standalone files\n * would just bloat the image.\n */\n protected async cleanupPreCompileArtifacts(\n root: string,\n distDir: string,\n ): Promise<void> {\n const targets = [\n this.fs.join(root, distDir, \"server\"),\n this.fs.join(root, distDir, \"index.js\"),\n this.fs.join(root, distDir, \"package.json\"),\n ];\n for (const target of targets) {\n if (await this.fs.exists(target)) {\n await this.fs.rm(target, { recursive: true });\n }\n }\n }\n\n protected async copyMigrations(\n root: string,\n distDir: string,\n ): Promise<boolean> {\n const migrationsDir = this.fs.join(root, \"migrations\");\n if (await this.fs.exists(migrationsDir)) {\n await this.fs.cp(\n migrationsDir,\n this.fs.join(root, distDir, \"migrations\"),\n );\n return true;\n }\n return false;\n }\n\n protected async writeDockerfile(\n root: string,\n distDir: string,\n opts: {\n compile: ResolvedCompile | null;\n standard: { image: string; command: string };\n hasMigrations: boolean;\n install: string[];\n },\n ): Promise<void> {\n const header =\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 const migrationsLine = opts.hasMigrations\n ? \"COPY migrations ./migrations\\n\"\n : \"\";\n\n let dockerfile: string;\n\n if (opts.compile) {\n // `install` is ignored in compile mode — distroless has no npm.\n dockerfile = `${header}FROM ${opts.compile.base}\nWORKDIR /app\n\nCOPY app .\n${migrationsLine}\nENV SERVER_HOST=0.0.0.0\n\nENTRYPOINT [\"/app/app\"]\n`;\n } else {\n const { image, command } = opts.standard;\n // Install requested packages locally (no --global). They land in\n // `/app/node_modules/`, alongside the app's own deps. Use\n // `--no-save` so we don't mutate the bundled package.json. Node\n // module resolution walks up into `/app/node_modules/` when the\n // workspace lives under `/app/workspace/<deploy-id>/`.\n const installLine = opts.install.length\n ? `RUN npm install --no-save --no-fund --no-audit ${opts.install.join(\" \")}\\n`\n : \"\";\n dockerfile = `${header}FROM ${image}\nWORKDIR /app\n\nCOPY . .\n\nRUN ${command === \"bun\" ? \"bun\" : \"npm\"} install\n${installLine}\nENV SERVER_HOST=0.0.0.0\n\nCMD [\"${command}\", \"index.js\"]\n`;\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.flags?.prebuilt) {\n return;\n }\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 { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate PWA web app manifest.\n *\n * Produces a `manifest.webmanifest` in the public output directory\n * from the `pwa` section of build options. Detects icons from `public/`.\n */\nexport class BuildPwaTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.flags?.prebuilt) {\n return;\n }\n const pwa = ctx.options.pwa;\n if (!pwa || !ctx.hasClient) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const outputDir = this.fs.join(ctx.root, distDir, publicDir);\n\n await ctx.run({\n name: \"generate pwa manifest\",\n handler: async () => {\n const icons = await this.detectIcons(outputDir);\n\n const manifest: Record<string, unknown> = {\n name: pwa.name,\n short_name: pwa.shortName ?? pwa.name,\n start_url: \"/\",\n display: pwa.display ?? \"standalone\",\n theme_color: pwa.themeColor ?? \"#ffffff\",\n background_color: pwa.backgroundColor ?? \"#ffffff\",\n };\n\n if (icons.length > 0) {\n manifest.icons = icons;\n }\n\n const output = this.fs.join(outputDir, \"manifest.webmanifest\");\n await this.fs.writeFile(output, JSON.stringify(manifest, null, 2));\n },\n });\n }\n\n /**\n * Detect icon files in the public output directory.\n *\n * Looks for common icon filenames and generates\n * manifest icon entries with appropriate sizes and types.\n */\n protected async detectIcons(\n publicDir: string,\n ): Promise<Array<{ src: string; sizes: string; type: string }>> {\n const icons: Array<{ src: string; sizes: string; type: string }> = [];\n\n const candidates: Array<{\n file: string;\n sizes: string;\n type: string;\n }> = [\n { file: \"icon-192.png\", sizes: \"192x192\", type: \"image/png\" },\n { file: \"icon-512.png\", sizes: \"512x512\", type: \"image/png\" },\n { file: \"icon.svg\", sizes: \"any\", type: \"image/svg+xml\" },\n ];\n\n for (const candidate of candidates) {\n if (await this.fs.exists(this.fs.join(publicDir, candidate.file))) {\n icons.push({\n src: `/${candidate.file}`,\n sizes: candidate.sizes,\n type: candidate.type,\n });\n }\n }\n\n return icons;\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 if (ctx.flags?.prebuilt) {\n return;\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 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 codeSplitting: {\n groups: [\n {\n name: \"react\",\n test: /node_modules\\/react(\\/|-dom\\/)/,\n },\n ],\n },\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 const path: string = options.path ?? \"\";\n if (options.children) {\n return false;\n }\n if (path.includes(\"*\")) {\n return false;\n }\n if (path === \"/404\") {\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 type { CronProvider } from \"alepha/scheduler\";\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(\n outputDir,\n ctx.options.vercel?.config,\n this.collectCronJobs(ctx),\n );\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 * Collect every registered `$scheduler` / `$job({ cron })` and turn it\n * into a Vercel Cron entry. Vercel hits `path` on the configured\n * `schedule`; the entry-point handler routes that to a `serverless:cron`\n * event so `CronProvider` runs the matching job in-process.\n *\n * Mirrors the equivalent in `BuildCloudflareTask.enhanceCron`, except\n * Vercel needs one path per job (it doesn't dispatch by cron expression\n * the way Cloudflare does).\n */\n protected collectCronJobs(\n ctx: BuildTaskContext,\n ): { path: string; schedule: string }[] {\n if (ctx.alepha.primitives(\"scheduler\").length === 0) {\n // `$job` registers cron jobs through the same provider, so the\n // primitives count covers both `$scheduler` and `$job({ cron })`.\n }\n\n let cronProvider: CronProvider | undefined;\n try {\n cronProvider = ctx.alepha.inject(\"CronProvider\") as CronProvider;\n } catch {}\n\n const jobs = cronProvider?.getCronJobs();\n if (!jobs || jobs.length === 0) {\n return [];\n }\n\n return jobs.map((job) => ({\n path: `/_alepha/cron/${encodeURIComponent(job.name)}`,\n schedule: job.expression,\n }));\n }\n\n /**\n * Write .vercel/output/config.json with Build Output API v3 format.\n *\n * `userCrons` are merged with auto-collected `$scheduler` / `$job({ cron })`\n * entries — explicit user config wins on conflicting paths.\n */\n protected async writeOutputConfig(\n outputDir: string,\n config?: { crons?: { path: string; schedule: string }[] },\n autoCrons: { 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 const merged = new Map<string, { path: string; schedule: string }>();\n for (const c of autoCrons) merged.set(c.path, c);\n for (const c of config?.crons ?? []) merged.set(c.path, c);\n const crons = [...merged.values()];\n if (crons.length > 0) {\n outputConfig.crons = 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\nconst CRON_PREFIX = \"/_alepha/cron/\";\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 // Vercel Cron triggers are HTTP GETs to a configured path. We route them\n // to the CronProvider via an event so the same job declaration works on\n // Vercel, Cloudflare, and long-running Node alike. Vercel signs cron\n // requests with \\`Authorization: Bearer \\${CRON_SECRET}\\`; the secret is\n // available as \\`process.env.CRON_SECRET\\`. When set, we require the\n // header to match before triggering.\n const url = req.url || \"\";\n if (url.startsWith(CRON_PREFIX)) {\n const expected = process.env.CRON_SECRET;\n if (expected) {\n const got = (req.headers?.authorization || \"\").replace(/^Bearer\\\\s+/i, \"\");\n if (got !== expected) {\n res.writeHead(401, { \"content-type\": \"text/plain\" });\n res.end(\"Unauthorized\");\n return;\n }\n }\n const name = decodeURIComponent(url.slice(CRON_PREFIX.length).split(\"?\")[0]);\n try {\n await __alepha.events.emit(\"serverless:cron\", { name });\n res.writeHead(200, { \"content-type\": \"text/plain\" });\n res.end(\"ok\");\n } catch (err) {\n __alepha.log.error(\\`Cron trigger '\\${name}' failed\\`, err);\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"cron failed\");\n }\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 { BuildPwaTask } from \"../tasks/BuildPwaTask.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(BuildPwaTask),\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 compile: t.optional(\n t.boolean({\n aliases: [\"c\"],\n description:\n \"Compile server to a single static binary (requires --target=docker --runtime=bun)\",\n }),\n ),\n prebuilt: t.optional(\n t.boolean({\n description:\n \"Skip the bundle steps (Vite client/server + asset compression). Only regenerates target-specific deploy config (e.g. wrangler.jsonc). Use when `dist/` is already built and you just need the config refreshed.\",\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.compile !== undefined && {\n docker: {\n ...current.docker,\n compile: flags.compile ? (current.docker?.compile ?? true) : false,\n },\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 // Prebuilt mode: skip clean + Vite builds + asset compression; only\n // regenerate target-specific deploy config (e.g. wrangler.jsonc).\n // Used by external orchestrators (Rocket) that ship a pre-built\n // dist/ and just need the config refreshed for per-tenant overrides.\n if (!flags.prebuilt) {\n await run.rm(distDir, { alias: \"clean dist\" });\n }\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 // Validate --compile requires --target=docker --runtime=bun\n if (options.docker?.compile) {\n if (target !== \"docker\") {\n throw new AlephaError(\n `Compile mode requires '--target=docker', got '${target ?? \"bare\"}'`,\n );\n }\n if (options.runtime !== \"bun\") {\n throw new AlephaError(\n `Compile mode requires '--runtime=bun', got '${options.runtime}'`,\n );\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, prebuilt: flags.prebuilt },\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 // drizzle-kit ships embedded in `alepha` — resolve and run it from\n // alepha's own install, so the project never declares it.\n // `global: true` because the command starts with `node` (a system\n // binary) — without it, exec tries to resolve `node` as a\n // node_modules bin and fails.\n const drizzleKit = this.utils.resolveBin(\"drizzle-kit\");\n await this.utils.exec(\n `node \"${drizzleKit}\" ${options.command} --config=${drizzleConfigJsPath}${flags}`,\n {\n global: true,\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(`<script type=\"module\">import \"/${style}\";</script>`);\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 tailwind: t.optional(\n t.boolean({\n description: \"Include Tailwind CSS with Vite plugin. Implies --react\",\n }),\n ),\n shadcn: t.optional(\n t.union([t.boolean(), t.text()], {\n description:\n \"Set up shadcn/ui (components.json, cn helper, theme tokens, alepha registry). Pass an optional preset id (default: b0). Implies --react and --tailwind\",\n }),\n ),\n saas: t.optional(\n t.union([t.boolean(), t.text()], {\n description:\n \"Scaffold a SaaS starter: auth (login/register/reset/verify) + admin panel (/admin AppShell with users/sessions/api-keys/parameters/audits). Pass an optional preset id (default: b0). Implies --shadcn and --api\",\n }),\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 { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class LintCommand {\n protected readonly utils = $inject(AlephaCliUtils);\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 // Biome ships embedded in `alepha` — resolve and run it from alepha's\n // own install, so the project never declares it.\n const biome = this.utils.resolveBin(\"@biomejs/biome\", \"biome\");\n await run(`node \"${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 \"../alephaPackageJson.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 { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TestCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly test = $command({\n name: \"test\",\n description:\n \"Run tests using Vitest. Pass a filter to run only matching specs, e.g. `alepha test user` or `alepha test test/auth.spec.ts`\",\n args: t.optional(\n t.text({\n title: \"filter\",\n description: \"Only run spec files whose path matches this string\",\n }),\n ),\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, args }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const config = flags.config ? `--config=${flags.config}` : \"\";\n\n // The positional arg is forwarded to Vitest as a filename filter —\n // `alepha test user` runs only specs whose path matches \"user\".\n const filter = args ? JSON.stringify(args) : \"\";\n\n // Vitest ships embedded in `alepha` (paired with vite) — resolve and\n // run it from alepha's own install, so the project never declares it.\n const vitest = this.utils.resolveBin(\"vitest\", \"vitest\");\n await run(\n `node \"${vitest}\" run ${config} ${filter} ${env.VITEST_ARGS}`\n .replace(/\\s+/g, \" \")\n .trim(),\n );\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TypecheckCommand {\n protected readonly utils = $inject(AlephaCliUtils);\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 // TypeScript ships embedded in `alepha` — resolve and run its `tsc`\n // from alepha's own install, so the project never declares it.\n const tsc = this.utils.resolveBin(\"typescript\", \"tsc\");\n await run(`node \"${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 a `test/` directory exists)\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 // Vitest ships embedded in `alepha`, so it's no longer a project\n // dependency — gate on the presence of a `test/` directory instead.\n if (await this.utils.exists(root, \"test\")) {\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 \"./alephaPackageJson.ts\";\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\";\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,M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;;;;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":["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","../../../src/cli/core/alephaPackageJson.ts","../../../src/cli/core/services/PackageManagerUtils.ts","../../../src/cli/core/templates/agentMd.ts","../../../src/cli/core/templates/alephaConfigTs.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/logoSvg.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/vitestConfigTs.ts","../../../src/cli/core/templates/vscodeSettingsJson.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/BuildPwaTask.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/pack.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 * Extra packages to install globally in the generated image.\n *\n * Each entry becomes a `RUN npm install --global --no-fund\n * --no-audit <pkg> …` line inserted after `FROM` and before the\n * app `COPY`. Use it for CLI tools the running app shells out to\n * — typical example is `wrangler` for a service that deploys to\n * Cloudflare on someone else's behalf.\n *\n * Ignored in `compile` mode (the distroless base has no `npm`).\n *\n * @example install: [\"wrangler\"]\n */\n install: t.optional(t.array(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 * Compile the server entry to a single static binary using\n * `bun build --compile`, then package it inside a minimal base image\n * (distroless by default). Requires `runtime: \"bun\"`.\n *\n * When enabled:\n * - the binary is produced at `<dist>/app` and the original `dist/server/`,\n * `dist/index.js` and `dist/package.json` are removed\n * - the generated Dockerfile uses a distroless base image and does not\n * run `bun install` (everything is embedded in the binary)\n * - any non-empty `dependencies` in the externals manifest causes the\n * task to fail loudly (compile requires fully-bundled output)\n *\n * Pass `true` to enable with defaults, or an object to override.\n */\n compile: t.optional(\n t.union([\n t.boolean(),\n t.object({\n /**\n * Bun target triple, e.g. `bun-linux-x64-musl`,\n * `bun-linux-arm64-musl`, or `bun-linux-x64-modern-musl`\n * (AVX2 required).\n *\n * @default derived from host arch — always linux-musl.\n */\n target: t.optional(t.string()),\n\n /**\n * Base image for the generated Dockerfile.\n *\n * @default \"gcr.io/distroless/static-debian12\"\n */\n base: t.optional(t.string()),\n\n /**\n * Minify the compiled output.\n *\n * @default true\n */\n minify: t.optional(t.boolean()),\n }),\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 * PWA (Progressive Web App) configuration.\n *\n * Generates a web app manifest and enables installability.\n * Requires a client-side bundle (React).\n */\n pwa: t.optional(\n t.object({\n /**\n * Full application name displayed on the splash screen\n * and in the OS app switcher.\n */\n name: t.string(),\n\n /**\n * Short name displayed on the home screen icon.\n * Falls back to `name` if omitted.\n */\n shortName: t.optional(t.string()),\n\n /**\n * Theme color used for the browser toolbar and OS chrome.\n *\n * @default \"#ffffff\"\n */\n themeColor: t.optional(t.string()),\n\n /**\n * Background color for the splash screen.\n *\n * @default \"#ffffff\"\n */\n backgroundColor: t.optional(t.string()),\n\n /**\n * Display mode for the installed PWA.\n *\n * - `standalone` - Looks like a native app (default)\n * - `fullscreen` - Uses entire screen (games, immersive)\n * - `minimal-ui` - Like standalone with minimal browser UI\n * - `browser` - Standard browser tab\n *\n * @default \"standalone\"\n */\n display: t.optional(\n t.enum([\"standalone\", \"fullscreen\", \"minimal-ui\", \"browser\"]),\n ),\n\n /**\n * Enable offline support via service worker.\n *\n * TODO: Not yet implemented.\n */\n offline: t.optional(t.boolean()),\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, opts?: { pwa?: boolean }): string {\n const style = entry.style;\n const browser = entry.browser ?? entry.server;\n const manifestLink = opts?.pwa\n ? '\\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />'\n : \"\";\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\"/>${manifestLink}\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 { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { $inject, Alepha, AlephaError } 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 * Resolve the absolute path to a toolchain binary that ships embedded in\n * `alepha`'s own `dependencies` (typescript, vite, vitest, @biomejs/biome,\n * drizzle-kit).\n *\n * The CLI runs the result via `node <path>` so the toolchain works under\n * every package manager — including pnpm with a strict node-linker, where\n * a transitive dependency's bin is NOT hoisted into the project's\n * `node_modules/.bin`. Resolution starts from `alepha`'s own location, so\n * the version is whatever `alepha` shipped — the project never pins it.\n *\n * @param pkg - npm package name (e.g. `\"typescript\"`)\n * @param binName - which `bin` entry to use (e.g. `\"tsc\"`); defaults to the\n * package's only/first bin\n */\n public resolveBin(pkg: string, binName?: string): string {\n const require = createRequire(import.meta.url);\n\n // Locate the package root by scanning the `node_modules` directories\n // Node would search, then reading `package.json` from disk directly.\n // We deliberately avoid `require.resolve(\"<pkg>/package.json\")` — a\n // strict `exports` map (e.g. drizzle-kit) blocks that subpath.\n let pkgDir: string | undefined;\n for (const nm of require.resolve.paths(pkg) ?? []) {\n const candidate = join(nm, pkg);\n if (existsSync(join(candidate, \"package.json\"))) {\n pkgDir = candidate;\n break;\n }\n }\n if (!pkgDir) {\n throw new AlephaError(\n `Cannot locate package '${pkg}' — is it installed alongside alepha?`,\n );\n }\n\n const meta = JSON.parse(\n readFileSync(join(pkgDir, \"package.json\"), \"utf8\"),\n ) as { bin?: string | Record<string, string> };\n const bin = meta.bin;\n if (!bin) {\n throw new AlephaError(`Package '${pkg}' declares no 'bin' entry`);\n }\n const rel =\n typeof bin === \"string\"\n ? bin\n : (bin[binName ?? pkg] ?? Object.values(bin)[0]);\n if (!rel) {\n throw new AlephaError(`Package '${pkg}' has no bin named '${binName}'`);\n }\n return join(pkgDir, rel);\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 pkg from \"alepha/package.json\" with { type: \"json\" };\n\nexport const alephaPackageJson = pkg;\nexport const version = pkg.version as string;\n","import { basename } from \"node:path\";\nimport { $inject, Alepha } from \"alepha\";\nimport type { RunnerMethod } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { alephaPackageJson, version } from \"../alephaPackageJson.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 pkg.packageManager = undefined;\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 pkg.packageManager = undefined;\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 // The toolchain (typescript, vite, vitest, biome, drizzle-kit) is NOT\n // pinned here — it ships embedded as `dependencies` of `alepha`, so the\n // `alepha` CLI resolves and runs it from its own install. The project\n // never declares those versions; upgrading `alepha` moves the whole\n // toolchain atomically. See `AlephaCliUtils.resolveBin`.\n const devDependencies: Record<string, string> = {};\n\n const scripts: Record<string, string> = {\n dev: \"alepha dev\",\n build: \"alepha build\",\n test: \"alepha test\",\n lint: \"alepha lint\",\n typecheck: \"alepha typecheck\",\n verify: \"alepha verify\",\n };\n\n if (modes.tailwind) {\n devDependencies.tailwindcss = alephaDeps.tailwindcss;\n devDependencies[\"@tailwindcss/vite\"] = alephaDeps[\"@tailwindcss/vite\"];\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 expo?: boolean;\n tailwind?: boolean;\n /**\n * Whether the project is a workspace package inside a monorepo.\n */\n isPackage?: boolean;\n}\n","export const agentMd = (): string => {\n return `# AGENTS.md\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\nalepha platform plan # Show planned cloud topology (requires platform plugin)\nalepha platform up # Provision + deploy to a configured environment\nalepha platform status # Inspect deployed resources\n\\`\\`\\`\n\n## Testing\n\n- Specs live in \\`test/\\`, named \\`*.spec.ts\\`.\n- Run with \\`alepha test\\` (Vitest, embedded in alepha — nothing to install).\n- \\`test/dummy.spec.ts\\` is the starting example; \\`Alepha.create()\\` is the\n entry point and \\`.inject(...)\\` resolves providers.\n\n## Cloud deployment (Cloudflare Workers)\n\nAdd the \\`platform\\` plugin to \\`alepha.config.ts\\` to manage cloud\nprovisioning, deploy, secrets, and DB migrations end-to-end:\n\n\\`\\`\\`ts\nimport { defineConfig } from \"alepha/cli/config\";\nimport { platform } from \"alepha/cli/platform\";\n\nexport default defineConfig({\n plugins: [\n platform({\n environments: {\n production: {\n adapter: \"cloudflare\",\n domain: \"yourapp.com\",\n // zone: \"yourapp.com\", // required only for wildcard domains\n // jurisdiction: \"eu\", // optional: EU data residency\n },\n },\n }),\n ],\n});\n\\`\\`\\`\n\nThen: \\`alepha platform up --env production\\` (auth via \\`wrangler login\\` on first run).\n\nSupported adapters: \\`cloudflare\\`, \\`vercel\\`. The Cloudflare adapter provisions\nD1 (or Hyperdrive when \\`DATABASE_URL\\` is postgres), KV, R2, Queues, and pushes\nsecrets via \\`wrangler secret bulk\\`. Set \\`build.target: \"cloudflare\"\\` in\n\\`alepha.config.ts\\` if you only want the build artifact without the orchestrator.\n\n## Documentation\n\n- Framework source: \\`node_modules/alepha/src/\\`\n- Docs: https://alepha.dev/llms.txt\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// import { platform } from \"alepha/cli/platform\";\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 // // Deploy to Cloudflare in ~10s: \\`alepha platform up --env production\\`\n // // Requires \\`wrangler login\\` once. D1, R2, KV, Queues and cron triggers\n // // are auto-provisioned from your $repository / $bucket / $cache / $queue\n // // / $scheduler primitives — no wrangler.toml to maintain.\n // plugins: [\n // platform({\n // environments: {\n // production: { adapter: \"cloudflare\", domain: \"myapp.com\" },\n // preview: { adapter: \"cloudflare\" }, // workers.dev subdomain\n // },\n // }),\n // ],\n});\n`;\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}\n\nexport const apiIndexTs = (options: ApiIndexTsOptions = {}) => {\n const { appName = \"app\" } = options;\n\n return `\nimport { $module } from \"alepha\";\nimport { HelloController } from \"./controllers/HelloController.ts\";\n\nexport const ApiModule = $module({\n name: \"${appName}.api\",\n services: [HelloController],\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 \"a11y\": {\n \"useFocusableInteractive\": \"off\",\n \"useSemanticElements\": \"off\",\n \"useKeyWithClickEvents\": \"off\",\n \"useAriaPropsForRole\": \"off\",\n \"noLabelWithoutControl\": \"off\"\n },\n \"correctness\": {\n \"useExhaustiveDependencies\": \"off\"\n },\n \"suspicious\": {\n \"noArrayIndexKey\": \"off\",\n \"noExplicitAny\": \"off\",\n \"noDocumentCookie\": \"off\"\n },\n \"style\": {\n \"noNonNullAssertion\": \"off\"\n }\n },\n \"domains\": {\n \"react\": \"recommended\"\n }\n },\n \"css\": {\n \"parser\": {\n \"cssModules\": false,\n \"tailwindDirectives\": true\n }\n },\n \"assist\": {\n \"actions\": {\n \"source\": {\n \"organizeImports\": \"on\"\n }\n }\n }\n}\n`.trim();\n","/**\n * Starter spec written by `alepha init`. It doubles as a worked example:\n * it shows the test location (`test/`), the `*.spec.ts` naming, and the\n * canonical Alepha entry point — `Alepha.create()` + `.inject(...)`.\n *\n * Tests run with `alepha test` (Vitest, embedded in alepha). Replace this\n * with real specs as the project grows.\n */\nexport const dummySpecTs = () =>\n `\nimport { Alepha } from \"alepha\";\nimport { expect, test } from \"vitest\";\n\ntest(\"alepha app can be created\", () => {\n const alepha = Alepha.create();\n\n expect(alepha).toBeDefined();\n expect(alepha.inject).toBeTypeOf(\"function\");\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 logoSvg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"300\" height=\"300\">\n <svg xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"b\" x1=\"142.3\" x2=\"159.6\" y1=\"123.3\" y2=\"176.7\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#33a72c\"/>\n <stop offset=\"1\" stop-color=\"#2d8d40\"/>\n </linearGradient>\n <linearGradient id=\"c\" x1=\"61.6\" x2=\"100.7\" y1=\"218.5\" y2=\"174\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#298e35\"/>\n <stop offset=\"1\" stop-color=\"#327952\"/>\n </linearGradient>\n <linearGradient id=\"d\" x1=\"262.7\" x2=\"242.2\" y1=\"178.4\" y2=\"220.1\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#32a62d\"/>\n <stop offset=\"1\" stop-color=\"#2d8d40\"/>\n </linearGradient>\n <linearGradient id=\"e\" x1=\"81.2\" x2=\"69.1\" y1=\"126.7\" y2=\"92.3\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#299a2c\"/>\n <stop offset=\"1\" stop-color=\"#51be40\"/>\n </linearGradient>\n <clipPath id=\"a\">\n <path fill=\"none\" d=\"M0 0h300v241H0z\"/>\n </clipPath>\n </defs>\n <g fill=\"none\" stroke-miterlimit=\"10\" clip-path=\"url(#a)\" font-family=\"none\" font-size=\"none\" font-weight=\"300\" style=\"mix-blend-mode:normal\" text-anchor=\"middle\">\n <path fill=\"url(#b)\" d=\"M54 174a182 182 0 0 1 106-51c19-2 37-6 54-15l16-11 3-4 1 1 1 4 1 6v9c0 6-2 12-5 18l-1 4-7 8c-5 7-12 14-19 19l-4 2-11 7v1l-1-1-3 2a120 120 0 0 1-30 8l-8 1-20-1c-21-3-44-10-64 0-5 2-9 4-12 8l-9 9h1l14-9c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-5 1h-8l-7-1H15c0-3 4-7 5-9l7-11 5-8c6-10 14-19 22-28z\"/>\n <path fill=\"#1d524a\" d=\"M178 141c9-1 17-4 24-8l8-4-6 4c-9 7-20 11-32 13l-39 5h-5l-15 3 16 13 18 15-20-1c-21-3-44-10-64 0-5 2-9 4-12 8l-9 9h1l14-9c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-5 1h-8l-7-1H15c0-3 4-7 5-9l7-11 5-8c6-10 14-19 22-28l4-2 23-14 11-5c21-7 43-9 65-9l21-3z\"/>\n <path fill=\"url(#c)\" d=\"M57 189c7-4 15-6 23-7h7l25 3 3 1-2 5-3 5c-4 7-10 14-15 18l-4 3c-12 8-25 12-39 13h-5l-4-9-2-5 5-2 9-4 10-5 10-4c5-2 10-3 14-6l3-1h-1a1136 1136 0 0 0-43 14c1-6 6-14 9-19 1 0 0 0 0 0z\"/>\n <path fill=\"#2d6f4d\" d=\"m41 216 5-2 9-4 5 3c9 4 18 6 27 4h4c-12 8-25 12-39 13h-5l-4-9-2-5zm16-27s1 0 0 0c-3 5-8 13-9 19l-15 8c0-3 1-9 3-11l3-3 4-4 14-9z\"/>\n <path fill=\"#49b63b\" d=\"M42 198h1l-4 4 3-4z\"/>\n <path fill=\"#2d6f4d\" d=\"m113 154 15-3 11 2 18 8c11 6 23 8 35 5l8-2-11 7v1l-1-1-3 2a120 120 0 0 1-30 8l-8 1-18-15-16-13z\"/>\n <path fill=\"#49b63b\" d=\"M81 158c2-4 11-7 15-8 18-6 36-7 55-8l12-1h15l-21 3c-22 0-44 2-65 9l-11 5z\"/>\n <path fill=\"#2d913b\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1 1 5v6l6 12 5 10 12 26 2 5 4 10 7 17 4 8c-9 5-20 9-30 12l-16 3-7-14-6-14-5-10-1-3-4 7-13 27-6 11-6 2-24 9 2-4c11-16 14-36 11-56l-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#2d6f4d\" d=\"m175 17 6 12 5 10 12 26 2 5 4 10 7 17 4 8c-9 5-20 9-30 12l-16 3-7-14-6-14-5-10-1-3c0-2 5-8 6-10l1-2c9-13 17-28 18-45v-5z\"/>\n <path fill=\"#1d524a\" d=\"m175 17 6 12 5 10 12 26 2 5-3-1-13-8-7 4 3 7-4 1-2-3-5-12-5 7a136 136 0 0 1-10 15l-3 2-1-3c0-2 5-8 6-10l1-2c9-13 17-28 18-45v-5z\"/>\n <path fill=\"#2d6f4d\" d=\"m186 39 12 26 2 5-3-1-13-8-7 4-6-12 8-7 7-7z\"/>\n <path fill=\"#2d913b\" d=\"m177 65 7-4 13 8 3 1 4 10-3 7-7 14-2 8-1-4-6-19a99 99 0 0 0-8-21zm-3 5 2 3 12 32h-1l-8 5c-4 1-9 0-13-2l-1-1c-1-8 2-15 4-22 1-5 2-10 5-15z\"/>\n <path fill=\"#1d524a\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1c-3 1-3 2-4 4l-11 14-5 5v1c-11 11-22 24-31 37l-5 6-6 11h1l6 12c3 7 8 13 14 17l-6 11-6 2-24 9 2-4c11-16 14-36 11-56l-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#49b63b\" d=\"m110 52 2-5 9-14c7-8 19-14 29-18l10-3 12-6 1-1 1 1c-3 1-3 2-4 4l-11 14-5 5-8 7-13 11-5 6c-5-2-10-5-15-3l-3 2z\"/>\n <path fill=\"#2d913b\" d=\"m110 52 3-2c5-2 10 1 15 3l-12 13-6 9-3 1-9 5 1-3 9-21 2-5z\"/>\n <path fill=\"#2d6f4d\" d=\"M121 92c10-5 19-9 28-17l7-6c-1 2-6 8-6 10l-4 7-13 27c-6-4-11-10-14-17l-6-12 4-5 4 13z\"/>\n <path fill=\"#49b63b\" d=\"m154 30-1 11c0 4-3 9-6 12-6 9-19 10-25 19-1 0-3 2-4 1l5-6c9-13 20-26 31-37z\"/>\n <path fill=\"url(#d)\" d=\"m230 135 3 6 11 17 2 5 4 5 3 6 9 14 19 36 4 5c-2 2-19 2-22 2l-5-1h-2c-12 0-25-4-35-10l-4-3c-10-8-15-16-21-27l-7-18v-1l11-7 4-2c7-5 14-12 19-19l7-8z\"/>\n <path fill=\"#1d524a\" d=\"m230 135 3 6 11 17 2 5 4 5 3 6h-1c-10-8-20-9-32-4l23 23 13 12 1 2-20-14-13-12-4-3-5-6c-2 0-2 3-2 5l-1 10c-1 8-2 11 1 19l2 6 2 5c-10-8-15-16-21-27l-7-18v-1l11-7 4-2c7-5 14-12 19-19l7-8z\"/>\n <path fill=\"#2d6f4d\" d=\"m233 141 11 17 2 5 4 5 3 6h-1c-10-8-20-9-32-4l-7-9 15-15 5-5zm-16 76-2-5-2-6c-3-8-2-11-1-19l1-10c0-2 0-5 2-5l5 6 4 3h-1c0 4 8 22 11 26 6 10 15 18 25 22 2 0 3 0 4 2l-5-1h-2c-12 0-25-4-35-10l-4-3z\"/>\n <path fill=\"#2d913b\" d=\"M110 75c3 20 0 40-11 56l-2 4a145 145 0 0 0-43 31l-5 4-11 15v-7l-1-10a143 143 0 0 1 5-29l9-20c13-18 32-29 52-37l4-3 3-4z\"/>\n <path fill=\"url(#e)\" d=\"m42 139 9-20c13-18 32-29 52-37l4-3-3 7c-4 5-8 11-13 15l-3 3c-6 6-13 12-18 19l-8 11-20 5z\"/>\n <path fill=\"#1d524a\" d=\"M91 101c0 2-4 6-6 8-5 5-10 11-14 18l-9 13-4 9 5 1c4 0 16-9 19-7-10 7-20 14-28 23l-5 4-11 15v-7l-1-10a143 143 0 0 1 5-29l20-5 8-11c5-7 12-13 18-19l3-3z\"/>\n <path fill=\"#2d6f4d\" d=\"m62 134-9 16-3 7-2 4c-3 3-8 5-10 8l-1-1a143 143 0 0 1 5-29l20-5zm0 6 11-5 7-4c5-1 14-2 19 0l-2 4-15 8c-3-2-15 7-19 7l-5-1 4-9z\"/>\n </g>\n </svg>\n</svg>\n`;\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: { tailwind?: boolean } = {}) => {\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 * - 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","/**\n * Minimal Vitest config for a freshly scaffolded Alepha project.\n *\n * Defines `test.root` explicitly so Vitest doesn't walk up the directory\n * tree and inherit a parent monorepo config (which can pull in unrelated\n * setup files, database connections, etc.).\n */\nexport const vitestConfigTs = () =>\n `import { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n test: {\n root: \".\",\n globals: true,\n },\n});\n`;\n","/**\n * `.vscode/settings.json` — points the editor's TypeScript language server\n * at the `typescript` copy embedded in `alepha`'s dependencies, so the IDE\n * type-checks with the exact same compiler version as `alepha typecheck`.\n *\n * Without this, VS Code falls back to its own bundled TypeScript, which\n * drifts from whatever `alepha` ships — the classic \"green in CI, red\n * squiggles in the editor\" skew.\n *\n * The path assumes a hoisting package manager (yarn node-modules / npm /\n * bun), where `alepha`'s `typescript` dependency lands at the project's\n * top-level `node_modules/typescript`. Since the project no longer declares\n * its own `typescript`, that is the only copy present.\n */\nexport const vscodeSettingsJson = () =>\n `\n{\n \"typescript.tsdk\": \"node_modules/typescript/lib\",\n \"typescript.enablePromptUseWorkspaceTsdk\": true\n}\n`.trim();\n","export interface WebAppRouterOptions {\n api?: boolean;\n}\n\nexport const webAppRouterTs = (options: WebAppRouterOptions) => {\n const imports: string[] = ['import { $page } from \"alepha/react/router\";'];\n const classMembers: string[] = [];\n\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 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\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 { 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 { agentMd } from \"../templates/agentMd.ts\";\nimport { alephaConfigTs } from \"../templates/alephaConfigTs.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 { logoSvg } from \"../templates/logoSvg.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 { vitestConfigTs } from \"../templates/vitestConfigTs.ts\";\nimport { vscodeSettingsJson } from \"../templates/vscodeSettingsJson.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?: boolean;\n /**\n * Write `.vscode/settings.json` pointing the editor's TypeScript\n * server at the `typescript` copy embedded in `alepha`.\n */\n vscodeSettings?: boolean;\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, { force }));\n }\n if (opts.vscodeSettings) {\n tasks.push(this.ensureVscodeSettings(root, { force, checkWorkspace }));\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 const exists = await this.existsInParents(root, \"tsconfig.json\");\n if (!opts.force && exists) {\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 `.vscode/settings.json` exists, pointing the editor's TypeScript\n * language server at the `typescript` copy embedded in `alepha`. Keeps the\n * IDE on the same compiler version as `alepha typecheck` — see\n * `vscodeSettingsJson`.\n */\n public async ensureVscodeSettings(\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, \".vscode\"))\n ) {\n return;\n }\n const target = this.fs.join(root, \".vscode\", \"settings.json\");\n if (!opts.force && (await this.fs.exists(target))) {\n return;\n }\n await this.fs.mkdir(this.fs.join(root, \".vscode\"), { recursive: true });\n await this.fs.writeFile(target, vscodeSettingsJson());\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 /**\n * Ensure AGENTS.md (cross-tool standard, canonical source) exists, with a\n * CLAUDE.md stub that imports it via Claude Code's `@` syntax. Single\n * source of truth, cross-platform, no symlink needed.\n */\n public async ensureAgentMd(\n root: string,\n options: { force?: boolean } = {},\n ): Promise<void> {\n await Promise.all([\n this.ensureFile(root, \"AGENTS.md\", agentMd(), options.force),\n this.ensureFile(root, \"CLAUDE.md\", \"@AGENTS.md\\n\", options.force),\n ]);\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: { 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 }),\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\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 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 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({ 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({ api: opts.api }),\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 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 + a self-contained\n * `vitest.config.ts`. Pinning `test.root` prevents Vitest from walking up\n * to a parent monorepo config (e.g. one that boots a Postgres container).\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 const vitestConfigPath = this.fs.join(root, \"vitest.config.ts\");\n\n if (!(await this.fs.exists(vitestConfigPath))) {\n await this.fs.writeFile(vitestConfigPath, vitestConfigTs());\n }\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 tailwind?: boolean;\n force?: boolean;\n };\n args?: string;\n }) {\n if (!args) {\n // If the current directory doesn't look like an existing project\n // (no package.json), default to creating a `my-app/` subdirectory\n // rather than scaffolding into a random cwd.\n const hasPackageJson = await this.fs.exists(\n this.fs.join(root, \"package.json\"),\n );\n if (!hasPackageJson) {\n args = \"my-app\";\n }\n }\n\n if (args) {\n root = this.fs.join(root, args);\n await this.fs.mkdir(root, { force: true });\n }\n\n // Flag cascading: --tailwind → --react\n if (flags.tailwind) {\n flags.react = true;\n }\n\n const f = flags;\n\n // When codegen flags are set, target directory must be empty (unless --force)\n const hasCodegenFlags = flags.api || 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 // Always emit both AGENTS.md and CLAUDE.md at project roots (skip for\n // monorepo sub-packages where agent files live at workspace root).\n const writeAgentMd = !workspace.isPackage;\n\n const isExpo = await this.pm.hasExpo(root);\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: { ...f, isPackage: workspace.isPackage },\n tsconfigJson: !workspace.config.tsconfigJson,\n biomeJson: true,\n editorconfig: !workspace.config.editorconfig,\n agentMd: writeAgentMd,\n // Editor TS-server pointer at a project root only; monorepo\n // sub-packages inherit the workspace-root `.vscode/`.\n vscodeSettings: writeAgentMd,\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, { force });\n }\n if (flags.react && !isExpo) {\n await this.ensureWebProject(root, {\n api: !!flags.api,\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 // Always scaffold the test setup — Vitest ships embedded in `alepha`, so\n // `alepha test` works in every project. The dummy spec doubles as a\n // worked example for both humans and AI agents.\n await this.ensureTestDir(root);\n\n // Best-effort lint pass — don't block init if it fails. The user can\n // fix or silence issues later.\n try {\n await run(`${pmName} run lint`, {\n alias: \"running linter\",\n root,\n });\n } catch (err) {\n this.log.warn(\n \"Linter reported issues during init — continuing. Run `lint` again later to inspect.\",\n { error: err instanceof Error ? err.message : String(err) },\n );\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 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\";\nimport type { BuildManifest } from \"./BuildCloudflareTask.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 /**\n * Build-time snapshot of primitive data, read from\n * `dist/manifest.json`. Populated only in `--prebuilt` mode when a\n * previous build's manifest is present — lets BuildCloudflareTask\n * regenerate `wrangler.jsonc` without re-booting the workspace.\n * `null` when introspection (`ctx.alepha`) is the source of truth.\n */\n manifest: BuildManifest | null;\n\n /**\n * Resolved `platform({ default, environments, ... })` options from\n * the workspace's `alepha.config.ts`. Populated by `BuildCommand`\n * from the CLI's Alepha instance (where alepha.config.ts ran) —\n * BuildCloudflareTask uses these to write the corresponding fields\n * into `dist/manifest.json` so the deploy side doesn't need to\n * re-load `alepha.config.ts`. `null` when no platform options were\n * declared.\n */\n platformOptions: {\n default?: string;\n tenancy?: \"none\" | \"optional\" | \"required\";\n environments?: Record<\n string,\n {\n adapter: \"cloudflare\" | \"vercel\";\n domain?: string;\n zone?: string;\n jurisdiction?: \"eu\" | \"fedramp\";\n accountId?: string;\n }\n >;\n } | null;\n\n flags?: {\n image?: boolean | string;\n /**\n * Skip the slow build steps (Vite client + Vite server + asset\n * compression). Only runs the deploy-config generation\n * (wrangler.jsonc, etc.) — useful when the caller already has a\n * built `dist/` and just needs the wrangler config refreshed for\n * per-tenant overrides.\n */\n prebuilt?: boolean;\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 if (ctx.flags?.prebuilt) {\n return;\n }\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.flags?.prebuilt) {\n return;\n }\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 pwa: !!ctx.options.pwa,\n });\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 type { ContainerPrimitive } from \"alepha/container\";\nimport { SEND_EMAIL_DEFAULT_BINDING } from \"alepha/email/cloudflare\";\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\n// Looked up by class name string (not by class identity) because\n// BuildCloudflareTask runs in the CLI's Alepha context while ctx.alepha\n// is the workspace's separate context. Two module graphs = two distinct\n// `CloudflareEmailProvider` class objects, so the imported reference\n// here wouldn't match the one the workspace registered.\nconst CLOUDFLARE_EMAIL_PROVIDER_NAME = \"CloudflareEmailProvider\";\n\ninterface WranglerConfig {\n [key: string]: any;\n}\n\n/**\n * Build-time snapshot describing what the workspace needs at deploy\n * time. Written to `dist/manifest.json` alongside `wrangler.jsonc`.\n *\n * Lets `alepha platform up --prebuilt` skip the Vite-based\n * introspection step on the deploy side — and lets Alepha Rocket skip\n * the workspace's runtime `npm install` because no app source is\n * booted at deploy time. The manifest captures the bits of primitive\n * data that the deploy steps (provision, secrets, hooks) need to\n * know.\n */\nexport interface BuildManifest {\n version: 1;\n project: string;\n /**\n * Default environment when `--env` is omitted at deploy time.\n * Captured from `platformOptions.default` (defaults to `\"production\"`).\n */\n defaultEnv: string;\n /**\n * Multi-tenancy mode (`none` | `optional` | `required`). Captured from\n * `platformOptions.tenancy` so the prebuilt deploy side (Rocket) can\n * validate `--tenant` without re-evaluating `alepha.config.ts`.\n */\n tenancy?: \"none\" | \"optional\" | \"required\";\n /**\n * Resolved `platform({ environments: ... })` map. Captured at build\n * time from the workspace's `alepha.config.ts` so the deploy side\n * doesn't need to re-evaluate the config. Each value is the same\n * `EnvironmentConfig` shape consumed by the orchestrator (adapter,\n * domain, zone, jurisdiction, accountId).\n */\n environments: Record<\n string,\n {\n adapter: \"cloudflare\" | \"vercel\";\n domain?: string;\n zone?: string;\n jurisdiction?: \"eu\" | \"fedramp\";\n accountId?: string;\n }\n >;\n resources: {\n hasDatabase: boolean;\n hasBucket: boolean;\n hasKV: boolean;\n hasQueue: boolean;\n hasCron: boolean;\n };\n /**\n * All distinct cron expressions registered by `$scheduler`\n * primitives. Empty when `hasCron` is false.\n */\n crons: string[];\n /**\n * `$container()` descriptors — image, port, lifecycle settings.\n * Used both to populate Cloudflare Containers bindings in\n * wrangler.jsonc and (in future) to know which images Rocket should\n * pull on the deploy side.\n */\n containers: Array<{\n name: string;\n className: string;\n image: string;\n port: number;\n sleepAfter: string;\n instanceType: string;\n maxInstances: number;\n }>;\n /**\n * Every env var the app declares via `$env`, captured from\n * `alepha.dump().env` at build time. The deploy `secrets` step uses this\n * as the worker-secret allowlist (minus build/binding vars) so CI can\n * deliver secrets straight from `process.env` without a `.env` file —\n * `platform.secrets.keys` overrides it when set. Empty when introspection\n * was unavailable (older artifacts / prebuilt mode).\n */\n env: string[];\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 // Slugify the dir basename — wrangler rejects names that aren't\n // `^[a-z0-9-]+$` (no uppercase, dots, underscores, spaces, etc.).\n // Without this, running `alepha build -t cloudflare` in a dir like\n // `My App` or `club-0.0.2` produces an unusable `wrangler.jsonc`.\n const name = basename(root)\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 63);\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 wrangler.observability ??= {\n enabled: true,\n head_sampling_rate: 1,\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 this.enhanceEmail(ctx, wrangler);\n const containers = this.enhanceContainers(ctx, wrangler);\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"wrangler.jsonc\"),\n JSON.stringify(wrangler, null, 2),\n );\n\n // Only write a fresh manifest when we discovered it from a booted\n // Alepha instance. In manifest mode (ctx.manifest != null) we're\n // re-emitting the same data we just read — skip to avoid a redundant\n // write and to keep the original manifest as the canonical record.\n if (!ctx.manifest) {\n await this.writeManifest(ctx, root, distDir, name, containers);\n }\n await this.writeWorkerEntryPoint(root, distDir, containers);\n }\n\n /**\n * Write `dist/manifest.json` — a build-time snapshot of everything\n * downstream tooling needs to know about the app without re-booting\n * it. Used by `alepha platform up --prebuilt` (and Alepha Rocket) so\n * the deploy path can skip the Vite-based introspection step and the\n * workspace's runtime npm install.\n */\n protected async writeManifest(\n ctx: BuildTaskContext,\n root: string,\n distDir: string,\n name: string,\n containers: ContainerDescriptor[],\n ): Promise<void> {\n // Discover the same primitive shapes the enhance* methods read.\n // Errors are silently swallowed — an absent primitive class just\n // means the app doesn't use that resource.\n let hasDatabase = false;\n let hasBucket = false;\n let hasKV = false;\n let hasQueue = false;\n let crons: string[] = [];\n\n try {\n const repo = ctx.alepha.inject(\"RepositoryProvider\") as {\n getRepositories?: () => unknown[];\n };\n hasDatabase = (repo.getRepositories?.() ?? []).length > 0;\n } catch {}\n\n try {\n hasBucket = ctx.alepha.primitives(\"$bucket\").length > 0;\n } catch {}\n\n try {\n // Only count $cache primitives without an explicit `provider`\n // option — those fall back to KV on workerd. Explicit memory /\n // Redis / Postgres providers opt out of KV provisioning.\n hasKV =\n ctx.alepha\n .primitives(\"cache\")\n .filter(\n (p) =>\n (p as { options?: { provider?: unknown } }).options?.provider ==\n null,\n ).length > 0;\n } catch {}\n\n try {\n hasQueue = ctx.alepha.primitives(\"$queue\").length > 0;\n } catch {}\n\n try {\n const cronProvider = ctx.alepha.inject(\"CronProvider\") as {\n getCronJobs?: () => Array<{ expression: string }>;\n };\n crons = [\n ...new Set(\n (cronProvider.getCronJobs?.() ?? []).map((c) => c.expression),\n ),\n ];\n } catch {}\n\n // platformOptions come from the CLI's Alepha instance (where\n // alepha.config.ts ran during the configure hook). BuildCommand\n // reads them up there and threads them via ctx — ctx.alepha here\n // is the WORKSPACE's Vite-booted Alepha, which never saw the\n // platform options.\n const defaultEnv = ctx.platformOptions?.default ?? \"production\";\n const environments = (ctx.platformOptions?.environments ??\n {}) as BuildManifest[\"environments\"];\n\n // Every declared `$env` key. dump() force-instantiates the graph (no\n // start/ready hooks), so this is the full env surface — used by the\n // deploy `secrets` step as the worker-secret allowlist.\n let env: string[] = [];\n try {\n env = Object.keys(ctx.alepha.dump().env).sort();\n } catch {}\n\n const manifest: BuildManifest = {\n version: 1,\n project: name,\n defaultEnv,\n tenancy: ctx.platformOptions?.tenancy,\n environments,\n resources: {\n hasDatabase,\n hasBucket,\n hasKV,\n hasQueue,\n hasCron: crons.length > 0,\n },\n crons,\n containers: containers.map((c) => ({\n name: c.name,\n className: c.className,\n image: c.image,\n port: c.port,\n sleepAfter: c.sleepAfter,\n instanceType: c.instanceType,\n maxInstances: c.maxInstances,\n })),\n env,\n };\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"manifest.json\"),\n JSON.stringify(manifest, null, 2),\n );\n }\n\n protected enhanceDomain(wrangler: WranglerConfig): void {\n const domain = process.env.CLOUDFLARE_DOMAIN;\n if (!domain) {\n return;\n }\n\n if (domain.includes(\"*\")) {\n const zone = process.env.CLOUDFLARE_ZONE;\n if (!zone) {\n throw new Error(\n `Wildcard domain \"${domain}\" requires CLOUDFLARE_ZONE to be set (the parent zone name, e.g. \"alepha.dev\").`,\n );\n }\n wrangler.routes = [\n {\n pattern: domain.endsWith(\"/*\") ? domain : `${domain}/*`,\n zone_name: zone,\n },\n ];\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 const cronExpressions = ctx.manifest\n ? ctx.manifest.crons\n : this.discoverCrons(ctx);\n if (cronExpressions.length === 0) {\n return;\n }\n wrangler.triggers ??= {};\n wrangler.triggers.crons = cronExpressions;\n }\n\n protected discoverCrons(ctx: BuildTaskContext): string[] {\n if (ctx.alepha.primitives(\"scheduler\").length === 0) {\n return [];\n }\n let cronProvider: CronProvider | undefined;\n try {\n cronProvider = ctx.alepha.inject(\"CronProvider\") as WorkerdCronProvider;\n } catch {}\n const crons = cronProvider?.getCronJobs();\n if (!crons || crons.length === 0) {\n return [];\n }\n return [...new Set(crons.map((c) => c.expression))];\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 const jurisdiction = process.env.CLOUDFLARE_JURISDICTION;\n wrangler.d1_databases = wrangler.d1_databases || [];\n wrangler.d1_databases.push({\n binding,\n database_name: dbName,\n database_id: id,\n ...(jurisdiction ? { jurisdiction } : {}),\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 const jurisdiction = process.env.CLOUDFLARE_JURISDICTION;\n wrangler.r2_buckets = wrangler.r2_buckets || [];\n wrangler.r2_buckets.push({\n binding: bucketName,\n bucket_name: bucketName,\n ...(jurisdiction ? { jurisdiction } : {}),\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 enhanceEmail(\n ctx: BuildTaskContext,\n wrangler: WranglerConfig,\n ): void {\n // Manifest mode doesn't capture email provider details yet. Apps\n // using CloudflareEmailProvider would need a manifest field added.\n // For now, skip — non-email apps and apps using non-CF providers\n // are unaffected. TODO: add `emailProvider` to BuildManifest.\n if (ctx.manifest || !ctx.alepha) {\n return;\n }\n try {\n ctx.alepha.inject(CLOUDFLARE_EMAIL_PROVIDER_NAME);\n } catch {\n return;\n }\n\n wrangler.send_email = wrangler.send_email || [];\n if (\n wrangler.send_email.some(\n (b: { name: string }) => b.name === SEND_EMAIL_DEFAULT_BINDING,\n )\n ) {\n return;\n }\n\n // NOTE: do NOT set `destination_address` here. On a Cloudflare\n // `send_email` binding, `destination_address` is a *recipient* allow-list\n // lock (the worker may then only send TO that one address) — it is not the\n // sender. Setting it to `EMAIL_FROM` (the sender) broke all outbound mail:\n // a bare address locked delivery to that single recipient (\"email to … not\n // allowed\"), and a display-name form like `Lore <noreply@…>` is a malformed\n // destination value that Cloudflare rejects with \"internal error\". The\n // sender goes in the message `from` field (see CloudflareEmailProvider.send);\n // leaving the binding unrestricted lets the worker send to any verified\n // destination.\n const entry: Record<string, unknown> = { name: SEND_EMAIL_DEFAULT_BINDING };\n\n wrangler.send_email.push(entry);\n }\n\n /**\n * Discover `$container` primitives and emit the matching Cloudflare\n * Containers bindings, Durable Object bindings, and migrations into\n * `wrangler.jsonc`. The DO class declarations are added later, when\n * the worker entry point is written.\n *\n * Returns the list of container descriptors so\n * `writeWorkerEntryPoint` can emit `export class <NAME> extends\n * Container` declarations referencing them.\n */\n protected discoverContainers(ctx: BuildTaskContext): ContainerDescriptor[] {\n // String key, not the `$container` factory. The build task runs in\n // the CLI's Node realm, while the workspace's entry module is\n // loaded by Vite — two separate module copies of\n // `alepha/container`. Looking up by `$container[KIND]` (a class\n // reference) would dereference the CLI's ContainerPrimitive class,\n // which never matches the workspace's. The string form iterates\n // the registry by class name and survives the dual-realm — same\n // pattern used for `$bucket`, `$queue`, `scheduler` below.\n const primitives = ctx.alepha.primitives(\n \"container\",\n ) as ContainerPrimitive[];\n return primitives.map((p) => ({\n name: p.name.toUpperCase(),\n className: p.name\n .split(/[^a-zA-Z0-9]/)\n .filter(Boolean)\n .map((s) => s[0]!.toUpperCase() + s.slice(1))\n .join(\"\"),\n image: p.options.image,\n port: p.options.port ?? 3000,\n sleepAfter:\n typeof p.options.sleepAfter === \"string\" ? p.options.sleepAfter : \"15m\",\n // `lite` is the post-GA name for what `$container` historically\n // called `dev`. Default to `lite` here and rewrite any\n // explicit `dev` to it on the way out — wrangler warns\n // otherwise.\n instanceType:\n p.options.instanceType === \"dev\"\n ? \"lite\"\n : (p.options.instanceType ?? \"lite\"),\n maxInstances: p.options.maxInstances ?? 5,\n envVars: p.options.envVars,\n }));\n }\n\n /**\n * Expand a short image ref (e.g. `alepha-rocket:0.1.0`) into the\n * fully-qualified `registry.cloudflare.com/<account>/<image>:<tag>`\n * URL that wrangler validates at deploy time.\n *\n * Cloudflare Containers only pulls from `registry.cloudflare.com`;\n * wrangler accepts either a Dockerfile path or a fully-qualified\n * registry URL in the `image` field — not a bare DockerHub-style\n * name. We let `$container({ image })` callers write the short\n * form (it matches what `wrangler containers push <local>` accepts\n * + matches the local docker tag) and rewrite to the CF registry\n * URL here.\n *\n * Pass-through cases:\n * - already a full URL: starts with `registry.cloudflare.com/`\n * or contains a scheme/`://`\n * - looks like a Dockerfile path: starts with `./` or `/`\n */\n protected resolveContainerImage(image: string): string {\n if (\n image.startsWith(\"./\") ||\n image.startsWith(\"/\") ||\n image.startsWith(\"registry.cloudflare.com/\") ||\n image.includes(\"://\")\n ) {\n return image;\n }\n const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;\n if (!accountId) {\n // No account id — leave the short form and let wrangler error\n // out with a clearer message. This branch fires only in dry\n // builds where the env isn't wired (e.g. `alepha build` without\n // `alepha platform up` around it).\n return image;\n }\n return `registry.cloudflare.com/${accountId}/${image}`;\n }\n\n protected enhanceContainers(\n ctx: BuildTaskContext,\n wrangler: WranglerConfig,\n ): ContainerDescriptor[] {\n const descriptors: ContainerDescriptor[] = ctx.manifest\n ? (ctx.manifest.containers as ContainerDescriptor[])\n : this.discoverContainers(ctx);\n if (descriptors.length === 0) {\n return [];\n }\n\n wrangler.containers = wrangler.containers || [];\n wrangler.durable_objects = wrangler.durable_objects || {};\n wrangler.durable_objects.bindings = wrangler.durable_objects.bindings || [];\n wrangler.migrations = wrangler.migrations || [];\n\n const newSqliteClasses: string[] = [];\n for (const d of descriptors) {\n wrangler.containers.push({\n class_name: d.className,\n image: this.resolveContainerImage(d.image),\n instance_type: d.instanceType,\n max_instances: d.maxInstances,\n });\n wrangler.durable_objects.bindings.push({\n name: d.name,\n class_name: d.className,\n });\n newSqliteClasses.push(d.className);\n }\n\n if (newSqliteClasses.length > 0) {\n wrangler.migrations.push({\n tag: \"containers-v1\",\n new_sqlite_classes: newSqliteClasses,\n });\n }\n\n return descriptors;\n }\n\n protected async writeWorkerEntryPoint(\n root: string,\n distDir: string,\n containers: ContainerDescriptor[] = [],\n ): Promise<void> {\n // Extend `globalThis.__alepha_CloudflareContainer` instead of\n // importing `@cloudflare/containers` directly. The entry is\n // written AFTER Vite, so any bare specifier in here survives to\n // workerd (which has `no_bundle: true`) and 10021's out. The\n // global is set by a side-effect in `alepha/container`'s\n // workerd entry, which Vite has already inlined into\n // `./index.js`. ESM evaluates top-level imports before the\n // module body, so by the time the `extends` expression below is\n // evaluated, the global is set.\n const containerDeclarations = containers\n .map((c) => {\n const envVars = c.envVars\n ? ` envVars = ${JSON.stringify(c.envVars)};\\n`\n : \"\";\n return `export class ${c.className} extends globalThis.__alepha_CloudflareContainer {\\n defaultPort = ${c.port};\\n sleepAfter = \"${c.sleepAfter}\";\\n${envVars}}`;\n })\n .join(\"\\n\\n\");\n\n const workerCode = `\nimport \"./index.js\";\n\n// Stash the per-invocation \\`executionCtx.waitUntil\\` in the Alepha store\n// so background work (notably $job direct dispatch) can keep the isolate\n// alive past the response.\nconst setWaitUntil = (executionCtx) => {\n if (executionCtx && typeof executionCtx.waitUntil === \"function\") {\n __alepha.set(\"cloudflare.waitUntil\", (p) => executionCtx.waitUntil(p));\n } else {\n __alepha.set(\"cloudflare.waitUntil\", undefined);\n }\n};\n\n// Bind the per-invocation Worker \\`env\\`: keep the full binding (D1, R2, KV, …)\n// in the store for providers, and lift its string values (secrets/vars like\n// PUBLIC_URL) into \\`alepha.env\\` so \\`$env\\` resolves them at runtime.\nconst bindEnv = (env) => {\n __alepha.set(\"cloudflare.env\", env);\n __alepha.loadEnv(env);\n};\n\nexport default {\n fetch: async (request, env, executionCtx) => {\n const ctx = { req: request, res: undefined };\n\n bindEnv(env);\n setWaitUntil(executionCtx);\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, executionCtx) => {\n bindEnv(env);\n setWaitUntil(executionCtx);\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, executionCtx) => {\n bindEnv(env);\n setWaitUntil(executionCtx);\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 const containerBlock =\n containers.length > 0 ? `${containerDeclarations}\\n\\n` : \"\";\n\n await this.fs.writeFile(\n this.fs.join(root, distDir, \"main.cloudflare.js\"),\n `${this.warningComment}\\n${containerBlock}${workerCode}`.trim(),\n );\n }\n}\n\ninterface ContainerDescriptor {\n name: string;\n className: string;\n image: string;\n port: number;\n sleepAfter: string;\n /**\n * Cloudflare Containers instance class.\n *\n * `dev` is the wrangler-pre-GA name; the platform accepts it but\n * emits a deprecation warning telling you to use `lite`. We\n * silently translate at write time (see `discoverContainers`\n * default + `enhanceContainers` write) so older\n * `$container({ instanceType: \"dev\" })` declarations keep working.\n */\n instanceType: \"dev\" | \"lite\" | \"basic\" | \"standard\";\n maxInstances: number;\n envVars?: Record<string, string>;\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.flags?.prebuilt) {\n return;\n }\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 * Resolved compile options after merging config + flag defaults.\n */\ninterface ResolvedCompile {\n target: string;\n base: string;\n minify: boolean;\n}\n\n/**\n * Generate Docker deployment configuration and optionally build the image.\n *\n * Two modes:\n *\n * 1. Standard (default) - copies the bundled JS + `package.json` and runs\n * `bun install` (or `npm install`) inside the container.\n * 2. Compile - runs `bun build --compile` to produce a single static binary\n * and packages it inside a minimal distroless image. No `node_modules`\n * are ever installed; all dependencies must be bundled by Vite. Requires\n * `runtime: \"bun\"`.\n *\n * Creates:\n * - Dockerfile (compile or standard variant)\n * - Copies migrations directory if it exists\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 const compile = this.resolveCompile(ctx);\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 if (compile) {\n await ctx.run({\n name: \"assert no externals (compile mode)\",\n handler: async () => {\n await this.assertNoExternals(ctx.root, distDir);\n },\n });\n\n await ctx.run(this.buildCompileCommand(compile), {\n alias: `bun build --compile (${compile.target})`,\n root: this.fs.join(ctx.root, distDir),\n });\n\n await ctx.run({\n name: \"cleanup pre-compile artifacts\",\n handler: async () => {\n await this.cleanupPreCompileArtifacts(ctx.root, distDir);\n },\n });\n }\n\n await ctx.run({\n name: \"generate deploy config (docker)\",\n handler: async () => {\n const migrationsCopied = await this.copyMigrations(ctx.root, distDir);\n const hasDeps = await this.hasRuntimeDeps(ctx.root, distDir);\n await this.writeDockerfile(ctx.root, distDir, {\n compile,\n standard: { image: dockerFrom, command: dockerCommand },\n hasMigrations: migrationsCopied,\n hasDeps,\n install: ctx.options.docker?.install ?? [],\n });\n },\n });\n\n if (ctx.flags?.image) {\n await this.buildDockerImage(ctx, distDir);\n }\n }\n\n /**\n * Merge the user-supplied compile config with sensible defaults.\n * Returns null when compile mode is disabled.\n */\n protected resolveCompile(ctx: BuildTaskContext): ResolvedCompile | null {\n const raw = ctx.options.docker?.compile;\n if (!raw) {\n return null;\n }\n\n if (ctx.options.runtime !== \"bun\") {\n throw new AlephaError(\n `Compile mode requires runtime 'bun', got '${ctx.options.runtime}'`,\n );\n }\n\n const config = typeof raw === \"object\" ? raw : {};\n\n return {\n target: config.target ?? this.defaultBunTarget(),\n base: config.base ?? \"gcr.io/distroless/static-debian12\",\n minify: config.minify ?? true,\n };\n }\n\n /**\n * Resolve the default Bun target triple for the current host arch.\n * Always targets linux-musl (the container OS), regardless of build host.\n */\n protected defaultBunTarget(): string {\n switch (process.arch) {\n case \"x64\":\n return \"bun-linux-x64-musl\";\n case \"arm64\":\n return \"bun-linux-arm64-musl\";\n default:\n throw new AlephaError(\n `No bun linux-musl target available for host arch '${process.arch}'. ` +\n \"Set `build.docker.compile.target` explicitly.\",\n );\n }\n }\n\n /**\n * Build the `bun build --compile` invocation. Runs from `<root>/<dist>` so\n * the entry path stays relative and the output lands next to the migrations.\n */\n protected buildCompileCommand(compile: ResolvedCompile): string {\n const parts = [\n \"bun build\",\n \"--compile\",\n `--target=${compile.target}`,\n compile.minify ? \"--minify\" : \"\",\n \"--outfile=app\",\n \"index.js\",\n ].filter(Boolean);\n return parts.join(\" \");\n }\n\n /**\n * Compile mode requires fully-bundled output. If Vite left anything in\n * `dist/package.json`'s `dependencies`, fail loudly so the user can\n * either bundle the dep or disable compile.\n */\n protected async assertNoExternals(\n root: string,\n distDir: string,\n ): Promise<void> {\n const pkgPath = this.fs.join(root, distDir, \"package.json\");\n if (!(await this.fs.exists(pkgPath))) {\n return;\n }\n let pkg: { dependencies?: Record<string, string> };\n try {\n pkg = JSON.parse((await this.fs.readFile(pkgPath)).toString());\n } catch {\n return;\n }\n const deps = pkg.dependencies ?? {};\n const names = Object.keys(deps);\n if (names.length > 0) {\n throw new AlephaError(\n `Cannot use compile mode: the following dependencies were not bundled by Vite: ${names.join(\", \")}. ` +\n \"All dependencies must be bundleable to produce a single-binary build.\",\n );\n }\n }\n\n /**\n * Remove artifacts that are no longer needed once the binary exists.\n * The binary embeds the JS bundle and runtime; the standalone files\n * would just bloat the image.\n */\n protected async cleanupPreCompileArtifacts(\n root: string,\n distDir: string,\n ): Promise<void> {\n const targets = [\n this.fs.join(root, distDir, \"server\"),\n this.fs.join(root, distDir, \"index.js\"),\n this.fs.join(root, distDir, \"package.json\"),\n ];\n for (const target of targets) {\n if (await this.fs.exists(target)) {\n await this.fs.rm(target, { recursive: true });\n }\n }\n }\n\n protected async copyMigrations(\n root: string,\n distDir: string,\n ): Promise<boolean> {\n const migrationsDir = this.fs.join(root, \"migrations\");\n if (await this.fs.exists(migrationsDir)) {\n await this.fs.cp(\n migrationsDir,\n this.fs.join(root, distDir, \"migrations\"),\n );\n return true;\n }\n return false;\n }\n\n /**\n * Whether the produced `dist/package.json` declares any runtime\n * dependencies. Alepha apps normally bundle everything into the\n * server entry via Vite, leaving `dependencies: {}` — in which case\n * the generated Dockerfile's `RUN npm install` is wasted work\n * (and emits deprecation noise). Skip the line when empty.\n */\n protected async hasRuntimeDeps(\n root: string,\n distDir: string,\n ): Promise<boolean> {\n try {\n const pkg = await this.fs.readJsonFile<{\n dependencies?: Record<string, string>;\n }>(this.fs.join(root, distDir, \"package.json\"));\n return Object.keys(pkg.dependencies ?? {}).length > 0;\n } catch {\n // No package.json in dist/ → nothing to install.\n return false;\n }\n }\n\n protected async writeDockerfile(\n root: string,\n distDir: string,\n opts: {\n compile: ResolvedCompile | null;\n standard: { image: string; command: string };\n hasMigrations: boolean;\n hasDeps: boolean;\n install: string[];\n },\n ): Promise<void> {\n const header =\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 const migrationsLine = opts.hasMigrations\n ? \"COPY migrations ./migrations\\n\"\n : \"\";\n\n let dockerfile: string;\n\n if (opts.compile) {\n // `install` is ignored in compile mode — distroless has no npm.\n dockerfile = `${header}FROM ${opts.compile.base}\nWORKDIR /app\n\nCOPY app .\n${migrationsLine}\nENV SERVER_HOST=0.0.0.0\n\nENTRYPOINT [\"/app/app\"]\n`;\n } else {\n const { image, command } = opts.standard;\n // Skip `RUN <pm> install` when `dist/package.json` declares no\n // runtime deps — Alepha apps normally bundle everything via Vite,\n // making the install a no-op that just emits deprecation noise.\n const baseInstallLine = opts.hasDeps\n ? `RUN ${command === \"bun\" ? \"bun\" : \"npm\"} install\\n`\n : \"\";\n // Install requested packages locally (no --global). They land in\n // `/app/node_modules/`, alongside the app's own deps. Use\n // `--no-save` so we don't mutate the bundled package.json. Node\n // module resolution walks up into `/app/node_modules/` when the\n // workspace lives under `/app/workspace/<deploy-id>/`.\n const extraInstallLine = opts.install.length\n ? `RUN npm install --no-save --no-fund --no-audit ${opts.install.join(\" \")}\\n`\n : \"\";\n dockerfile = `${header}FROM ${image}\nWORKDIR /app\n\nCOPY . .\n\n${baseInstallLine}${extraInstallLine}\nENV SERVER_HOST=0.0.0.0\n\nCMD [\"${command}\", \"index.js\"]\n`;\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.flags?.prebuilt) {\n return;\n }\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 { $inject } from \"alepha\";\nimport { FileSystemProvider } from \"alepha/system\";\nimport { BuildTask, type BuildTaskContext } from \"./BuildTask.ts\";\n\n/**\n * Generate PWA web app manifest.\n *\n * Produces a `manifest.webmanifest` in the public output directory\n * from the `pwa` section of build options. Detects icons from `public/`.\n */\nexport class BuildPwaTask extends BuildTask {\n protected readonly fs = $inject(FileSystemProvider);\n\n async run(ctx: BuildTaskContext): Promise<void> {\n if (ctx.flags?.prebuilt) {\n return;\n }\n const pwa = ctx.options.pwa;\n if (!pwa || !ctx.hasClient) {\n return;\n }\n\n const distDir = ctx.options.output?.dist ?? \"dist\";\n const publicDir = ctx.options.output?.public ?? \"public\";\n const outputDir = this.fs.join(ctx.root, distDir, publicDir);\n\n await ctx.run({\n name: \"generate pwa manifest\",\n handler: async () => {\n const icons = await this.detectIcons(outputDir);\n\n const manifest: Record<string, unknown> = {\n name: pwa.name,\n short_name: pwa.shortName ?? pwa.name,\n start_url: \"/\",\n display: pwa.display ?? \"standalone\",\n theme_color: pwa.themeColor ?? \"#ffffff\",\n background_color: pwa.backgroundColor ?? \"#ffffff\",\n };\n\n if (icons.length > 0) {\n manifest.icons = icons;\n }\n\n const output = this.fs.join(outputDir, \"manifest.webmanifest\");\n await this.fs.writeFile(output, JSON.stringify(manifest, null, 2));\n },\n });\n }\n\n /**\n * Detect icon files in the public output directory.\n *\n * Looks for common icon filenames and generates\n * manifest icon entries with appropriate sizes and types.\n */\n protected async detectIcons(\n publicDir: string,\n ): Promise<Array<{ src: string; sizes: string; type: string }>> {\n const icons: Array<{ src: string; sizes: string; type: string }> = [];\n\n const candidates: Array<{\n file: string;\n sizes: string;\n type: string;\n }> = [\n { file: \"icon-192.png\", sizes: \"192x192\", type: \"image/png\" },\n { file: \"icon-512.png\", sizes: \"512x512\", type: \"image/png\" },\n { file: \"icon.svg\", sizes: \"any\", type: \"image/svg+xml\" },\n ];\n\n for (const candidate of candidates) {\n if (await this.fs.exists(this.fs.join(publicDir, candidate.file))) {\n icons.push({\n src: `/${candidate.file}`,\n sizes: candidate.sizes,\n type: candidate.type,\n });\n }\n }\n\n return icons;\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 if (ctx.flags?.prebuilt) {\n return;\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 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 codeSplitting: {\n groups: [\n {\n name: \"react\",\n test: /node_modules\\/react(\\/|-dom\\/)/,\n },\n ],\n },\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 const path: string = options.path ?? \"\";\n if (options.children) {\n return false;\n }\n if (path.includes(\"*\")) {\n return false;\n }\n if (path === \"/404\") {\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 type { CronProvider } from \"alepha/scheduler\";\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(\n outputDir,\n ctx.options.vercel?.config,\n this.collectCronJobs(ctx),\n );\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 * Collect every registered `$scheduler` / `$job({ cron })` and turn it\n * into a Vercel Cron entry. Vercel hits `path` on the configured\n * `schedule`; the entry-point handler routes that to a `serverless:cron`\n * event so `CronProvider` runs the matching job in-process.\n *\n * Mirrors the equivalent in `BuildCloudflareTask.enhanceCron`, except\n * Vercel needs one path per job (it doesn't dispatch by cron expression\n * the way Cloudflare does).\n */\n protected collectCronJobs(\n ctx: BuildTaskContext,\n ): { path: string; schedule: string }[] {\n if (ctx.alepha.primitives(\"scheduler\").length === 0) {\n // `$job` registers cron jobs through the same provider, so the\n // primitives count covers both `$scheduler` and `$job({ cron })`.\n }\n\n let cronProvider: CronProvider | undefined;\n try {\n cronProvider = ctx.alepha.inject(\"CronProvider\") as CronProvider;\n } catch {}\n\n const jobs = cronProvider?.getCronJobs();\n if (!jobs || jobs.length === 0) {\n return [];\n }\n\n return jobs.map((job) => ({\n path: `/_alepha/cron/${encodeURIComponent(job.name)}`,\n schedule: job.expression,\n }));\n }\n\n /**\n * Write .vercel/output/config.json with Build Output API v3 format.\n *\n * `userCrons` are merged with auto-collected `$scheduler` / `$job({ cron })`\n * entries — explicit user config wins on conflicting paths.\n */\n protected async writeOutputConfig(\n outputDir: string,\n config?: { crons?: { path: string; schedule: string }[] },\n autoCrons: { 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 const merged = new Map<string, { path: string; schedule: string }>();\n for (const c of autoCrons) merged.set(c.path, c);\n for (const c of config?.crons ?? []) merged.set(c.path, c);\n const crons = [...merged.values()];\n if (crons.length > 0) {\n outputConfig.crons = 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\nconst CRON_PREFIX = \"/_alepha/cron/\";\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 // Vercel Cron triggers are HTTP GETs to a configured path. We route them\n // to the CronProvider via an event so the same job declaration works on\n // Vercel, Cloudflare, and long-running Node alike. Vercel signs cron\n // requests with \\`Authorization: Bearer \\${CRON_SECRET}\\`; the secret is\n // available as \\`process.env.CRON_SECRET\\`. When set, we require the\n // header to match before triggering.\n const url = req.url || \"\";\n if (url.startsWith(CRON_PREFIX)) {\n const expected = process.env.CRON_SECRET;\n if (expected) {\n const got = (req.headers?.authorization || \"\").replace(/^Bearer\\\\s+/i, \"\");\n if (got !== expected) {\n res.writeHead(401, { \"content-type\": \"text/plain\" });\n res.end(\"Unauthorized\");\n return;\n }\n }\n const name = decodeURIComponent(url.slice(CRON_PREFIX.length).split(\"?\")[0]);\n try {\n await __alepha.events.emit(\"serverless:cron\", { name });\n res.writeHead(200, { \"content-type\": \"text/plain\" });\n res.end(\"ok\");\n } catch (err) {\n __alepha.log.error(\\`Cron trigger '\\${name}' failed\\`, err);\n res.writeHead(500, { \"content-type\": \"text/plain\" });\n res.end(\"cron failed\");\n }\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 { BuildPwaTask } from \"../tasks/BuildPwaTask.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(BuildPwaTask),\n $inject(BuildPrerenderTask),\n $inject(BuildVercelTask),\n $inject(BuildCloudflareTask),\n $inject(BuildDockerTask),\n $inject(BuildStaticTask),\n $inject(BuildCompressTask),\n ];\n\n /**\n * Value aliases accepted for `--target`.\n *\n * These let the CLI accept short forms (e.g. `--target cf`) that are\n * canonicalized to a real {@link BuildTarget} before they flow into the\n * pipeline. The enum in `flags.target` must also list the alias so it\n * passes schema validation.\n */\n protected readonly targetAliases: Record<string, BuildTarget> = {\n cf: \"cloudflare\",\n };\n\n /**\n * Canonicalize a raw `--target` value, mapping any known alias\n * (e.g. `cf` → `cloudflare`) to its real {@link BuildTarget}.\n */\n protected resolveTarget(target: string | undefined): BuildTarget | undefined {\n if (!target) {\n return undefined;\n }\n return this.targetAliases[target] ?? (target as BuildTarget);\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\", \"cf\", \"static\"], {\n aliases: [\"t\"],\n description: \"Deployment target (cf = cloudflare)\",\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 compile: t.optional(\n t.boolean({\n aliases: [\"c\"],\n description:\n \"Compile server to a single static binary (requires --target=docker --runtime=bun)\",\n }),\n ),\n prebuilt: t.optional(\n t.boolean({\n description:\n \"Skip the bundle steps (Vite client/server + asset compression). Only regenerates target-specific deploy config (e.g. wrangler.jsonc). Use when `dist/` is already built and you just need the config refreshed.\",\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 const target = this.resolveTarget(flags.target) ?? current.target;\n return {\n ...current,\n stats: flags.stats ?? current.stats ?? false,\n target,\n runtime: this.resolveRuntime(\n target,\n flags.runtime ?? current.runtime,\n ),\n ...(flags.compile !== undefined && {\n docker: {\n ...current.docker,\n compile: flags.compile\n ? (current.docker?.compile ?? true)\n : false,\n },\n }),\n ...(flags.sitemap && {\n sitemap: { hostname: flags.sitemap },\n }),\n };\n });\n\n const options = this.options;\n\n const distDir = options.output?.dist ?? \"dist\";\n\n // Prebuilt mode: skip clean + Vite builds + asset compression; only\n // regenerate target-specific deploy config (e.g. wrangler.jsonc).\n // Used by external orchestrators (Rocket) that ship a pre-built\n // dist/ and just need the config refreshed for per-tenant overrides.\n if (!flags.prebuilt) {\n await run.rm(distDir, { alias: \"clean dist\" });\n }\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 // Validate --compile requires --target=docker --runtime=bun\n if (options.docker?.compile) {\n if (target !== \"docker\") {\n throw new AlephaError(\n `Compile mode requires '--target=docker', got '${target ?? \"bare\"}'`,\n );\n }\n if (options.runtime !== \"bun\") {\n throw new AlephaError(\n `Compile mode requires '--runtime=bun', got '${options.runtime}'`,\n );\n }\n }\n\n this.log.trace(\"Build configuration\", {\n target,\n runtime: options.runtime,\n });\n\n // Prebuilt + manifest fast-path: skip `analyze app` (which boots\n // the workspace via Vite and requires its full node_modules tree).\n // BuildCloudflareTask reads from `ctx.manifest` instead of from\n // `ctx.alepha` in this mode. Falls back to the introspection path\n // when no manifest is present (older artifacts).\n let manifest: Awaited<ReturnType<typeof this.loadManifest>> = null;\n if (flags.prebuilt) {\n manifest = await this.loadManifest(root);\n }\n\n let appAlepha: Alepha | undefined;\n let hasClient = false;\n\n if (!manifest) {\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\n // Read platformOptions from the CLI's Alepha instance — this is\n // where alepha.config.ts wrote them during the configure hook.\n // The workspace's appAlepha (from Vite) is a separate instance\n // and doesn't have these. Captured here so BuildCloudflareTask\n // can serialize them into dist/manifest.json without needing to\n // re-load alepha.config.ts at deploy time.\n const platformOptions =\n (this.alepha.store.get(\"alepha.cli.platform.options\") as\n | BuildTaskContext[\"platformOptions\"]\n | undefined) ?? null;\n\n const ctx: BuildTaskContext = {\n // Cast: when manifest mode is active, BuildCloudflareTask reads\n // from ctx.manifest and never dereferences ctx.alepha. Bundle\n // tasks (BuildClient/Server/etc.) self-guard on ctx.flags.prebuilt\n // and return early, so they don't touch alepha either.\n alepha: (appAlepha ?? null) as unknown as Alepha,\n options,\n root,\n run,\n entry,\n hasClient,\n manifest,\n platformOptions,\n flags: { image: flags.image, prebuilt: flags.prebuilt },\n };\n\n for (const task of this.pipeline) {\n await task.run(ctx);\n }\n },\n });\n\n /**\n * Read `dist/manifest.json` produced by a previous `alepha build`.\n * Returns null when absent or unparseable — caller falls back to the\n * Vite-introspection path.\n */\n protected async loadManifest(root: string) {\n try {\n const fs = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n const raw = await fs.readFile(\n path.join(root, \"dist\", \"manifest.json\"),\n \"utf-8\",\n );\n return JSON.parse(\n raw,\n ) as import(\"../tasks/BuildCloudflareTask.ts\").BuildManifest;\n } catch {\n return null;\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 // drizzle-kit ships embedded in `alepha` — resolve and run it from\n // alepha's own install, so the project never declares it.\n // `global: true` because the command starts with `node` (a system\n // binary) — without it, exec tries to resolve `node` as a\n // node_modules bin and fails.\n const drizzleKit = this.utils.resolveBin(\"drizzle-kit\");\n await this.utils.exec(\n `node \"${drizzleKit}\" ${options.command} --config=${drizzleConfigJsPath}${flags}`,\n {\n global: true,\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 // React component (.tsx/.jsx) edits always need the SSR module\n // graph invalidated — the `_ssrModule` shortcut below misses files\n // that are workspace-linked source-only (e.g. `@alepha/ui/...`).\n // Those don't carry an `_ssrModule` ref on `ctx.modules[0]` on\n // first edit and get classified as browser-only, leaving stale\n // SSR HTML and triggering hydration mismatches on next request.\n const isTsx = /\\.(tsx|jsx)$/.test(ctx.file);\n if (!isTsx) {\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\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(`<script type=\"module\">import \"/${style}\";</script>`);\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, across both client and\n * SSR module graphs.\n *\n * Vite registers a file under multiple module ids (one per query\n * variant — e.g. `?v=…`, `?import` and the bare path), and `getModuleById`\n * only matches one. For workspace-linked source files (`@alepha/ui/...`)\n * the SSR-graph entry is keyed by the absolute path while the client\n * may use the package-qualified id. `getModulesByFile` returns every\n * variant Vite knows about for a given absolute path — invalidating\n * each catches both halves of the dual graph and prevents stale SSR\n * compiled exports from surviving across edits.\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 invalidated.add(file);\n\n const mods = new Set([\n ...(graph.getModulesByFile(file) ?? []),\n ...(graph.getModuleById(file) ? [graph.getModuleById(file)!] : []),\n ]);\n if (mods.size === 0) continue;\n\n for (const mod of mods) {\n graph.invalidateModule(mod);\n for (const importer of mod.importers) {\n const key = importer.file ?? importer.id;\n if (key && !invalidated.has(key)) {\n queue.push(key);\n }\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 tailwind: t.optional(\n t.boolean({\n description: \"Include Tailwind CSS with Vite plugin. Implies --react\",\n }),\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 { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class LintCommand {\n protected readonly utils = $inject(AlephaCliUtils);\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 // Biome ships embedded in `alepha` — resolve and run it from alepha's\n // own install, so the project never declares it.\n const biome = this.utils.resolveBin(\"@biomejs/biome\", \"biome\");\n await run(`node \"${biome}\" check --fix`);\n },\n });\n}\n","import { $inject, AlephaError, t } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { $logger } from \"alepha/logger\";\nimport { FileSystemProvider, ShellProvider } from \"alepha/system\";\n\n/**\n * Pack the workspace into a deployable `tar.gz`.\n *\n * The tar contains everything a remote runner (Alepha Rocket, or any\n * `alepha platform <op> --prebuilt` consumer) needs to deploy the app:\n *\n * dist/ pre-built output (incl. manifest.json)\n * migrations/ SQL files (if present)\n *\n * No source, no `alepha.config.ts`, no `package.json` — the deploy\n * side reads everything from `dist/manifest.json` and never touches\n * source. Excludes: `node_modules`, `.DS_Store`, macOS AppleDouble\n * (`._*`), `.alepha` build cache, `e2e`, `playwright-report`,\n * `coverage`.\n *\n * Output name: `<project-name>-<tag>.tar.gz` (default tag\n * \"latest\"). Project name comes from `package.json.name`. Naming\n * mirrors Docker tags — same artifact, different tag = different\n * file.\n */\nexport class PackCommand {\n protected readonly log = $logger();\n protected readonly fs = $inject(FileSystemProvider);\n protected readonly shell = $inject(ShellProvider);\n\n public readonly pack = $command({\n name: \"pack\",\n description:\n \"Pack the workspace into a deployable tar.gz (for `alepha platform --prebuilt` consumers like Alepha Rocket).\",\n flags: t.object({\n tag: t.optional(\n t.text({\n aliases: [\"t\"],\n description:\n \"Tag suffix for the artifact name (Docker-style). Defaults to `latest` → `<project>-latest.tar.gz`. Pass a real version like `0.0.2` for a pinned artifact.\",\n }),\n ),\n output: t.optional(\n t.text({\n aliases: [\"o\"],\n description:\n \"Output directory for the tar.gz (default: current dir).\",\n }),\n ),\n }),\n handler: async ({ flags, root, run }) => {\n const pkgPath = this.fs.join(root, \"package.json\");\n let project: string;\n try {\n const pkg = await this.fs.readJsonFile<{ name?: string }>(pkgPath);\n if (!pkg.name) {\n throw new AlephaError(\n 'Missing \"name\" in package.json — `alepha pack` needs it for the artifact filename.',\n );\n }\n project = pkg.name;\n } catch (err) {\n if (err instanceof AlephaError) throw err;\n throw new AlephaError(\n `Could not read package.json at ${pkgPath}. Run \\`alepha pack\\` from a workspace directory.`,\n );\n }\n\n const tag = flags.tag ?? \"latest\";\n const outputDir = flags.output ?? root;\n const filename = `${project}-${tag}.tar.gz`;\n const outputPath = this.fs.join(outputDir, filename);\n\n // Include list: just `dist/` + `migrations/`. Everything else\n // (src, alepha.config.ts, tsconfig.json, package.json) is\n // dev-time scaffolding — the deploy side reads\n // `dist/manifest.json` for project/env/resources and never\n // touches source.\n const candidates = [\"dist\", \"migrations\"];\n const includes: string[] = [];\n for (const candidate of candidates) {\n if (await this.fs.exists(this.fs.join(root, candidate))) {\n includes.push(candidate);\n }\n }\n\n if (!includes.includes(\"dist\")) {\n throw new AlephaError(\n \"dist/ missing — run `alepha build --target=cloudflare` before `alepha pack`.\",\n );\n }\n const manifestPath = this.fs.join(root, \"dist\", \"manifest.json\");\n if (!(await this.fs.exists(manifestPath))) {\n throw new AlephaError(\n `dist/manifest.json missing — required for prebuilt deploys. Rebuild with the current alepha version (\\`alepha build --target=cloudflare\\`).`,\n );\n }\n\n // macOS sets COPYFILE_DISABLE=0 by default; tar will then include\n // AppleDouble `._*` files. Force it off here so the tarball is\n // portable. Also pass explicit excludes for `node_modules`,\n // `.DS_Store`, etc. — they slip in via `dist/`.\n const excludes = [\n \"node_modules\",\n \".DS_Store\",\n \"._*\",\n \".alepha\",\n \"e2e\",\n \"playwright-report\",\n \"test-results\",\n \"coverage\",\n ]\n .map((p) => `--exclude='${p}'`)\n .join(\" \");\n\n const tarCmd = `tar -czf '${outputPath}' ${excludes} ${includes.map((p) => `'${p}'`).join(\" \")}`;\n // Wrap in `sh -c` so the env-var assignment is interpreted by the\n // shell instead of being parsed as the binary name. COPYFILE_DISABLE\n // suppresses macOS AppleDouble (`._*`) entries that tar otherwise\n // emits when running on HFS+/APFS.\n const cmd = `sh -c \"COPYFILE_DISABLE=1 ${tarCmd}\"`;\n\n await run({\n name: `pack → ${filename}`,\n handler: async () => {\n await this.shell.run(cmd, { root });\n },\n });\n\n this.log.info(`Packed ${filename} → ${outputPath}`);\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 \"../alephaPackageJson.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 { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TestCommand {\n protected readonly utils = $inject(AlephaCliUtils);\n protected readonly scaffolder = $inject(ProjectScaffolder);\n\n public readonly test = $command({\n name: \"test\",\n description:\n \"Run tests using Vitest. Pass a filter to run only matching specs, e.g. `alepha test user` or `alepha test test/auth.spec.ts`\",\n args: t.optional(\n t.text({\n title: \"filter\",\n description: \"Only run spec files whose path matches this string\",\n }),\n ),\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, args }) => {\n await this.scaffolder.ensureConfig(root, {\n tsconfigJson: true,\n });\n\n const config = flags.config ? `--config=${flags.config}` : \"\";\n\n // The positional arg is forwarded to Vitest as a filename filter —\n // `alepha test user` runs only specs whose path matches \"user\".\n const filter = args ? JSON.stringify(args) : \"\";\n\n // Vitest ships embedded in `alepha` (paired with vite) — resolve and\n // run it from alepha's own install, so the project never declares it.\n const vitest = this.utils.resolveBin(\"vitest\", \"vitest\");\n await run(\n `node \"${vitest}\" run ${config} ${filter} ${env.VITEST_ARGS}`\n .replace(/\\s+/g, \" \")\n .trim(),\n );\n },\n });\n}\n","import { $inject } from \"alepha\";\nimport { $command } from \"alepha/command\";\nimport { AlephaCliUtils } from \"../services/AlephaCliUtils.ts\";\nimport { ProjectScaffolder } from \"../services/ProjectScaffolder.ts\";\n\nexport class TypecheckCommand {\n protected readonly utils = $inject(AlephaCliUtils);\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 // TypeScript ships embedded in `alepha` — resolve and run its `tsc`\n // from alepha's own install, so the project never declares it.\n const tsc = this.utils.resolveBin(\"typescript\", \"tsc\");\n await run(`node \"${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 a `test/` directory exists)\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 // Vitest ships embedded in `alepha`, so it's no longer a project\n // dependency — gate on the presence of a `test/` directory instead.\n if (await this.utils.exists(root, \"test\")) {\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 { PackCommand } from \"./commands/pack.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 \"./alephaPackageJson.ts\";\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/pack.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\";\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 PackCommand,\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,KAAK,CAAC;EAC3B,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC;EAC5B,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC;CAC5B,CAAC;CACD,SAAS,CAAC;AACZ,CAAC;;;;;;;;;ACqBD,MAAa,eAAe,MAAM;CAChC,MAAM;CACN,aAAa;CACb,QAAQ,EAAE,OAAO;;;;;;;EAOf,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;;;;;;;;EAS1D,QAAQ,EAAE,SACR,EAAE,KAAK;GAAC;GAAQ;GAAU;GAAU;GAAc;EAAQ,CAAC,CAC7D;;;;;;;;;;;;EAaA,SAAS,EAAE,SAAS,EAAE,KAAK;GAAC;GAAQ;GAAO;EAAS,CAAC,CAAC;;;;EAKtD,QAAQ,EAAE,SACR,EAAE,OAAO;;;;;;GAMP,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,OAAO,CAAC,CAAC;;;;;;GAO9C,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,SAAS,CAAC,CAAC;EACpD,CAAC,CACH;;;;;;;EAQA,QAAQ,EAAE,SACR,EAAE,OAAO;GACP,aAAa,EAAE,SAAS,EAAE,OAAO,CAAC;GAClC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;GAC5B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