managarten/apps/api/src/modules/storage/routes.ts
Till JS 919fcca4b7 refactor(shared-tailwind): rewrite themes.css to single-layer shadcn convention
Pre-launch theme system audit found multiple parallel layers in themes.css
(--theme-X full hsl strings, --X partial shadcn aliases, --color-X populated
by runtime store with raw channels) plus dead-code companion files. The
inconsistency caused light-mode regressions when scoped-CSS consumers
wrote `var(--color-X)` standalone — the variable holds raw HSL channels
which is invalid as a color value, browser fell back to inherited (white).

Rewrite to one consistent layer:

  - Source of truth: --color-X defined as raw HSL channels (e.g.
    `0 0% 17%`) in :root, .dark, and all variant [data-theme="..."]
    blocks. Matches the format the runtime store
    (@mana/shared-theme/src/utils.ts) writes, eliminating the
    static-fallback-vs-runtime mismatch and the corresponding flash
    of unstyled content on hydration.

  - @theme inline uses self-reference + Tailwind v4 <alpha-value>
    placeholder so utility classes generate correctly AND opacity
    modifiers work: `text-foreground/50` → `hsl(var(--color-foreground) / 0.5)`.

  - @layer components (.btn-primary, .card, .badge, etc.) wraps
    var(--color-X) refs with hsl() — they were broken in light mode
    too for the same reason.

Convention going forward (also documented in the file header):

  1. Markup: use Tailwind utility classes (text-foreground, bg-card, …)
  2. Scoped CSS: hsl(var(--color-X)) — always wrap with hsl()
  3. NEVER raw var(--color-X) in CSS — that's the bug pattern

Net file: 692 → 580 LOC. Single source layer, no indirection.

Also delete dead companion files (zero imports anywhere):
  - tailwind-v4.css (had broken self-reference, never imported)
  - theme-variables.css (legacy hex-based palette)
  - components.css (legacy component utilities)
  - index.js / preset.js / colors.js (Tailwind v3 preset format,
    irrelevant under Tailwind v4)

package.json exports map shrinks accordingly to just `./themes.css`.

Consumers using `hsl(var(--color-X))` (~379 files across mana-web,
manavoxel-web, arcade-web) keep working unchanged — the public API
name `--color-X` is preserved. Only the broken pattern `var(--color-X)`
(~61 files) needs a follow-up sweep, handled in a separate commit.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 01:13:06 +02:00

133 lines
4 KiB
TypeScript

/**
* Storage module — File upload/download via S3
* Ported from apps/storage/apps/server
*
* Metadata CRUD for files/folders handled by mana-sync.
* This module handles S3 operations (upload, download, presigned URLs).
*/
import { Hono } from 'hono';
import type { AuthVariables } from '@mana/shared-hono';
const routes = new Hono<{ Variables: AuthVariables }>();
// ─── File Upload (server-only: S3) ──────────────────────────
routes.post('/files/upload', async (c) => {
const userId = c.get('userId');
const formData = await c.req.formData();
const file = formData.get('file') as File | null;
const folderId = formData.get('folderId') as string | null;
if (!file) return c.json({ error: 'No file' }, 400);
if (file.size > 100 * 1024 * 1024) return c.json({ error: 'Max 100MB' }, 400);
try {
const buffer = await file.arrayBuffer();
const { isImageMimeType } = await import('../../lib/media');
// Images -> mana-media for dedup, thumbnails & Photos gallery
if (isImageMimeType(file.type)) {
const { uploadImageToMedia } = await import('../../lib/media');
const result = await uploadImageToMedia(buffer, file.name, { app: 'storage', userId });
return c.json(
{
id: crypto.randomUUID(),
name: file.name,
storagePath: result.id,
storageKey: result.id,
mimeType: file.type,
size: file.size,
parentFolderId: folderId,
mediaId: result.id,
},
201
);
}
// Non-images -> shared-storage as before
const { createStorageStorage, generateUserFileKey, getContentType } =
await import('@mana/shared-storage');
const storage = createStorageStorage();
const key = generateUserFileKey(userId, file.name);
await storage.upload(key, Buffer.from(buffer), {
contentType: getContentType(file.name),
public: false,
});
return c.json(
{
id: crypto.randomUUID(),
name: file.name,
storagePath: key,
storageKey: key,
mimeType: file.type,
size: file.size,
parentFolderId: folderId,
},
201
);
} catch (_err) {
return c.json({ error: 'Upload failed' }, 500);
}
});
// ─── File Download (server-only: S3 presigned URL) ──────────
routes.get('/files/:id/download', async (c) => {
const storagePath = c.req.query('storagePath');
const urlOnly = c.req.query('url') === 'true';
if (!storagePath) return c.json({ error: 'storagePath required' }, 400);
try {
const { createStorageStorage } = await import('@mana/shared-storage');
const storage = createStorageStorage();
if (urlOnly) {
const url = await storage.getDownloadUrl(storagePath, { expiresIn: 3600 });
return c.json({ url });
}
const [buffer, metadata] = await Promise.all([
storage.download(storagePath),
storage.getMetadata(storagePath).catch(() => null),
]);
return new Response(new Uint8Array(buffer), {
headers: {
'Content-Type': metadata?.contentType || 'application/octet-stream',
'Content-Disposition': `attachment; filename="${storagePath.split('/').pop()}"`,
},
});
} catch (_err) {
return c.json({ error: 'Download failed' }, 500);
}
});
// ─── Version Upload ─────────────────────────────────────────
routes.post('/files/:id/versions', async (c) => {
const userId = c.get('userId');
const fileId = c.req.param('id');
const formData = await c.req.formData();
const file = formData.get('file') as File | null;
if (!file) return c.json({ error: 'No file' }, 400);
try {
const { createStorageStorage, generateUserFileKey } = await import('@mana/shared-storage');
const storage = createStorageStorage();
const key = generateUserFileKey(userId, `v-${Date.now()}-${file.name}`);
const buffer = Buffer.from(await file.arrayBuffer());
await storage.upload(key, buffer, { contentType: file.type });
return c.json({ fileId, storagePath: key, size: file.size }, 201);
} catch (_err) {
return c.json({ error: 'Version upload failed' }, 500);
}
});
export { routes as storageRoutes };