Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Compile admin stylesheets on ejected projects (#14255)

Damian Legawieccfb84e2e3e69
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index af414db6f8..b837012224 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 2.3.7
+
+### Patch Changes
+
+- Compile the admin dashboard stylesheet on ejected projects. Ejecting bind-mounts `./backend` over the image's precompiled `app/assets/builds`, and the dev stack never runs `assets:precompile`, so `spree/admin/application.css` was missing and every admin page 500'd. `spree eject` now compiles it, and `spree dev` compiles it if missing and then runs the Tailwind watcher so admin edits recompile live.
+
## 2.3.6
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 8071b0c620..c987d62993 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.3.6",
+ "version": "2.3.7",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 34d6704b6a..86ada49f10 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -1,10 +1,9 @@
-import fs from 'node:fs'
import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execa } from 'execa'
import pc from 'picocolors'
-import { detectProject, hasMonorepoSpreePath } from '../context.js'
+import { detectProject, hasMonorepoSpreePath, isEjectedProject } from '../context.js'
import { dockerCompose } from '../docker.js'
export function registerBuildCommand(program: Command): void {
@@ -31,7 +30,7 @@ export function registerBuildCommand(program: Command): void {
// `spree dev` runs. After `spree eject` that contains a `build:` section
// pointing at ./backend; before eject, it's a prebuilt-image stack and
// there's nothing to rebuild.
- if (!hasBuildSection(ctx.projectDir)) {
+ if (!isEjectedProject(ctx.projectDir)) {
console.error(
`\n${pc.red('Error:')} docker-compose.yml has no \`build:\` section. ` +
`Run ${pc.bold('spree eject')} first to switch to a build-from-source stack.\n`,
@@ -96,14 +95,6 @@ export function registerBuildCommand(program: Command): void {
})
}
-function hasBuildSection(projectDir: string): boolean {
- const composeFile = path.join(projectDir, 'docker-compose.yml')
- if (!fs.existsSync(composeFile)) return false
- // Cheap YAML probe — looks for `build:` at the start of a line (the only
- // valid YAML position for a service-level build directive).
- return /^\s*build\s*:/m.test(fs.readFileSync(composeFile, 'utf-8'))
-}
-
async function resolveComposeProjectName(projectDir: string): Promise<string> {
try {
const { stdout } = await execa('docker', ['compose', 'config', '--format', 'json'], {
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
index 8516b8c1e2..6375bbf5f1 100644
--- a/packages/cli/src/commands/dev.ts
+++ b/packages/cli/src/commands/dev.ts
@@ -1,9 +1,16 @@
+import fs from 'node:fs'
+import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import pc from 'picocolors'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
-import { detectProject, hasMonorepoSpreePath } from '../context.js'
-import { dockerCompose, primeBundleVolume } from '../docker.js'
+import { detectProject, hasMonorepoSpreePath, isEjectedProject } from '../context.js'
+import {
+ buildAdminStylesheets,
+ dockerCompose,
+ primeBundleVolume,
+ watchAdminStylesheets,
+} from '../docker.js'
export function registerDevCommand(program: Command): void {
program
@@ -60,6 +67,47 @@ export function registerDevCommand(program: Command): void {
// leave the volume half-populated (a partial copy-up would make the
// next run's emptiness gate lie). On a warm volume this is a ~1s no-op.
await primeBundleVolume(ctx.projectDir)
+
+ // On an ejected project the ./backend bind-mount masks the admin
+ // stylesheet the image baked into app/assets/builds, and `bin/rails
+ // server` never (re)compiles it. First guarantee a compiled file exists
+ // for the first paint (the image's is masked; a stack ejected before
+ // this CLI shipped never had one), then start the Tailwind watcher so
+ // admin source edits recompile live — the dev server `bin/rails server`
+ // alone can't offer. Both run against the web container prime just
+ // brought up. Non-ejected stacks serve the baked asset from the image,
+ // so this is skipped there.
+ if (isEjectedProject(ctx.projectDir)) {
+ // The dev stack bind-mounts ./backend onto the container's Rails.root,
+ // so the stylesheet the tailwind task writes to Rails.root/app/assets/
+ // builds lands here on the host.
+ const adminStylesheet = path.join(
+ ctx.projectDir,
+ 'backend/app/assets/builds/spree/admin/application.css',
+ )
+ if (!fs.existsSync(adminStylesheet)) {
+ const s = p.spinner()
+ s.start('Compiling admin dashboard stylesheets...')
+ try {
+ await buildAdminStylesheets(ctx.projectDir)
+ s.stop('Admin dashboard stylesheets compiled.')
+ } catch {
+ // Non-fatal: the foreground boot below still streams logs, and the
+ // operator can rebuild explicitly. Don't abort dev over assets.
+ s.stop('Could not compile admin dashboard stylesheets — admin pages may 500.')
+ }
+ }
+
+ try {
+ await watchAdminStylesheets(ctx.projectDir)
+ p.log.info('Watching admin dashboard stylesheets — edits recompile live.')
+ } catch {
+ // Best-effort: the compiled file above still serves admin pages.
+ // A watcher that can't start (e.g. no `listen` gem) just means no
+ // live recompile, not a broken boot.
+ }
+ }
+
result = await dockerCompose(['up', 'web', 'worker'], ctx.projectDir, {
stdio: 'inherit',
reject: false,
diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.ts
index d895bcfad9..e7d2107641 100644
--- a/packages/cli/src/commands/eject.ts
+++ b/packages/cli/src/commands/eject.ts
@@ -4,7 +4,12 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import pc from 'picocolors'
import { detectProject } from '../context.js'
-import { dockerCompose, dockerComposeExec, primeBundleVolume } from '../docker.js'
+import {
+ buildAdminStylesheets,
+ dockerCompose,
+ dockerComposeExec,
+ primeBundleVolume,
+} from '../docker.js'
// Switch the project from the prebuilt-image compose to the bind-mounted
// dev compose. Source under ./backend becomes live in the container —
@@ -58,6 +63,12 @@ export function registerEjectCommand(program: Command) {
console.log(`\n${pc.bold('Preparing the development database...')}\n`)
await dockerComposeExec(['bin/rails', 'db:prepare'], ctx.projectDir, { tty: false })
+ // The bind-mount masks the admin stylesheet the image baked into
+ // app/assets/builds, and the dev stack never precompiles — compile it now
+ // so admin pages render instead of 500ing on the missing asset.
+ console.log(`\n${pc.bold('Building admin dashboard stylesheets...')}\n`)
+ await buildAdminStylesheets(ctx.projectDir)
+
p.note(
[
`Backend is now bind-mounted from ${pc.bold('./backend')} — edits are live.`,
diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts
index 4b215ea214..b4f93fbf9f 100644
--- a/packages/cli/src/context.ts
+++ b/packages/cli/src/context.ts
@@ -74,6 +74,23 @@ export function hasMonorepoSpreePath(projectDir: string): boolean {
}
}
+// A project is "ejected" once `spree eject` swaps in the dev compose, whose
+// service carries a `build:` section pointing at ./backend — the prebuilt-image
+// compose has none. Gates steps that only apply to the bind-mounted,
+// build-from-source dev stack (e.g. compiling admin assets the image would have
+// baked in but the bind-mount now masks).
+export function isEjectedProject(projectDir: string): boolean {
+ const composeFile = path.join(projectDir, 'docker-compose.yml')
+ if (!fs.existsSync(composeFile)) return false
+ try {
+ // Cheap YAML probe — `build:` at the start of a line is the only valid
+ // position for a service-level build directive.
+ return /^\s*build\s*:/m.test(fs.readFileSync(composeFile, 'utf-8'))
+ } catch {
+ return false
+ }
+}
+
export function readPortFromEnv(projectDir: string): number {
const envPath = path.join(projectDir, '.env')
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index 951d1591f8..de39b04a3f 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -81,6 +81,10 @@ export async function isServiceRunning(service: string, projectDir: string): Pro
export interface DockerComposeExecOptions {
service?: string
tty?: boolean
+ // Run the command detached (`-d`): compose starts it inside the container and
+ // returns immediately. The process shares the container's lifecycle — stop the
+ // container and it dies with it. Used for the admin Tailwind watcher.
+ detach?: boolean
env?: Record<string, string>
}
@@ -99,8 +103,9 @@ export async function dockerComposeExec(
projectDir: string,
options: DockerComposeExecOptions = {},
): Promise<void> {
- const { service = 'web', tty = true, env } = options
+ const { service = 'web', tty = true, detach = false, env } = options
const args = ['compose', 'exec']
+ if (detach) args.push('-d')
if (!tty) args.push('-T')
if (env) {
for (const [key, value] of Object.entries(env)) {
@@ -112,6 +117,34 @@ export async function dockerComposeExec(
await execa('docker', args, { cwd: projectDir, stdio: 'inherit' })
}
+// Compile the admin dashboard's Tailwind stylesheet inside the web container.
+// The prebuilt image bakes this into app/assets/builds during image build (the
+// assets:precompile hook runs spree:admin:tailwindcss:build), but the ejected
+// dev stack bind-mounts ./backend over that path and never precompiles — so
+// Propshaft has no `spree/admin/application.css` to serve and every admin page
+// 500s. Building it once persists the file into the bind-mounted
+// app/assets/builds on the host. The task reads source and runs the tailwind
+// binary; it needs no database (it runs at image build time where none exists).
+export async function buildAdminStylesheets(projectDir: string): Promise<void> {
+ await dockerComposeExec(['bin/rails', 'spree:admin:tailwindcss:build'], projectDir, {
+ tty: false,
+ })
+}
+
+// Start the admin Tailwind watcher as a detached process inside the running web
+// container. It recompiles spree/admin/application.css on every admin source
+// change — the live dev-server experience `bin/rails server` alone can't give
+// the ejected stack. Detached so it runs alongside the foreground web+worker
+// logs and shares the web container's lifecycle: stopping web (Ctrl+C during
+// `spree dev`) tears the watcher down too, leaving no orphan. Requires the
+// `listen` gem (Rails' default development group); if it's absent the task exits
+// and the one-shot build remains the compiled fallback.
+export async function watchAdminStylesheets(projectDir: string): Promise<void> {
+ await dockerComposeExec(['bin/rails', 'spree:admin:tailwindcss:watch'], projectDir, {
+ detach: true,
+ })
+}
+
export interface DockerComposeRunOptions {
service?: string
env?: Record<string, string>
diff --git a/packages/cli/tests/context.test.ts b/packages/cli/tests/context.test.ts
index 2ceafe9f46..7a410060c2 100644
--- a/packages/cli/tests/context.test.ts
+++ b/packages/cli/tests/context.test.ts
@@ -2,7 +2,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { detectProject } from '../src/context'
+import { detectProject, isEjectedProject } from '../src/context'
describe('detectProject', () => {
const tempDirs: string[] = []
@@ -102,3 +102,43 @@ describe('detectProject', () => {
expect(ctx.projectDir).toBe(backend)
})
})
+
+describe('isEjectedProject', () => {
+ const tempDirs: string[] = []
+
+ function makeTempDir(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-ejected-test-'))
+ tempDirs.push(dir)
+ return dir
+ }
+
+ afterEach(() => {
+ for (const dir of tempDirs) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ tempDirs.length = 0
+ })
+
+ it('is true when the compose has a service-level build section (dev stack)', () => {
+ const dir = makeTempDir()
+ fs.writeFileSync(
+ path.join(dir, 'docker-compose.yml'),
+ 'services:\n web:\n build:\n context: ./backend\n',
+ )
+ expect(isEjectedProject(dir)).toBe(true)
+ })
+
+ it('is false for a prebuilt-image compose with no build section', () => {
+ const dir = makeTempDir()
+ fs.writeFileSync(
+ path.join(dir, 'docker-compose.yml'),
+ 'services:\n web:\n image: spree/spree:latest\n',
+ )
+ expect(isEjectedProject(dir)).toBe(false)
+ })
+
+ it('is false when docker-compose.yml is missing', () => {
+ const dir = makeTempDir()
+ expect(isEjectedProject(dir)).toBe(false)
+ })
+})
diff --git a/packages/cli/tests/docker.test.ts b/packages/cli/tests/docker.test.ts
index bb0aa8f380..9a61219a4e 100644
--- a/packages/cli/tests/docker.test.ts
+++ b/packages/cli/tests/docker.test.ts
@@ -15,7 +15,12 @@ vi.mock('@clack/prompts', () => ({
}))
import { execa } from 'execa'
-import { dockerComposeExecOrRun, dockerComposeRun } from '../src/docker'
+import {
+ buildAdminStylesheets,
+ dockerComposeExecOrRun,
+ dockerComposeRun,
+ watchAdminStylesheets,
+} from '../src/docker'
const mockExeca = vi.mocked(execa)
@@ -105,6 +110,36 @@ describe('dockerComposeRun', () => {
})
})
+describe('buildAdminStylesheets', () => {
+ afterEach(() => mockExeca.mockReset())
+
+ it('runs the admin tailwind build via a non-interactive compose exec on web', async () => {
+ await buildAdminStylesheets('/proj')
+
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', '-T', 'web', 'bin/rails', 'spree:admin:tailwindcss:build'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ })
+})
+
+describe('watchAdminStylesheets', () => {
+ afterEach(() => mockExeca.mockReset())
+
+ it('starts the admin tailwind watcher detached inside web', async () => {
+ await watchAdminStylesheets('/proj')
+
+ // `-d` detaches so the watcher runs alongside the foreground web+worker
+ // logs and dies with the web container on Ctrl+C.
+ expect(mockExeca).toHaveBeenCalledWith(
+ 'docker',
+ ['compose', 'exec', '-d', 'web', 'bin/rails', 'spree:admin:tailwindcss:watch'],
+ { cwd: '/proj', stdio: 'inherit' },
+ )
+ })
+})
+
describe('dockerComposeExecOrRun', () => {
class ExitError extends Error {
constructor(public code: number) {
diff --git a/packages/cli/tests/eject.test.ts b/packages/cli/tests/eject.test.ts
index eb8306a2a7..20f1018ac7 100644
--- a/packages/cli/tests/eject.test.ts
+++ b/packages/cli/tests/eject.test.ts
@@ -4,7 +4,12 @@ import path from 'node:path'
import { Command } from 'commander'
import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
import { registerEjectCommand } from '../src/commands/eject'
-import { dockerCompose, dockerComposeExec, primeBundleVolume } from '../src/docker'
+import {
+ buildAdminStylesheets,
+ dockerCompose,
+ dockerComposeExec,
+ primeBundleVolume,
+} from '../src/docker'
const COMPOSE_DEV_STALE = `x-app: &app
build:
@@ -34,6 +39,7 @@ vi.mock('../src/docker', () => ({
dockerCompose: vi.fn().mockResolvedValue(undefined),
dockerComposeExec: vi.fn().mockResolvedValue(undefined),
primeBundleVolume: vi.fn().mockResolvedValue(undefined),
+ buildAdminStylesheets: vi.fn().mockResolvedValue(undefined),
}))
function makeProject(devComposeContent: string): string {
@@ -99,6 +105,17 @@ describe('spree eject', () => {
})
})
+ it('compiles the admin stylesheet the bind-mount masks', async () => {
+ projectDir = makeProject(COMPOSE_DEV_STALE)
+
+ await runEject()
+
+ // The image baked spree/admin/application.css into app/assets/builds, but
+ // eject's ./backend bind-mount masks it — without this compile every admin
+ // page 500s on the missing asset.
+ expect(buildAdminStylesheets).toHaveBeenCalledWith(projectDir)
+ })
+
it('primes the bundle volume with web before the parallel up', async () => {
projectDir = makeProject(COMPOSE_DEV_STALE)