@oktis-works/web 0.17.1 → 1.0.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 CHANGED
@@ -1,122 +1,30 @@
1
1
  # @oktis-works/web
2
2
 
3
- Theme Engine Runtime — public HTTP server that renders sites via themes.
3
+ Public HTTP host for tenant-aware OkCMS sites. The web app owns routing,
4
+ tenant context, SEO/document wrapping, plugin assets, and public response
5
+ security. Theme source code is not interpreted by this process.
4
6
 
5
- ## Public Routes
7
+ ## Theme rendering
6
8
 
7
- | Route | Handler | Description |
8
- |-------|---------|-------------|
9
- | `GET /health` | health check | DB connectivity |
10
- | `GET /themes/*` | theme assets | Static files from active theme `dist/` |
11
- | `GET /sitemap.xml` | sitemap | Hub pages + published items (canonical URLs) |
12
- | `GET /{hubBase}/feed` | RSS/Atom | Feed for hub type (RSS 2.0 default, `?format=atom` for Atom 1.0) |
13
- | `GET *` | catch-all | Theme rendering via `RuntimeRouter` |
9
+ For each request the host establishes the tenant context, resolves a logical
10
+ render key, creates a request-scoped `ThemeSdkBridge`, and invokes the compiled
11
+ theme artifact:
14
12
 
