God Mode - Complete Parasite Application

This commit is contained in:
cawcenter
2025-12-15 18:22:03 -05:00
parent f658f76941
commit 6e826de942
38 changed files with 2153 additions and 201 deletions

View File

@@ -8,6 +8,7 @@ const currentPath = Astro.url.pathname;
import SystemStatus from '@/components/admin/SystemStatus';
import SystemStatusBar from '@/components/admin/SystemStatusBar';
import DevStatus from '@/components/admin/DevStatus.astro';
import { GlobalToaster, CoreProvider } from '@/components/providers/CoreProviders';
@@ -234,5 +235,11 @@ function isActive(href: string) {
<!-- Full-Width System Status Bar -->
<SystemStatusBar client:load />
<GlobalToaster client:load />
<!-- Universal Dev Status -->
<DevStatus
pageStatus="active"
dbStatus="connected"
/>
</body>
</html>

View File

@@ -1,37 +1,15 @@
import { query } from '../db';
/**
* Directus Shim for Valhalla
* Translates Directus SDK calls to Raw SQL (Server) or Proxy API (Client).
*/
const isServer = typeof window === 'undefined';
import type { Query } from './types';
const PROXY_ENDPOINT = '/api/god/proxy';
// --- Types ---
interface QueryCmp {
_eq?: any;
_neq?: any;
_gt?: any;
_lt?: any;
_contains?: any;
_in?: any[];
}
interface QueryFilter {
[field: string]: QueryCmp | QueryFilter | any;
_or?: QueryFilter[];
_and?: QueryFilter[];
}
interface Query {
filter?: QueryFilter;
fields?: string[];
limit?: number;
offset?: number;
sort?: string[];
aggregate?: any;
}
// Re-export types for consumers
export * from './types';
// --- SDK Mocks ---
@@ -68,8 +46,10 @@ export function aggregate(collection: string, q?: Query) {
export function getDirectusClient() {
return {
request: async (command: any) => {
if (isServer) {
// SERVER-SIDE: Direct DB Access
// Check if running on server via import.meta.env provided by Vite/Astro
if (import.meta.env.SSR) {
// SERVER-SIDE: Dynamic import to avoid bundling 'pg' in client
const { executeCommand } = await import('./server');
return await executeCommand(command);
} else {
// CLIENT-SIDE: Proxy via HTTP
@@ -82,7 +62,7 @@ export function getDirectusClient() {
// --- Proxy Execution (Client) ---
async function executeProxy(command: any) {
const token = localStorage.getItem('godToken') || ''; // Assuming auth token storage
const token = typeof localStorage !== 'undefined' ? localStorage.getItem('godToken') : '';
const res = await fetch(PROXY_ENDPOINT, {
method: 'POST',
headers: {
@@ -100,174 +80,3 @@ async function executeProxy(command: any) {
return await res.json();
}
// --- Server Execution (Server) ---
// This is exported so the Proxy Endpoint can use it too!
export async function executeCommand(command: any) {
try {
switch (command.type) {
case 'readItems':
return await executeReadItems(command.collection, command.query);
case 'readItem':
return await executeReadItem(command.collection, command.id, command.query);
case 'createItem':
return await executeCreateItem(command.collection, command.data);
case 'updateItem':
return await executeUpdateItem(command.collection, command.id, command.data);
case 'deleteItem':
return await executeDeleteItem(command.collection, command.id);
case 'aggregate':
return await executeAggregate(command.collection, command.query);
default:
throw new Error(`Unknown command type: ${command.type}`);
}
} catch (err: any) {
console.error(`Shim Error (${command.type} on ${command.collection}):`, err);
throw err;
}
}
// --- SQL Builders ---
async function executeReadItems(collection: string, q: Query = {}) {
// SECURITY: Validate collection name to prevent SQL injection via simple table name abuse
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
let sql = `SELECT ${buildSelectFields(q.fields)} FROM "${collection}"`;
const params: any[] = [];
if (q.filter) {
const { where, vals } = buildWhere(q.filter, params);
if (where) sql += ` WHERE ${where}`;
}
// Sort
if (q.sort) {
const orderBy = q.sort.map(s => {
const desc = s.startsWith('-');
const field = desc ? s.substring(1) : s;
if (!/^[a-zA-Z0-9_]+$/.test(field)) return 'id'; // sanitize
return `"${field}" ${desc ? 'DESC' : 'ASC'}`;
}).join(', ');
if (orderBy) sql += ` ORDER BY ${orderBy}`;
}
// Limit/Offset
if (q.limit !== undefined && q.limit !== -1) sql += ` LIMIT ${q.limit}`;
if (q.offset) sql += ` OFFSET ${q.offset}`;
const res = await query(sql, params);
return res.rows;
}
async function executeReadItem(collection: string, id: string | number, q: Query = {}) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const res = await query(`SELECT * FROM "${collection}" WHERE id = $1`, [id]);
return res.rows[0];
}
async function executeCreateItem(collection: string, data: any) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const keys = Object.keys(data);
const vals = Object.values(data);
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
const cols = keys.map(k => `"${k}"`).join(', ');
const sql = `INSERT INTO "${collection}" (${cols}) VALUES (${placeholders}) RETURNING *`;
const res = await query(sql, vals);
return res.rows[0];
}
async function executeUpdateItem(collection: string, id: string | number, data: any) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const keys = Object.keys(data);
const vals = Object.values(data);
const setClause = keys.map((k, i) => `"${k}" = $${i + 2}`).join(', ');
const sql = `UPDATE "${collection}" SET ${setClause} WHERE id = $1 RETURNING *`;
const res = await query(sql, [id, ...vals]);
return res.rows[0];
}
async function executeDeleteItem(collection: string, id: string | number) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
await query(`DELETE FROM "${collection}" WHERE id = $1`, [id]);
return true;
}
async function executeAggregate(collection: string, q: Query = {}) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
if (q.aggregate?.count) {
let sql = `SELECT COUNT(*) as count FROM "${collection}"`;
const params: any[] = [];
if (q.filter) {
const { where, vals } = buildWhere(q.filter, params);
if (where) sql += ` WHERE ${where}`;
}
const res = await query(sql, params);
return [{ count: res.rows[0].count }];
}
return [];
}
// --- Query Helpers ---
function buildSelectFields(fields?: string[]) {
if (!fields || fields.includes('*') || fields.length === 0) return '*';
const cleanFields = fields.filter(f => typeof f === 'string');
if (cleanFields.length === 0) return '*';
return cleanFields.map(f => `"${f.replace(/[^a-zA-Z0-9_]/g, '')}"`).join(', ');
}
function buildWhere(filter: QueryFilter, params: any[]): { where: string, vals: any[] } {
const conditions: string[] = [];
if (filter._or) {
const orConds = filter._or.map(f => {
const res = buildWhere(f, params);
return `(${res.where})`;
});
conditions.push(`(${orConds.join(' OR ')})`);
return { where: conditions.join(' AND '), vals: params };
}
if (filter._and) {
const andConds = filter._and.map(f => {
const res = buildWhere(f, params);
return `(${res.where})`;
});
conditions.push(`(${andConds.join(' AND ')})`);
return { where: conditions.join(' AND '), vals: params };
}
for (const [key, val] of Object.entries(filter)) {
if (key.startsWith('_')) continue;
if (!/^[a-zA-Z0-9_]+$/.test(key)) continue; // skip invalid keys
if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
for (const [op, opVal] of Object.entries(val)) {
if (op === '_eq') {
params.push(opVal);
conditions.push(`"${key}" = $${params.length}`);
} else if (op === '_neq') {
params.push(opVal);
conditions.push(`"${key}" != $${params.length}`);
} else if (op === '_contains') {
params.push(`%${opVal}%`);
conditions.push(`"${key}" LIKE $${params.length}`);
} else if (op === '_gt') {
params.push(opVal);
conditions.push(`"${key}" > $${params.length}`);
} else if (op === '_lt') {
params.push(opVal);
conditions.push(`"${key}" < $${params.length}`);
}
}
} else {
params.push(val);
conditions.push(`"${key}" = $${params.length}`);
}
}
return { where: conditions.join(' AND '), vals: params };
}

172
src/lib/directus/server.ts Normal file
View File

@@ -0,0 +1,172 @@
import { query } from '../db';
import type { Query, QueryFilter } from './types';
// --- Server Execution (Server) ---
export async function executeCommand(command: any) {
try {
switch (command.type) {
case 'readItems':
return await executeReadItems(command.collection, command.query);
case 'readItem':
return await executeReadItem(command.collection, command.id, command.query);
case 'createItem':
return await executeCreateItem(command.collection, command.data);
case 'updateItem':
return await executeUpdateItem(command.collection, command.id, command.data);
case 'deleteItem':
return await executeDeleteItem(command.collection, command.id);
case 'aggregate':
return await executeAggregate(command.collection, command.query);
default:
throw new Error(`Unknown command type: ${command.type}`);
}
} catch (err: any) {
console.error(`Shim Error (${command.type} on ${command.collection}):`, err);
throw err;
}
}
// --- SQL Builders ---
async function executeReadItems(collection: string, q: Query = {}) {
// SECURITY: Validate collection name to prevent SQL injection via simple table name abuse
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
let sql = `SELECT ${buildSelectFields(q.fields)} FROM "${collection}"`;
const params: any[] = [];
if (q.filter) {
const { where, vals } = buildWhere(q.filter, params);
if (where) sql += ` WHERE ${where}`;
}
// Sort
if (q.sort) {
const orderBy = q.sort.map(s => {
const desc = s.startsWith('-');
const field = desc ? s.substring(1) : s;
if (!/^[a-zA-Z0-9_]+$/.test(field)) return 'id'; // sanitize
return `"${field}" ${desc ? 'DESC' : 'ASC'}`;
}).join(', ');
if (orderBy) sql += ` ORDER BY ${orderBy}`;
}
// Limit/Offset
if (q.limit !== undefined && q.limit !== -1) sql += ` LIMIT ${q.limit}`;
if (q.offset) sql += ` OFFSET ${q.offset}`;
const res = await query(sql, params);
return res.rows;
}
async function executeReadItem(collection: string, id: string | number, q: Query = {}) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const res = await query(`SELECT * FROM "${collection}" WHERE id = $1`, [id]);
return res.rows[0];
}
async function executeCreateItem(collection: string, data: any) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const keys = Object.keys(data);
const vals = Object.values(data);
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
const cols = keys.map(k => `"${k}"`).join(', ');
const sql = `INSERT INTO "${collection}" (${cols}) VALUES (${placeholders}) RETURNING *`;
const res = await query(sql, vals);
return res.rows[0];
}
async function executeUpdateItem(collection: string, id: string | number, data: any) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
const keys = Object.keys(data);
const vals = Object.values(data);
const setClause = keys.map((k, i) => `"${k}" = $${i + 2}`).join(', ');
const sql = `UPDATE "${collection}" SET ${setClause} WHERE id = $1 RETURNING *`;
const res = await query(sql, [id, ...vals]);
return res.rows[0];
}
async function executeDeleteItem(collection: string, id: string | number) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
await query(`DELETE FROM "${collection}" WHERE id = $1`, [id]);
return true;
}
async function executeAggregate(collection: string, q: Query = {}) {
if (!/^[a-zA-Z0-9_]+$/.test(collection)) throw new Error("Invalid collection name");
if (q.aggregate?.count) {
let sql = `SELECT COUNT(*) as count FROM "${collection}"`;
const params: any[] = [];
if (q.filter) {
const { where, vals } = buildWhere(q.filter, params);
if (where) sql += ` WHERE ${where}`;
}
const res = await query(sql, params);
return [{ count: res.rows[0].count }];
}
return [];
}
// --- Query Helpers ---
function buildSelectFields(fields?: string[]) {
if (!fields || fields.includes('*') || fields.length === 0) return '*';
const cleanFields = fields.filter(f => typeof f === 'string');
if (cleanFields.length === 0) return '*';
return cleanFields.map(f => `"${f.replace(/[^a-zA-Z0-9_]/g, '')}"`).join(', ');
}
function buildWhere(filter: QueryFilter, params: any[]): { where: string, vals: any[] } {
const conditions: string[] = [];
if (filter._or) {
const orConds = filter._or.map(f => {
const res = buildWhere(f, params);
return `(${res.where})`;
});
conditions.push(`(${orConds.join(' OR ')})`);
return { where: conditions.join(' AND '), vals: params };
}
if (filter._and) {
const andConds = filter._and.map(f => {
const res = buildWhere(f, params);
return `(${res.where})`;
});
conditions.push(`(${andConds.join(' AND ')})`);
return { where: conditions.join(' AND '), vals: params };
}
for (const [key, val] of Object.entries(filter)) {
if (key.startsWith('_')) continue;
if (!/^[a-zA-Z0-9_]+$/.test(key)) continue; // skip invalid keys
if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
for (const [op, opVal] of Object.entries(val)) {
if (op === '_eq') {
params.push(opVal);
conditions.push(`"${key}" = $${params.length}`);
} else if (op === '_neq') {
params.push(opVal);
conditions.push(`"${key}" != $${params.length}`);
} else if (op === '_contains') {
params.push(`%${opVal}%`);
conditions.push(`"${key}" LIKE $${params.length}`);
} else if (op === '_gt') {
params.push(opVal);
conditions.push(`"${key}" > $${params.length}`);
} else if (op === '_lt') {
params.push(opVal);
conditions.push(`"${key}" < $${params.length}`);
}
}
} else {
params.push(val);
conditions.push(`"${key}" = $${params.length}`);
}
}
return { where: conditions.join(' AND '), vals: params };
}

23
src/lib/directus/types.ts Normal file
View File

@@ -0,0 +1,23 @@
export interface QueryCmp {
_eq?: any;
_neq?: any;
_gt?: any;
_lt?: any;
_contains?: any;
_in?: any[];
}
export interface QueryFilter {
[field: string]: QueryCmp | QueryFilter | any;
_or?: QueryFilter[];
_and?: QueryFilter[];
}
export interface Query {
filter?: QueryFilter;
fields?: string[];
limit?: number;
offset?: number;
sort?: string[];
aggregate?: any;
}

View File

@@ -70,7 +70,7 @@ export const GET: APIRoute = async ({ params, request, url }) => {
const offset = parseInt(url.searchParams.get('offset') || '0');
// Sorting
const sort = url.searchParams.get('sort') || 'created_at';
const sort = url.searchParams.get('sort') || 'date_created';
const order = url.searchParams.get('order') || 'DESC';
// Search

View File

@@ -0,0 +1,287 @@
---
import { getDirectusClient, readItems } from '@/lib/directus/client';
const { articleId } = Astro.params;
if (!articleId) {
return Astro.redirect('/404');
}
const client = getDirectusClient();
let article;
try {
// @ts-ignore
const articles = await client.request(readItems('generated_articles', {
filter: { id: { _eq: articleId } },
limit: 1
}));
article = articles[0];
if (!article) {
return Astro.redirect('/404');
}
} catch (error) {
console.error('Error fetching article:', error);
return Astro.redirect('/404');
}
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{article.title} - Preview</title>
<meta name="description" content={article.metadata?.description || article.title}>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
line-height: 1.6;
color: #333;
background: #f5f5f5;
}
.preview-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem;
text-align: center;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.container {
max-width: 1200px;
margin: 2rem auto;
padding: 0 1rem;
}
.article-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
overflow: hidden;
}
.article-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
}
.article-header h1 {
font-size: 2.5rem;
margin-bottom: 0.5rem;
line-height: 1.2;
}
.article-meta {
display: flex;
gap: 1rem;
flex-wrap: wrap;
opacity: 0.9;
font-size: 0.9rem;
}
.meta-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.article-content {
padding: 2rem;
}
.article-content h2 {
color: #667eea;
margin-top: 2rem;
margin-bottom: 1rem;
font-size: 1.8rem;
}
.article-content h3 {
color: #764ba2;
margin-top: 1.5rem;
margin-bottom: 0.75rem;
font-size: 1.4rem;
}
.article-content p {
margin-bottom: 1rem;
font-size: 1.1rem;
}
.article-content ul,
.article-content ol {
margin-left: 2rem;
margin-bottom: 1rem;
}
.article-content li {
margin-bottom: 0.5rem;
}
.article-content strong {
color: #667eea;
font-weight: 600;
}
.article-footer {
background: #f8f9fa;
padding: 2rem;
border-top: 1px solid #e9ecef;
}
.metadata-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
margin-top: 1rem;
}
.metadata-item {
background: white;
padding: 1rem;
border-radius: 4px;
border-left: 3px solid #667eea;
}
.metadata-label {
font-size: 0.8rem;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.metadata-value {
font-size: 1.1rem;
font-weight: 600;
color: #333;
margin-top: 0.25rem;
}
.actions {
display: flex;
gap: 1rem;
margin-top: 2rem;
}
.btn {
padding: 0.75rem 1.5rem;
border-radius: 4px;
text-decoration: none;
font-weight: 600;
transition: all 0.2s;
display: inline-block;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: white;
color: #667eea;
border: 2px solid #667eea;
}
.btn-secondary:hover {
background: #667eea;
color: white;
}
</style>
</head>
<body>
<div class="preview-banner">
🔍 PREVIEW MODE - This is how your article will appear
</div>
<div class="container">
<div class="article-card">
<div class="article-header">
<h1>{article.title}</h1>
<div class="article-meta">
<div class="meta-item">
📅 {new Date(article.date_created).toLocaleDateString()}
</div>
<div class="meta-item">
🔗 {article.slug}
</div>
{article.metadata?.word_count && (
<div class="meta-item">
📝 {article.metadata.word_count} words
</div>
)}
{article.metadata?.seo_score && (
<div class="meta-item">
⭐ SEO Score: {article.metadata.seo_score}/100
</div>
)}
</div>
</div>
<div class="article-content">
<Fragment set:html={article.html_content} />
</div>
<div class="article-footer">
<h3>Article Metadata</h3>
<div class="metadata-grid">
<div class="metadata-item">
<div class="metadata-label">Article ID</div>
<div class="metadata-value">{article.id}</div>
</div>
<div class="metadata-item">
<div class="metadata-label">Status</div>
<div class="metadata-value">{article.status || 'Draft'}</div>
</div>
{article.metadata?.template && (
<div class="metadata-item">
<div class="metadata-label">Template</div>
<div class="metadata-value">{article.metadata.template}</div>
</div>
)}
{article.metadata?.location && (
<div class="metadata-item">
<div class="metadata-label">Target Location</div>
<div class="metadata-value">{article.metadata.location}</div>
</div>
)}
{article.generation_hash && (
<div class="metadata-item">
<div class="metadata-label">Generation Hash</div>
<div class="metadata-value" style="font-size: 0.8rem; word-break: break-all;">
{article.generation_hash}
</div>
</div>
)}
</div>
<div class="actions">
<a href={`/admin/content/generated-articles`} class="btn btn-primary">
← Back to Articles
</a>
<a href={`https://spark.jumpstartscaling.com/items/generated_articles/${article.id}`} class="btn btn-secondary" target="_blank">
Edit in Directus
</a>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,135 @@
---
/**
* Preview Page Route
* Shows a single page in preview mode
*/
import { getDirectusClient, readItem } from '@/lib/directus/client';
import BlockRenderer from '@/components/engine/BlockRenderer';
const { pageId } = Astro.params;
if (!pageId) {
return Astro.redirect('/admin/pages');
}
interface Page {
id: string;
title: string;
content: string;
blocks: any[];
status: string;
}
let page: Page | null = null;
let error: string | null = null;
try {
const client = getDirectusClient();
const result = await client.request(readItem('pages', pageId));
page = result as Page;
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to load page';
console.error('Preview error:', err);
}
import '@/styles/global.css';
if (!page && !error) {
return Astro.redirect('/admin/pages');
}
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview: {page?.title || 'Page'}</title>
<style>
.preview-banner {
position: fixed;
top: 0;
left: 0;
right: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 12px 20px;
z-index: 9999;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
display: flex;
justify-content: space-between;
align-items: center;
}
.preview-content {
margin-top: 60px;
padding: 20px;
max-width: 1200px;
margin-left: auto;
margin-right: auto;
}
.preview-badge {
background: rgba(255,255,255,0.2);
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.close-preview {
background: rgba(255,255,255,0.2);
border: none;
color: white;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
transition: background 0.2s;
}
.close-preview:hover {
background: rgba(255,255,255,0.3);
}
</style>
</head>
<body>
<!-- Preview Mode Banner -->
<div class="preview-banner">
<div style="display: flex; align-items: center; gap: 12px;">
<svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
</svg>
<span style="font-weight: 600; font-size: 14px;">PREVIEW MODE</span>
{page && <span class="preview-badge">{page.status || 'Draft'}</span>}
</div>
<div style="display: flex; gap: 12px; align-items: center;">
<span style="font-size: 13px; opacity: 0.9;">{page?.title}</span>
<button class="close-preview" onclick="window.close()">Close Preview</button>
</div>
</div>
<!-- Page Content -->
<div class="preview-content">
{error ? (
<div style="background: #fee; border: 1px solid #fcc; color: #c00; padding: 20px; border-radius: 8px;">
<h2>Error Loading Preview</h2>
<p>{error}</p>
</div>
) : page ? (
<>
<BlockRenderer blocks={page.blocks} client:load />
{(!page.blocks || page.blocks.length === 0) && page.content && (
// Fallback for content
<div style="line-height: 1.8; color: #333;" set:html={page.content}>
</div>
)}
</>
) : null}
</div>
</body>
</html>

View File

@@ -0,0 +1,282 @@
---
/**
* Preview Site Route
* Shows all pages for a site in preview mode
*/
import { getDirectusClient, readItems } from '@/lib/directus/client';
const { siteId } = Astro.params;
if (!siteId) {
return Astro.redirect('/admin/sites');
}
interface Site {
id: string;
name: string;
domain: string;
status: string;
date_created: string;
}
interface Page {
id: string;
title: string;
status: string;
permalink: string;
slug: string;
seo_description: string;
}
let site: Site | null = null;
let pages: Page[] = [];
let error: string | null = null;
try {
const client = getDirectusClient();
// Fetch site
const siteResult = await client.request(readItems('sites', {
filter: { id: { _eq: siteId } },
limit: 1
}));
site = siteResult[0] as Site;
// Fetch pages for this site
// Note: directus-shim buildWhere supports _eq
const pagesResult = await client.request(readItems('pages', {
filter: { site: { _eq: siteId } },
limit: -1
}));
pages = pagesResult as Page[];
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to load site';
console.error('Preview error:', err);
}
if (!site && !error) {
return Astro.redirect('/admin/sites');
}
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preview: {site?.name || 'Site'}</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0a0a0a;
color: #fff;
}
.preview-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
.banner-left {
display: flex;
align-items: center;
gap: 1rem;
}
.badge {
background: rgba(255,255,255,0.2);
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
}
.btn {
background: rgba(255,255,255,0.2);
border: none;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
cursor: pointer;
font-weight: 500;
transition: background 0.2s;
}
.btn:hover {
background: rgba(255,255,255,0.3);
}
.container {
max-width: 1200px;
margin: 2rem auto;
padding: 0 2rem;
}
.site-header {
background: #111;
border-radius: 0.5rem;
padding: 2rem;
margin-bottom: 2rem;
border: 1px solid #222;
}
.site-header h1 {
font-size: 2rem;
margin-bottom: 0.5rem;
}
.site-meta {
color: #888;
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.pages-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
}
.page-card {
background: #111;
border: 1px solid #222;
border-radius: 0.5rem;
padding: 1.5rem;
transition: all 0.2s;
cursor: pointer;
}
.page-card:hover {
border-color: #667eea;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}
.page-card h3 {
font-size: 1.25rem;
margin-bottom: 0.5rem;
color: #fff;
}
.page-card p {
color: #888;
font-size: 0.875rem;
margin-bottom: 1rem;
}
.page-status {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
}
.status-published {
background: #10b981;
color: white;
}
.status-draft {
background: #6b7280;
color: white;
}
.empty-state {
text-align: center;
padding: 4rem 2rem;
color: #666;
}
.empty-state svg {
width: 4rem;
height: 4rem;
margin-bottom: 1rem;
opacity: 0.3;
}
</style>
</head>
<body>
<!-- Preview Banner -->
<div class="preview-banner">
<div class="banner-left">
<svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
</svg>
<span style="font-weight: 600;">SITE PREVIEW</span>
{site && <span class="badge">{site.status || 'Active'}</span>}
</div>
<button class="btn" onclick="window.close()">Close Preview</button>
</div>
<!-- Site Content -->
<div class="container">
{error ? (
<div style="background: #fee; border: 1px solid #fcc; color: #c00; padding: 20px; border-radius: 8px;">
<h2>Error Loading Site</h2>
<p>{error}</p>
</div>
) : site ? (
<>
<div class="site-header">
<h1>{site.name}</h1>
<div class="site-meta">
<span>🌐 {site.domain}</span>
<span>📄 {pages.length} pages</span>
{site.date_created && (
<span>📅 Created {new Date(site.date_created).toLocaleDateString()}</span>
)}
</div>
</div>
<h2 style="margin-bottom: 1.5rem; font-size: 1.5rem;">Pages</h2>
{pages.length > 0 ? (
<div class="pages-grid">
{pages.map((page) => (
<div class="page-card" onclick={`window.open('/preview/page/${page.id}', '_blank')`}>
<h3>{page.title}</h3>
<p>{page.seo_description || 'No description'}</p>
<div style="display: flex; justify-between; align-items: center;">
<span class={`page-status ${page.status === 'published' ? 'status-published' : 'status-draft'}`}>
{page.status || 'draft'}
</span>
<span style="color: #666; font-size: 0.75rem;">
/{page.permalink || page.slug}
</span>
</div>
</div>
))}
</div>
) : (
<div class="empty-state">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
</svg>
<p>No pages created yet for this site.</p>
<p style="margin-top: 0.5rem; font-size: 0.875rem;">
<a href={`/admin/sites/${site.id}`} style="color: #667eea;">Create your first page →</a>
</p>
</div>
)}
</>
) : null}
</div>
</body>
</html>