15
- ## Core Helpers (exported from `apps/web/src/`)
16
-
17
- ### `url-helpers.ts`
18
-
19
- ```typescript
20
- // Build canonical item URL from hub base + parent chain
21
- buildItemUrl(item: { slug: string }, hubBase: string, parentChain?: string[]): string
22
- // → '/projects/cliente-a/projeto-1'
23
-
24
- // Build hub listing URL
25
- buildHubUrl(base: string): string
26
- // → '/projects/'
27
-
28
- // Build feed URL
29
- buildFeedUrl(base: string): string
30
- // → '/projects/feed'
31
-
32
- // Extract parent chain from record (if pre-loaded)
33
- extractParentChain(record: Record<string, unknown>): string[]
34
- ```
35
-
36
- ### `jsonld.ts`
37
-
38
- ```typescript
39
- // Build JSON-LD array: [mainEntity, breadcrumbList]
40
- buildJsonLd(context: JsonLdContext): Record<string, unknown>[]
41
- ```
42
-
43
- **JsonLdContext:**
44
- ```typescript
45
- {
46
- canonicalUrl: string; // full canonical URL
47
- siteName: string; // site title
48
- siteUrl: string; // base site URL (e.g., 'https://example.com')
49
- hubBase?: string; // 'blog', 'projects'
50
- itemPath?: string; // 'cliente-a/projeto-1'
51
- parentChain?: string[]; // ['cliente-a']
52
- title: string;
53
- description?: string;
54
- datePublished?: string; // ISO
55
- dateModified?: string; // ISO
56
- authorName?: string;
57
- imageUrl?: string;
58
- contentType?: string; // 'post', 'page', custom
59
- }
60
- ```
61
-
62
- **Output:** `[BlogPosting|WebPage|CreativeWork, BreadcrumbList]`
63
-
64
- **Template usage:** `<script type="application/ld+json">{{{jsonLd}}}</script>`
65
-
66
- ### `rss.ts`
67
-
68
- ```typescript
69
- // Generate both RSS 2.0 and Atom 1.0
70
- generateFeeds(context: FeedContext): { rss: string; atom: string }
71
- ```
72
-
73
- **FeedContext:**
74
- ```typescript
75
- {
76
- hubBase: string;
77
- hubTitle: string;
78
- hubDescription?: string;
79
- siteName: string;
80
- siteUrl: string;
81
- contentType: string;
82
- items: Array<Record<string, unknown>>; // published items
83
- feedUrl: string; // e.g., '/blog/feed'
84
- }
13
+ ```ts
14
+ render(templateKey, pageData, renderContext, sdk)
85
15
  ```
86
16
 
87
- **Route:** `GET /{hubBase}/feed` — auto-discovers hub type via `metadata.hub_type`.
88
-
89
- ## Template Context (injected by `renderContentPage`)
90
-
91
- | Variable | Type | Description |
92
- |----------|------|-------------|
93
- | `page.url` | string | Canonical URL (e.g., `/projects/cliente-a/projeto-1`) |
94
- | `page.hubBase` | string | Hub base slug |
95
- | `page.itemPath` | string | Path relative to hub |
96
- | `page.canonicalPath` | string | Same as `page.url` |
97
- | `page.isPageForPosts` | boolean | Is posts listing |
98
- | `page.isFrontPage` | boolean | Is static front page |
99
- | `items[].url` | string | Canonical URL for each listing item |
100
- | `jsonLd` | string | Pre-rendered JSON-LD script tag (single pages only) |
101
- | `pagination` | object | `{ page, perPage, total, pages, hasPrevious, hasNext }` |
102
-
103
- ## SEO Integration (Phase 2)
104
-
105
- - `<link rel="canonical" href="...">` — from `resolution.canonicalPath`
106
- - `<meta property="og:url" content="...">` — same
107
- - `<meta name="description">` — `page.seo_description` → `page.excerpt` → `siteDescription`
108
-
109
- ## Phase Summary
17
+ Only React and Solid artifacts with `render.apiVersion: 2` are accepted. An
18
+ invalid or missing artifact is a deterministic runtime error; the host does not
19
+ fall back to a string renderer or synthesize an HTML page.
110
20
 
111
- | Phase | Feature | Files |
112
- |-------|---------|-------|
113
- | 1 | Dynamic hierarchy (hub pages, parent_id, redirects) | `rendering.ts`, `index.ts`, `url-helpers.ts` |
114
- | 2 | Head SEO (canonical, og:url, meta description fix) | `rendering.ts` (`wrapDocument`) |
115
- | 3 | Sitemap | `index.ts` (`GET /sitemap.xml`) |
116
- | 4 | JSON-LD + Breadcrumbs | `jsonld.ts`, `index.ts`, templates |
117
- | 5 | RSS/Atom feeds | `rss.ts`, `index.ts` (`GET /{base}/feed`) |
21
+ ## Routes
118
22
 
119
- ## Multi-tenant
23
+ | Route | Responsibility |
24
+ | --- | --- |
25
+ | `GET /themes/*` | validated theme assets from the active tenant theme |
26
+ | `GET /feed.xml`, `GET /atom.xml` | public content feeds without CMS generator markers |
27
+ | `GET *` | logical-key routing and compiled theme SSR |
120
28
 
121
- All queries scoped to `current_setting('app.current_tenant_id')` via RLS.
122
- Theme activation stored in DB (status='ACTIVE'), read per-request — no restart needed.
29
+ Theme framework dependencies remain inside the theme build. The host runtime
30
+ does not require React or Solid packages to render a request.
package/dist/index.js CHANGED
@@ -5,24 +5,32 @@ import { Hono } from 'hono';
5
5
  import { existsSync, readFileSync, statSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { serve } from '@hono/node-server';
8
- import { bootstrap, ensureTenantPluginsLoaded, getPluginBlocks, getPluginPatterns } from '@oktis-works/core';
8
+ import { bootstrap, ensureTenantPluginsLoaded, getPluginBlocks, getPluginPatterns, verifyThemePreviewToken } from '@oktis-works/core';
9
9
  import { resolveExtensionDirectory } from '@oktis-works/core';
10
10
  import { runWithTenantContext } from '@oktis-works/core';
11
11
  import { getPluginAssets } from '@oktis-works/core';
12
12
  import { webAuthMiddleware } from '@oktis-works/core';
13
- import { CMS_VERSION, normalizeLogicalValues } from '@oktis-works/validation';
13
+ import { CMS_VERSION, checkExtensionCompatibility, normalizeLogicalValues, validateThemeManifestRender } from '@oktis-works/validation';
14
14
  import { getConnection, createConnection, runWithTenantTransaction } from '@oktis-works/database';
15
15
  import { loadConfig } from '@oktis-works/config';
16
16
  import { getHookRegistry } from '@oktis-works/plugin-runtime';
17
- import { createRouter, wireThemeHooks, renderContentPageAsync, toSiteSettings, resolveThemeAssetPath, contentTypeForAsset, enrichItemsMedia, buildThemeSettings, mergePreviewSettings, renderAssetTags, renderPluginBlocks, } from './rendering.js';
17
+ import { createRouter, renderContentPageAsync, toSiteSettings, resolveThemeAssetPath, contentTypeForAsset, enrichItemsMedia, buildThemeSettings, mergePreviewSettings, renderAssetTags, renderPluginBlocks, } from './rendering.js';
18
18
  import { buildItemUrl } from './url-helpers.js';
19
19
  import { buildJsonLd } from './jsonld.js';
20
20
  import { generateFeeds } from './rss.js';
21
21
  import { createDatabaseThemeDataProvider, loadThemeRenderData } from './theme-data.js';
22
+ import { createThemeSdkBridge } from './theme-bridge.js';
22
23
  import { resolveTenantFromHost } from './tenant-resolver.js';
23
- import { runWithThemeDataProvider } from '@oktis-works/theme-sdk';
24
- import { validateManifestV2 } from '@oktis-works/plugin-runtime';
24
+ import { readThemeBuild, validateStyleManifest } from '@oktis-works/theme-runtime';
25
25
  const SAFE_THEME_NAME_RE = /^[A-Za-z0-9_-]+$/;
26
+ function stableJson(value) {
27
+ if (Array.isArray(value))
28
+ return `[${value.map(stableJson).join(',')}]`;
29
+ if (value && typeof value === 'object') {
30
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`).join(',')}}`;
31
+ }
32
+ return JSON.stringify(value) ?? 'null';
33
+ }
26
34
  function bodyOf(row) {
27
35
  return normalizeLogicalValues({ body: row['body'], data: row['data'], native: row });
28
36
  }
@@ -55,74 +63,91 @@ async function buildParentChain(sql, tenantId, parentId) {
55
63
  }
56
64
  /**
57
65
  * Tema ativo efetivo: a fonte única é o banco (status ACTIVE, gravado pelo
58
- * admin ou pela CLI). Sem linha ativa — ou com o tema sem arquivos no disco —
59
- * cai no ACTIVE_THEME do ambiente. Lido por request: ativação no admin não
60
- * exige restart do web. A row completa volta junto (manifest + config do
61
- * customizador) para expor `settings.theme` nos templates.
66
+ * admin ou pela CLI). Não existe fallback global ou por ambiente: uma falha
67
+ * de bootstrap/configuração deve ser explícita. Lido por request: ativação no
68
+ * admin não exige restart do web. A row completa volta junto (manifest +
69
+ * config do customizador) para expor `settings.theme` nos templates.
62
70
  */
63
- async function resolveActiveTheme(themesRoot, envFallback, previewTheme) {
71
+ async function resolveActiveTheme(themesRoot, tenantId, previewToken, currentUserId) {
72
+ const preview = previewToken ? verifyThemePreviewToken(previewToken) : null;
73
+ if (previewToken && !preview)
74
+ throw new Error('Invalid or expired theme preview token');
75
+ if (preview && preview.tenantId !== tenantId)
76
+ throw new Error('Theme preview token does not belong to the current tenant');
77
+ if (preview && (!currentUserId || preview.userId !== currentUserId)) {
78
+ throw new Error('Theme preview token does not belong to the current user');
79
+ }
80
+ const rows = preview
81
+ ? await getConnection().unsafe('SELECT * FROM themes WHERE id = $1 AND tenant_id = $2 LIMIT 1', [preview.themeId, tenantId])
82
+ : await getConnection().unsafe(`SELECT * FROM themes
83
+ WHERE status = 'ACTIVE' AND tenant_id = $1
84
+ ORDER BY activated_at DESC NULLS LAST, created_at DESC
85
+ LIMIT 1`, [tenantId]);
86
+ const row = rows[0];
87
+ if (!row)
88
+ throw new Error(`No valid active theme exists for tenant "${tenantId}"`);
89
+ const name = row['name'];
90
+ if (typeof name !== 'string' || !SAFE_THEME_NAME_RE.test(name) || !existsSync(join(themesRoot, name))) {
91
+ throw new Error(`Theme files are missing or unsafe for tenant "${tenantId}"`);
92
+ }
93
+ const manifest = row['manifest'];
94
+ let filesystemManifest;
64
95
  try {
65
- const rows = previewTheme && SAFE_THEME_NAME_RE.test(previewTheme)
66
- ? await getConnection().unsafe('SELECT * FROM themes WHERE name = $1 LIMIT 1', [previewTheme])
67
- : await getConnection().unsafe(`SELECT * FROM themes WHERE status = 'ACTIVE'
68
- ORDER BY (tenant_id IS NULL), activated_at DESC NULLS LAST, created_at DESC
69
- LIMIT 1`);
70
- const row = rows[0];
71
- const name = row?.['name'];
72
- if (typeof name === 'string' && SAFE_THEME_NAME_RE.test(name) && existsSync(join(themesRoot, name))) {
73
- const parentManifests = [];
74
- const manifest = row?.['manifest'];
75
- let parentName = manifest?.['parent'];
76
- const visited = new Set([name]);
77
- while (parentName && SAFE_THEME_NAME_RE.test(parentName) && !visited.has(parentName)) {
78
- visited.add(parentName);
79
- const parentRows = await getConnection().unsafe(`SELECT manifest FROM themes
80
- WHERE name = $1
81
- AND (tenant_id = current_setting('app.current_tenant_id', true)::uuid OR tenant_id IS NULL)
82
- ORDER BY tenant_id NULLS LAST
83
- LIMIT 1`, [parentName]);
84
- if (parentRows[0]) {
85
- const parentManifest = parentRows[0]['manifest'];
86
- if (parentManifest) {
87
- // Validate parent manifest structure
88
- const manifestIssues = validateManifestV2(parentManifest);
89
- if (manifestIssues.length > 0) {
90
- throw new Error(`Invalid parent theme manifest for "${parentName}": ${manifestIssues.join('; ')}`);
91
- }
92
- parentManifests.push(parentManifest);
93
- parentName = parentManifest['parent'];
94
- }
95
- else {
96
- parentName = undefined;
97
- }
98
- }
99
- else {
100
- throw new Error(`Missing parent theme "${parentName}"`);
101
- }
102
- }
103
- if (parentName && !SAFE_THEME_NAME_RE.test(parentName))
104
- throw new Error(`Unsafe parent theme name "${parentName}"`);
105
- if (parentName && visited.has(parentName))
106
- throw new Error(`Theme inheritance cycle detected at "${parentName}"`);
107
- return { name, row: row ?? null, parentManifests };
108
- }
96
+ filesystemManifest = JSON.parse(readFileSync(join(themesRoot, name, 'theme.json'), 'utf8'));
97
+ }
98
+ catch {
99
+ throw new Error(`Theme manifest is missing or invalid on disk for "${name}"`);
100
+ }
101
+ if (stableJson(manifest) !== stableJson(filesystemManifest)) {
102
+ throw new Error(`Theme manifest drift detected for "${name}"; synchronize the database with the filesystem`);
109
103
  }
110
- catch (error) {
111
- if (error instanceof Error && /theme|parent/i.test(error.message))
112
- throw error;
113
- // Log the error for debugging
114
- console.error('[web] Failed to resolve active theme:', error);
115
- // If previewTheme was explicitly requested, return 500 instead of silently falling back
116
- if (previewTheme) {
117
- throw new Error(`Failed to resolve preview theme "${previewTheme}": ${error instanceof Error ? error.message : String(error)}`);
104
+ const manifestIssues = [
105
+ ...checkExtensionCompatibility('theme', manifest ?? {}, CMS_VERSION).map((issue) => issue.message),
106
+ ...validateThemeManifestRender(manifest ?? {}),
107
+ ...validateStyleManifest(filesystemManifest, join(themesRoot, name)),
108
+ ];
109
+ if (manifestIssues.length > 0)
110
+ throw new Error(`Invalid theme manifest for "${name}": ${manifestIssues.join('; ')}`);
111
+ const parentManifests = [];
112
+ const parentConfigs = [];
113
+ let parentName = manifest?.['parent'];
114
+ const visited = new Set([name]);
115
+ while (parentName) {
116
+ if (!SAFE_THEME_NAME_RE.test(parentName))
117
+ throw new Error(`Unsafe parent theme name "${parentName}"`);
118
+ if (visited.has(parentName))
119
+ throw new Error(`Theme inheritance cycle detected at "${parentName}"`);
120
+ visited.add(parentName);
121
+ const parentRows = await getConnection().unsafe(`SELECT manifest, config FROM themes WHERE name = $1 AND tenant_id = $2 LIMIT 1`, [parentName, tenantId]);
122
+ const parentManifest = parentRows[0]?.['manifest'];
123
+ if (!parentManifest)
124
+ throw new Error(`Missing parent theme "${parentName}" for tenant "${tenantId}"`);
125
+ const parentDir = join(themesRoot, parentName);
126
+ let parentFilesystemManifest;
127
+ try {
128
+ parentFilesystemManifest = JSON.parse(readFileSync(join(parentDir, 'theme.json'), 'utf8'));
118
129
  }
119
- // tabela ausente/falha de leitura nunca derruba o render — usa o env
130
+ catch {
131
+ throw new Error(`Parent theme files are missing or invalid for "${parentName}"`);
132
+ }
133
+ if (stableJson(parentManifest) !== stableJson(parentFilesystemManifest)) {
134
+ throw new Error(`Theme manifest drift detected for parent "${parentName}"; synchronize the database with the filesystem`);
135
+ }
136
+ const parentIssues = [
137
+ ...checkExtensionCompatibility('theme', parentManifest, CMS_VERSION).map((issue) => issue.message),
138
+ ...validateThemeManifestRender(parentManifest),
139
+ ...validateStyleManifest(parentFilesystemManifest, parentDir),
140
+ ];
141
+ if (parentIssues.length > 0)
142
+ throw new Error(`Invalid parent theme manifest for "${parentName}": ${parentIssues.join('; ')}`);
143
+ parentManifests.push(parentManifest);
144
+ parentConfigs.push(parentRows[0]?.['config'] ?? null);
145
+ parentName = parentManifest['parent'];
120
146
  }
121
- return { name: envFallback, row: null, parentManifests: [] };
147
+ return { name, row, parentManifests, parentConfigs };
122
148
  }
123
149
  async function main() {
124
150
  const lifecycle = await bootstrap();
125
- await wireThemeHooks();
126
151
  // Garante que a conexão com o banco esteja inicializada neste processo.
127
152
  // Quando o web é instalado via npm/bunx (não workspace), pode haver uma
128
153
  // cópia aninhada de @oktis-works/database diferente da que o core usou
@@ -139,7 +164,6 @@ async function main() {
139
164
  // API/CLI (env → okcms.config.json → ./themes). Antes o web lia só
140
165
  // THEMES_DIR com outro fallback — apps com cwd diferente divergiam.
141
166
  const themesRoot = resolveExtensionDirectory('theme');
142
- const envActiveTheme = process.env['ACTIVE_THEME']?.trim() || 'default';
143
167
  const app = new Hono();
144
168
  // Content Security Policy
145
169
  const WEB_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'";
@@ -147,18 +171,6 @@ async function main() {
147
171
  c.header('Content-Security-Policy', WEB_CSP);
148
172
  await next();
149
173
  });
150
- // Assinatura do produto para detectores (Wappalyzer etc.): X-Powered-By em
151
- // TODA resposta do site público. Vale inclusive para temas full-control,
152
- // que são donos do próprio <head> e por isso não recebem o
153
- // <meta name="generator"> aplicado pelo wrapDocument.
154
- // Controlled by EXPOSE_POWERED_BY env (default: false)
155
- const config = loadConfig();
156
- if (config.app.exposePoweredBy) {
157
- app.use('*', async (c, next) => {
158
- c.header('X-Powered-By', `OkCMS/${CMS_VERSION}`);
159
- await next();
160
- });
161
- }
162
174
  // Tenant resolution middleware (loopback → default; senão subdomain/domain)
163
175
  app.use('*', async (c, next) => {
164
176
  const tenant = await resolveTenantFromHost(c.req.header('host') ?? '');
@@ -178,12 +190,25 @@ async function main() {
178
190
  try {
179
191
  const sql = getConnection();
180
192
  await sql `SELECT 1`;
193
+ const tenant = c.get('tenant');
194
+ let theme = { status: 'ok' };
195
+ if (tenant?.id) {
196
+ try {
197
+ const active = await resolveActiveTheme(themesRoot, String(tenant.id));
198
+ theme = { status: 'ok', activeTheme: active.name };
199
+ }
200
+ catch (error) {
201
+ theme = { status: 'error', error: error instanceof Error ? error.message : String(error) };
202
+ }
203
+ }
204
+ const healthy = theme.status === 'ok';
181
205
  return c.json({
182
- status: 'healthy',
206
+ status: healthy ? 'healthy' : 'degraded',
183
207
  service: 'web',
184
208
  timestamp: new Date().toISOString(),
185
209
  database: 'connected',
186
- });
210
+ theme,
211
+ }, healthy ? 200 : 503);
187
212
  }
188
213
  catch {
189
214
  return c.json({
@@ -191,6 +216,7 @@ async function main() {
191
216
  service: 'web',
192
217
  timestamp: new Date().toISOString(),
193
218
  database: 'disconnected',
219
+ theme: { status: 'unknown' },
194
220
  }, 503);
195
221
  }
196
222
  });
@@ -455,23 +481,43 @@ async function main() {
455
481
  const wildcard = c.req.path.replace(/^\/themes\//, '');
456
482
  const [themeName, ...rest] = wildcard.split('/');
457
483
  const assetPath = rest.join('/');
484
+ // Server bundles and build metadata are never public assets. Client
485
+ // bundles and styles are served only when their path is explicitly
486
+ // referenced by a validated build manifest.
487
+ if (assetPath === 'dist/theme-build.json' ||
488
+ /^dist\/(?:server|\.versions\/[^/]+\/server)(?:\/|$)/.test(assetPath)) {
489
+ return c.notFound();
490
+ }
458
491
  const target = resolveThemeAssetPath(themesRoot, themeName ?? '', assetPath);
459
492
  if (!target || !existsSync(target) || !statSync(target).isFile()) {
460
493
  return c.notFound();
461
494
  }
495
+ const requestedVersion = c.req.query('v');
496
+ const build = readThemeBuild(join(themesRoot, themeName ?? ''));
497
+ const declaredBuildAsset = Boolean(build &&
498
+ [build.entry, ...build.styles, ...Object.values(build.client)].includes(`dist/${assetPath}`));
499
+ if (assetPath.startsWith('dist/.versions/') && !declaredBuildAsset) {
500
+ return c.notFound();
501
+ }
502
+ const versionedAsset = Boolean(requestedVersion &&
503
+ build?.buildId === requestedVersion &&
504
+ declaredBuildAsset);
462
505
  return c.body(new Uint8Array(readFileSync(target)), 200, {
463
506
  'Content-Type': contentTypeForAsset(target),
464
- 'Cache-Control': 'public, max-age=3600',
507
+ 'Cache-Control': versionedAsset
508
+ ? 'public, max-age=31536000, immutable'
509
+ : 'no-cache',
465
510
  });
466
511
  });
467
512
  // Content rendering routes (FEAT-095: runtime routing catch-all) — render REAL
468
513
  app.get('*', async (c) => {
469
514
  const path = c.req.path;
470
515
  try {
471
- // Tema ativo por request (banco → env): ativação reflete sem restart.
472
- const active = await resolveActiveTheme(themesRoot, envActiveTheme, c.req.query('preview_theme'));
516
+ // Theme active per request from the tenant-scoped database registry.
517
+ const active = await resolveActiveTheme(themesRoot, String(c.get('tenant')['id']), c.req.query('preview_token'), c.get('userId'));
473
518
  const activeTheme = active.name;
474
519
  const parentManifests = active.parentManifests;
520
+ const parentConfigs = active.parentConfigs;
475
521
  const router = createRouter(themesRoot, activeTheme);
476
522
  const resolution = await router.resolve(path);
477
523
  if (!resolution.matched) {
@@ -545,7 +591,7 @@ async function main() {
545
591
  }
546
592
  }
547
593
  const provider = createDatabaseThemeDataProvider(getConnection(), String(c.get('tenant')['id']));
548
- const html = await runWithThemeDataProvider(provider, async () => {
594
+ const html = await (async () => {
549
595
  const themeData = await loadThemeRenderData(provider);
550
596
  // Item 8: assets enfileirados por plugins (api.assets) — escopo
551
597
  // platform + tenant, dedupe por URL na renderização. Falha nunca
@@ -570,12 +616,14 @@ async function main() {
570
616
  const renderedBlocks = await renderPluginBlocks(data['_blocks'] ?? data['blocks'], blockCatalog, resolveExtensionDirectory('plugin'), themeDataWithPlugins.pluginPatterns);
571
617
  const renderData = renderedBlocks === null ? data : { ...data, html: renderedBlocks };
572
618
  let pluginAssetTags;
619
+ let themePluginAssets = [];
573
620
  try {
574
621
  const [platformAssets, tenantAssets] = await Promise.all([
575
622
  getPluginAssets(null),
576
623
  getPluginAssets(tenantId),
577
624
  ]);
578
- pluginAssetTags = renderAssetTags([...platformAssets, ...tenantAssets].flatMap((entry) => entry.assets));
625
+ themePluginAssets = [...platformAssets, ...tenantAssets].flatMap((entry) => entry.assets);
626
+ pluginAssetTags = renderAssetTags(themePluginAssets);
579
627
  }
580
628
  catch {
581
629
  pluginAssetTags = undefined;
@@ -594,7 +642,7 @@ async function main() {
594
642
  : [];
595
643
  const settings = {
596
644
  ...toSiteSettings(rawSettings),
597
- theme: buildThemeSettings(manifest, mergePreviewSettings(active.row?.['config'], c.req.query('preview_settings'), allowedKeys), parentManifests),
645
+ theme: buildThemeSettings(manifest, mergePreviewSettings(active.row?.['config'], c.req.query('preview_settings'), allowedKeys), parentManifests, parentConfigs),
598
646
  };
599
647
  // Build JSON-LD for single content pages (not listings)
600
648
  let jsonLd;
@@ -624,6 +672,26 @@ async function main() {
624
672
  });
625
673
  }
626
674
  }
675
+ const themeSdk = createThemeSdkBridge({
676
+ provider,
677
+ context: {
678
+ cmsVersion: CMS_VERSION,
679
+ tenantId,
680
+ locale: String(settings.language ?? 'en'),
681
+ url: c.req.url,
682
+ authenticated: Boolean(c.get('userId')),
683
+ roles: c.get('userRoles') ?? [],
684
+ route: {
685
+ templateKey: resolution.template ?? 'index',
686
+ contentType: resolution.contentType ?? undefined,
687
+ slug: resolution.slug ?? undefined,
688
+ canonicalPath: resolution.canonicalPath ?? undefined,
689
+ },
690
+ },
691
+ blocks: themeDataWithPlugins.pluginBlocks,
692
+ patterns: themeDataWithPlugins.pluginPatterns,
693
+ assets: themePluginAssets,
694
+ });
627
695
  return await renderContentPageAsync({
628
696
  resolution,
629
697
  contentRow,
@@ -636,12 +704,22 @@ async function main() {
636
704
  themesRoot,
637
705
  tenantId,
638
706
  pluginAssets: pluginAssetTags,
707
+ themeSdk,
639
708
  });
640
- });
709
+ })();
641
710
  return c.html(html);
642
711
  }
643
712
  catch (error) {
644
- console.error('[web] Falha ao resolver rota:', error);
713
+ const message = error instanceof Error ? error.message : String(error);
714
+ console.error('[web] Theme request failed:', message);
715
+ const themeFailure = /theme|artifact|manifest|build|preview token|active theme/i.test(message);
716
+ if (themeFailure) {
717
+ return c.json({
718
+ error: 'Theme runtime unavailable',
719
+ code: 'THEME_RUNTIME_INVALID',
720
+ ...(process.env['NODE_ENV'] !== 'production' ? { detail: message } : {}),
721
+ }, 503);
722
+ }
645
723
  return c.json({ error: 'Internal server error' }, 500);
646
724
  }
647
725
  });