@oktis-works/web 0.15.0 → 0.17.2

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/dist/rendering.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @oktis-works/web - Runtime Rendering (catch-all SSR com hierarquia de templates)
2
- import { existsSync, realpathSync } from 'node:fs';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { join, relative, resolve, sep } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
@@ -8,7 +8,7 @@ import { getConnection } from '@oktis-works/database';
8
8
  import { normalizeLogicalValues } from '@oktis-works/validation';
9
9
  import { getHookRegistry } from '@oktis-works/plugin-runtime';
10
10
  import { postTypeRegistry, HOOK_POINTS } from '@oktis-works/core';
11
- import { TemplateHierarchyResolver, RuntimeRouter, ThemeRenderer, createProjectTemplateResolver, resolveProjectThemeChain, } from '@oktis-works/theme-runtime';
11
+ import { TemplateHierarchyResolver, RuntimeRouter, ThemeRenderer, createProjectTemplateResolver, resolveProjectThemeChain, loadThemeCatalog, findTemplateProvider, templateKeyFromFile, renderCompiledTheme, } from '@oktis-works/theme-runtime';
12
12
  import { CMS_VERSION } from '@oktis-works/validation';
13
13
  /**
14
14
  * B1/Unificação (FEAT-095): a cadeia de templates do projeto
@@ -35,6 +35,52 @@ export function createTemplateChecker(themesRoot, activeTheme) {
35
35
  export function loadTemplateSource(themesRoot, activeTheme, file) {
36
36
  return projectTemplates(themesRoot, activeTheme).read(file);
37
37
  }
38
+ /** Registers manifest-declared legacy components from parent to child. */
39
+ function registerThemeComponents(themesRoot, activeTheme) {
40
+ const chain = resolveProjectThemeChain(themesRoot, activeTheme);
41
+ themeRenderer.clearComponents();
42
+ for (const themeName of [...chain].reverse()) {
43
+ const themeDir = resolve(themesRoot, themeName);
44
+ const manifestPath = join(themeDir, 'theme.json');
45
+ if (!existsSync(manifestPath))
46
+ continue;
47
+ let manifest;
48
+ try {
49
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ const components = Array.isArray(manifest['components']) ? manifest['components'] : [];
55
+ for (const value of components) {
56
+ if (!value || typeof value !== 'object' || Array.isArray(value))
57
+ continue;
58
+ const component = value;
59
+ const name = typeof component['name'] === 'string' ? component['name'] : '';
60
+ const file = typeof component['file'] === 'string' ? component['file'] : '';
61
+ if (!name || !file || file.includes('..') || file.includes('\\') || file.startsWith('/'))
62
+ continue;
63
+ const target = resolve(themeDir, file);
64
+ if (!target.startsWith(themeDir + sep) || !existsSync(target))
65
+ continue;
66
+ try {
67
+ const realThemeDir = realpathSync(themeDir);
68
+ const realTarget = realpathSync(target);
69
+ if (realTarget !== realThemeDir && !realTarget.startsWith(realThemeDir + sep))
70
+ continue;
71
+ themeRenderer.registerComponent({
72
+ name,
73
+ type: component['type'],
74
+ file: realTarget,
75
+ props: component['props'],
76
+ });
77
+ }
78
+ catch {
79
+ continue;
80
+ }
81
+ }
82
+ }
83
+ }
38
84
  export function toSiteSettings(raw) {
39
85
  return {
40
86
  siteTitle: toText(raw['siteTitle']) || 'OkCMS',
@@ -141,13 +187,18 @@ function extractDefaults(settings) {
141
187
  * admin (exposto como `settings.theme` no contexto do template).
142
188
  * Suporta herança parent/child: parent defaults → child defaults → child config
143
189
  */
144
- export function buildThemeSettings(manifest, config, parentManifest) {
190
+ export function buildThemeSettings(manifest, config, parentManifest, parentConfigs) {
145
191
  let settings = {};
146
192
  // 1. Parent defaults (if parent theme exists)
147
193
  if (parentManifest) {
148
194
  const parents = Array.isArray(parentManifest) ? [...parentManifest].reverse() : [parentManifest];
149
- for (const parent of parents) {
195
+ for (let index = 0; index < parents.length; index += 1) {
196
+ const parent = parents[index];
150
197
  settings = deepMerge(settings, extractDefaults(parent['settings']));
198
+ const configForParent = parentConfigs?.[parents.length - 1 - index];
199
+ if (configForParent && typeof configForParent === 'object' && !Array.isArray(configForParent)) {
200
+ settings = deepMerge(settings, configForParent);
201
+ }
151
202
  }
152
203
  }
153
204
  // 2. Child theme defaults
@@ -160,21 +211,13 @@ export function buildThemeSettings(manifest, config, parentManifest) {
160
211
  return settings;
161
212
  }
162
213
  /**
163
- * B1 — render real: injeta `content.body`/campos no template do tema.
164
- * Contexto exposto ao template:
165
- * site.title / site.description — settings (siteTitle/siteDescription)
166
- * content.* — colunas da row + campos do body
167
- * page.title / page.description — título da página (SEO) e meta description
168
- * settings — settings cruas (avançado)
214
+ * Builds the engine-agnostic render data once, so template and compiled
215
+ * themes receive exactly the same contract and hooks.
169
216
  */
170
- export function renderContentPage(input) {
171
- const file = input.resolution.template ?? 'index.astro';
172
- const template = loadTemplateSource(input.themesRoot, input.activeTheme, file);
173
- if (!template) {
174
- return renderFallbackPage(input, input.pluginAssets);
175
- }
217
+ function prepareContentPage(input, file) {
176
218
  const row = input.contentRow ?? {};
177
- const logicalRecord = normalizeLogicalValues({ body: row['body'], data: row['data'], native: row });
219
+ const publicRow = publicContentRecord(row);
220
+ const logicalRecord = normalizeLogicalValues({ body: publicRow['body'], data: publicRow['data'], native: publicRow });
178
221
  const title = toText(row['title']) || input.settings.siteTitle;
179
222
  // E5 (FEAT-100): render/save hook surface for plugin-built editors.
180
223
  // `theme:before:render` filters the render data right before templating —
@@ -190,19 +233,22 @@ export function renderContentPage(input) {
190
233
  slug: input.resolution.slug ?? '',
191
234
  activeTheme: input.activeTheme,
192
235
  settings: input.settings,
193
- contentRow: { ...row, ...logicalRecord },
236
+ contentRow: { ...publicRow, ...logicalRecord },
194
237
  };
195
- const renderData = registry.applyFilters(HOOK_POINTS.THEME_BEFORE_RENDER, { ...input.data }, hookContext) ?? input.data;
238
+ const renderData = registry.applyFilters(HOOK_POINTS.THEME_BEFORE_RENDER, { ...logicalRecord, ...input.data }, hookContext) ?? input.data;
239
+ const publicRenderData = sanitizePublicValue(renderData);
196
240
  const themeRecord = normalizeLogicalValues({
197
- body: renderData,
198
- data: row['data'],
199
- native: row,
241
+ body: publicRenderData,
242
+ data: publicRow['data'],
243
+ native: publicRow,
200
244
  });
201
245
  const context = {
202
246
  site: {
203
247
  title: input.settings.siteTitle,
204
248
  description: input.settings.siteDescription,
205
249
  theme: input.activeTheme,
250
+ url: input.settings.siteUrl,
251
+ language: input.settings.language,
206
252
  },
207
253
  page: {
208
254
  title,
@@ -217,8 +263,8 @@ export function renderContentPage(input) {
217
263
  isPageForPosts: input.resolution.isPageForPosts ?? false,
218
264
  isFrontPage: input.resolution.isFrontPage ?? false,
219
265
  },
220
- content: { ...plainColumns(row), ...renderData },
221
- fields: renderData,
266
+ content: { ...plainColumns(publicRow), ...publicRenderData },
267
+ fields: publicRenderData,
222
268
  record: themeRecord,
223
269
  items: input.items ?? [],
224
270
  pagination: input.pagination ?? { page: 1, perPage: 0, total: 0, pages: 0, hasPrevious: false, hasNext: false },
@@ -229,8 +275,14 @@ export function renderContentPage(input) {
229
275
  settings: { ...(input.themeData?.settings ?? {}), ...input.settings },
230
276
  themeData: input.themeData ?? { menus: { all: [], bySlug: {} }, contentTypes: [], taxonomies: [], terms: {}, settings: input.settings },
231
277
  };
232
- const body = themeRenderer.wrapWithThemeScope(themeRenderer.renderString(template, context, { ...row, ...themeRecord }), input.activeTheme);
233
- const stylesheet = resolveThemeStylesheet(input.themesRoot, input.activeTheme);
278
+ return { file, row: publicRow, logicalRecord, title, registry, hookContext, renderData: publicRenderData, themeRecord, context };
279
+ }
280
+ /** Wraps a rendered body in the document and runs the post-render hook. */
281
+ function finalizeContentPage(input, prepared, body, themeAssets) {
282
+ // Compiled artifacts carry their own versioned stylesheet list. Linking the
283
+ // legacy stable path as well would defeat cache versioning and may load a
284
+ // stale CSS generation.
285
+ const stylesheet = themeAssets ? null : resolveThemeStylesheets(input.themesRoot, input.activeTheme);
234
286
  // Build canonical URL for SEO
235
287
  const canonicalPath = input.resolution.canonicalPath ?? '';
236
288
  const siteUrl = input.settings['siteUrl'] || '';
@@ -239,11 +291,125 @@ export function renderContentPage(input) {
239
291
  const pageDescription = (input.contentRow
240
292
  ? input.contentRow['seo_description'] ?? input.contentRow['excerpt']
241
293
  : undefined) ?? input.settings.siteDescription;
242
- const html = wrapDocument(body, title, input.settings, input.activeTheme, stylesheet, input.pluginAssets, {
243
- canonicalUrl,
294
+ // Per-page SEO overrides from content row
295
+ const pageRobots = input.contentRow?.['seo_robots'] ?? undefined;
296
+ const pageCanonical = input.contentRow?.['seo_canonical_url'] ?? undefined;
297
+ const pageOgImage = input.contentRow?.['seo_og_image'] ?? undefined;
298
+ const configuredOgImage = toText(input.settings['ogImage']) || undefined;
299
+ const html = wrapDocument(body, prepared.title, input.settings, input.activeTheme, stylesheet, input.pluginAssets, {
300
+ canonicalUrl: pageCanonical ?? canonicalUrl,
244
301
  pageDescription,
302
+ ogTitle: prepared.title,
303
+ ogDescription: pageDescription,
304
+ ogImage: pageOgImage ?? configuredOgImage,
305
+ ogType: input.settings['ogType'] ?? 'website',
306
+ ogSiteName: input.settings.siteTitle,
307
+ ogLocale: input.settings.language ?? 'pt-BR',
308
+ twitterCard: input.settings['twitterCard'] ?? 'summary_large_image',
309
+ twitterTitle: prepared.title,
310
+ twitterDescription: pageDescription,
311
+ twitterImage: pageOgImage ?? configuredOgImage,
312
+ robots: pageRobots ?? input.settings['defaultRobots'] ?? 'index,follow',
313
+ }, themeAssets);
314
+ return prepared.registry.applyFilters(HOOK_POINTS.THEME_AFTER_RENDER, html, prepared.hookContext);
315
+ }
316
+ export function renderContentPage(input) {
317
+ const file = input.resolution.template ?? 'index.astro';
318
+ const template = loadTemplateSource(input.themesRoot, input.activeTheme, file);
319
+ if (!template) {
320
+ return renderFallbackPage(input, input.pluginAssets);
321
+ }
322
+ const prepared = prepareContentPage(input, file);
323
+ registerThemeComponents(input.themesRoot, input.activeTheme);
324
+ const body = themeRenderer.wrapWithThemeScope(themeRenderer.renderString(template, prepared.context, { ...prepared.themeRecord }), input.activeTheme);
325
+ return finalizeContentPage(input, prepared, body);
326
+ }
327
+ /**
328
+ * Engine-aware render entry point. Template themes keep the synchronous
329
+ * implementation above; React/Solid themes are imported from their build
330
+ * artifact and rendered through the compiled adapter.
331
+ */
332
+ export async function renderContentPageAsync(input) {
333
+ const catalog = loadThemeCatalog(input.themesRoot, input.activeTheme);
334
+ const active = catalog.entries[0] ?? null;
335
+ // No manifest or legacy template theme: preserve the existing path exactly.
336
+ if (!active || active.engine === 'template') {
337
+ return renderContentPage(input);
338
+ }
339
+ if (active.problems.length > 0) {
340
+ throw new Error(`Theme "${active.name}" cannot render: ${active.problems.join('; ')}`);
341
+ }
342
+ const file = input.resolution.template ?? 'index.astro';
343
+ const requestedKey = templateKeyFromFile(file);
344
+ const provider = findTemplateProvider(catalog, requestedKey, active.engine) ??
345
+ findTemplateProvider(catalog, '404', active.engine);
346
+ if (!provider?.build) {
347
+ return renderFallbackPage(input, input.pluginAssets);
348
+ }
349
+ if (provider.build.engine !== active.engine) {
350
+ throw new Error(`Theme "${provider.name}" engine mismatch: theme.json says ${active.engine}, artifact says ${provider.build.engine}.`);
351
+ }
352
+ const templateKey = provider.build.templates.includes(requestedKey) ? requestedKey : '404';
353
+ const prepared = prepareContentPage(input, file);
354
+ const styleAssets = catalog.entries
355
+ .filter((entry) => entry.problems.length === 0)
356
+ .flatMap((entry) => {
357
+ if (entry.build) {
358
+ return [{ themeName: entry.name, styles: entry.build.styles, buildId: entry.build.buildId }];
359
+ }
360
+ return existsSync(join(entry.dir, 'dist', 'theme.css'))
361
+ ? [{ themeName: entry.name, styles: ['dist/theme.css'] }]
362
+ : [];
363
+ });
364
+ const output = await renderCompiledTheme({
365
+ themeDir: provider.dir,
366
+ build: provider.build,
367
+ templateKey,
368
+ data: prepared.context,
369
+ // `getField()` (ALS) must see the same `theme:before:render` output as
370
+ // the component props, not the pre-hook row.
371
+ record: {
372
+ ...prepared.themeRecord,
373
+ body: {
374
+ ...(prepared.themeRecord['body'] ?? {}),
375
+ ...prepared.renderData,
376
+ },
377
+ data: {
378
+ ...(prepared.themeRecord['data'] ?? {}),
379
+ ...prepared.renderData,
380
+ },
381
+ },
382
+ context: {
383
+ url: input.resolution.canonicalPath ?? '',
384
+ params: {},
385
+ tenant: input.tenantId ?? '',
386
+ templateKey,
387
+ buildId: provider.build.buildId,
388
+ },
389
+ automaticAssets: provider.build.hydration === 'islands' || styleAssets.some((asset) => asset.styles.length > 0),
390
+ });
391
+ const body = themeRenderer.wrapWithThemeScope(output.html, provider.name);
392
+ const outputScripts = output.scripts ?? [];
393
+ const scripts = outputScripts.length > 0
394
+ ? outputScripts
395
+ : provider.build.hydration === 'islands'
396
+ ? Object.values(provider.build.client)
397
+ : [];
398
+ return finalizeContentPage(input, prepared, body, {
399
+ themeName: provider.name,
400
+ buildId: provider.build.buildId,
401
+ styles: output.styles,
402
+ styleAssets,
403
+ head: output.head,
404
+ scripts,
405
+ hydration: provider.build.hydration === 'islands'
406
+ ? {
407
+ buildId: provider.build.buildId,
408
+ templateKey,
409
+ data: prepared.context,
410
+ }
411
+ : undefined,
245
412
  });
246
- return registry.applyFilters(HOOK_POINTS.THEME_AFTER_RENDER, html, hookContext);
247
413
  }
248
414
  /**
249
415
  * Item 8 — renders plugin-enqueued assets as HTML tags with hash dedupe:
@@ -398,27 +564,62 @@ export async function renderPluginBlocks(blocks, catalog, pluginsRoot, patterns
398
564
  * sai sem <link> quebrado (nada de 404 silencioso no console).
399
565
  */
400
566
  export function resolveThemeStylesheet(themesRoot, activeTheme) {
401
- for (const theme of resolveProjectThemeChain(themesRoot, activeTheme)) {
402
- if (!theme)
403
- continue;
404
- if (existsSync(join(themesRoot, theme, 'dist', 'theme.css')))
405
- return theme;
406
- }
407
- return null;
567
+ return resolveThemeStylesheets(themesRoot, activeTheme)[0] ?? null;
408
568
  }
409
- /**
410
- * B1 — envolve o fragmento do template num documento completo com title/meta
411
- * das settings + CSS do tema + injeções de plugins via hook `theme:head`.
412
- * Template que já emite documento completo passa intocado (temas headless/full-control).
413
- */
414
- export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetTheme = null, pluginAssets, seo) {
569
+ /** Returns all inherited legacy styles in parent-to-child order. */
570
+ export function resolveThemeStylesheets(themesRoot, activeTheme) {
571
+ return [...resolveProjectThemeChain(themesRoot, activeTheme)]
572
+ .reverse()
573
+ .filter((theme) => existsSync(join(themesRoot, theme, 'dist', 'theme.css')));
574
+ }
575
+ /** Escapes JSON for an application/json script (never executable HTML). */
576
+ export function serializeThemeHydration(payload) {
577
+ return JSON.stringify(payload)
578
+ .replace(/</g, '\\u003c')
579
+ .replace(/>/g, '\\u003e')
580
+ .replace(/&/g, '\\u0026');
581
+ }
582
+ export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetTheme = null, pluginAssets, seo, themeAssets) {
415
583
  if (body.includes('<html') || body.includes('<!DOCTYPE')) {
416
584
  return body;
417
585
  }
418
586
  const title = pageTitle && pageTitle !== settings.siteTitle ? `${pageTitle} | ${settings.siteTitle}` : settings.siteTitle;
419
587
  const lang = escapeHtml(settings.language || 'pt-BR');
420
- const stylesheet = stylesheetTheme
421
- ? ` <link rel="stylesheet" href="/themes/${escapeHtml(stylesheetTheme)}/dist/theme.css" data-theme-style="${escapeHtml(stylesheetTheme)}" />\n`
588
+ const stylesheetNames = stylesheetTheme === null
589
+ ? []
590
+ : Array.isArray(stylesheetTheme)
591
+ ? stylesheetTheme
592
+ : [stylesheetTheme];
593
+ const stylesheet = stylesheetNames
594
+ .map((themeName) => ` <link rel="stylesheet" href="/themes/${escapeHtml(themeName)}/dist/theme.css" data-theme-style="${escapeHtml(themeName)}" />`)
595
+ .join('\n');
596
+ // Compiled themes may emit extra styles/scripts/head from their artifact.
597
+ const styleAssets = themeAssets
598
+ ? themeAssets.styleAssets ?? [{ themeName: themeAssets.themeName, styles: themeAssets.styles ?? [], buildId: themeAssets.buildId }]
599
+ : [];
600
+ const seenStyleAssets = new Set();
601
+ const extraStyles = styleAssets
602
+ .flatMap((asset) => asset.styles
603
+ .filter((style) => {
604
+ const key = `${asset.themeName}:${style}`;
605
+ if (seenStyleAssets.has(key))
606
+ return false;
607
+ seenStyleAssets.add(key);
608
+ return true;
609
+ })
610
+ .filter((style) => !(style === 'dist/theme.css' && asset.buildId))
611
+ .map((style) => ` <link rel="stylesheet" href="/themes/${escapeHtml(asset.themeName)}/${escapeHtml(style)}${asset.buildId ? `?v=${encodeURIComponent(asset.buildId)}` : ''}" data-theme-style="${escapeHtml(asset.themeName)}" />`))
612
+ .join('\n');
613
+ const legacyStyles = stylesheet ? `${stylesheet}\n` : '';
614
+ const compiledStyles = extraStyles ? `${extraStyles}\n` : '';
615
+ const themeHead = themeAssets?.head ? `${themeAssets.head}\n` : '';
616
+ const themeScripts = themeAssets
617
+ ? (themeAssets.scripts ?? [])
618
+ .map((script) => `<script type="module" src="/themes/${escapeHtml(themeAssets.themeName)}/${escapeHtml(script)}${themeAssets.buildId ? `?v=${encodeURIComponent(themeAssets.buildId)}` : ''}"></script>`)
619
+ .join('\n')
620
+ : '';
621
+ const hydrationScript = themeAssets?.hydration
622
+ ? `<script type="application/json" id="okcms-theme-hydration">${serializeThemeHydration(themeAssets.hydration)}</script>`
422
623
  : '';
423
624
  // WP6: ponto de extensão theme:head — plugins injetam tags no <head>
424
625
  const registry = getHookRegistry();
@@ -426,12 +627,52 @@ export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetT
426
627
  // Item 8: assets enfileirados via api.assets (styles + scripts de head)
427
628
  const assetHead = pluginAssets?.head ? `${pluginAssets.head}\n` : '';
428
629
  const assetFooter = pluginAssets?.footer ? `\n${pluginAssets.footer}` : '';
429
- // SEO: canonical URL + og:url
630
+ // SEO: canonical URL
430
631
  const canonicalUrl = seo?.canonicalUrl ?? '';
431
632
  const canonicalTag = canonicalUrl ? ` <link rel="canonical" href="${escapeHtml(canonicalUrl)}">\n` : '';
432
- const ogUrlTag = canonicalUrl ? ` <meta property="og:url" content="${escapeHtml(canonicalUrl)}">\n` : '';
633
+ // Open Graph defaults das settings
634
+ const ogTitle = seo?.ogTitle ?? pageTitle ?? settings.siteTitle;
635
+ const ogDescription = seo?.ogDescription ?? seo?.pageDescription ?? settings.siteDescription;
636
+ const ogImage = seo?.ogImage ?? (settings['siteUrl'] ? `${settings['siteUrl']}/logo.png` : '');
637
+ const ogType = seo?.ogType ?? 'website';
638
+ const ogSiteName = seo?.ogSiteName ?? settings.siteTitle;
639
+ const ogLocale = seo?.ogLocale ?? settings.language ?? 'pt-BR';
640
+ // Twitter defaults
641
+ const twitterCard = seo?.twitterCard ?? 'summary_large_image';
642
+ const twitterTitle = seo?.twitterTitle ?? ogTitle;
643
+ const twitterDescription = seo?.twitterDescription ?? ogDescription;
644
+ const twitterImage = seo?.twitterImage ?? ogImage;
645
+ // Robots meta: per-page override > settings default > index,follow
646
+ const robotsDirective = String(seo?.robots ?? settings['defaultRobots'] ?? 'index,follow');
433
647
  // Meta description: page-specific (seo_description/excerpt) > siteDescription
434
648
  const description = escapeHtml(seo?.pageDescription ?? settings.siteDescription);
649
+ // Tags Open Graph
650
+ const ogTags = [];
651
+ if (ogTitle)
652
+ ogTags.push(` <meta property="og:title" content="${escapeHtml(ogTitle)}">`);
653
+ if (ogDescription)
654
+ ogTags.push(` <meta property="og:description" content="${escapeHtml(ogDescription)}">`);
655
+ if (ogImage)
656
+ ogTags.push(` <meta property="og:image" content="${escapeHtml(ogImage)}">`);
657
+ ogTags.push(` <meta property="og:type" content="${escapeHtml(ogType)}">`);
658
+ if (ogSiteName)
659
+ ogTags.push(` <meta property="og:site_name" content="${escapeHtml(ogSiteName)}">`);
660
+ if (canonicalUrl)
661
+ ogTags.push(` <meta property="og:url" content="${escapeHtml(canonicalUrl)}">`);
662
+ ogTags.push(` <meta property="og:locale" content="${escapeHtml(ogLocale)}">`);
663
+ // Tags Twitter
664
+ const twitterTags = [];
665
+ twitterTags.push(` <meta name="twitter:card" content="${escapeHtml(twitterCard)}">`);
666
+ if (twitterTitle)
667
+ twitterTags.push(` <meta name="twitter:title" content="${escapeHtml(twitterTitle)}">`);
668
+ if (twitterDescription)
669
+ twitterTags.push(` <meta name="twitter:description" content="${escapeHtml(twitterDescription)}">`);
670
+ if (twitterImage)
671
+ twitterTags.push(` <meta name="twitter:image" content="${escapeHtml(twitterImage)}">`);
672
+ // Tag Robots
673
+ const robotsTag = ` <meta name="robots" content="${escapeHtml(robotsDirective)}">`;
674
+ // Filtro de plugin para injetar meta tags SEO adicionais
675
+ const seoMetaTags = String(registry.applyFilters('okcms.seo.meta.tags', '', { settings, activeTheme, seo }));
435
676
  return `<!DOCTYPE html>
436
677
  <html lang="${lang}" data-theme="${escapeHtml(activeTheme)}">
437
678
  <head>
@@ -440,9 +681,12 @@ export function wrapDocument(body, pageTitle, settings, activeTheme, stylesheetT
440
681
  <meta name="generator" content="OkCMS ${CMS_VERSION}">
441
682
  <title>${escapeHtml(title)}</title>
442
683
  <meta name="description" content="${description}">
443
- ${canonicalTag}${ogUrlTag} ${stylesheet}${headInjections}${assetHead}</head>
444
- <body>
445
- ${body}${assetFooter}
684
+ ${robotsTag}
685
+ ${canonicalTag}
686
+ ${ogTags.join('\n')}
687
+ ${twitterTags.join('\n')}
688
+ ${seoMetaTags}${legacyStyles}${compiledStyles}${themeHead}${headInjections}${assetHead}</head> <body>
689
+ ${body}${assetFooter}${hydrationScript ? `\n${hydrationScript}` : ''}${themeScripts ? `\n${themeScripts}` : ''}
446
690
  </body>
447
691
  </html>`;
448
692
  }
@@ -456,6 +700,31 @@ function plainColumns(row) {
456
700
  }
457
701
  return out;
458
702
  }
703
+ const PRIVATE_CONTENT_COLUMNS = new Set([
704
+ 'tenant_id',
705
+ 'password_hash',
706
+ 'password_reset_token',
707
+ 'reset_token',
708
+ 'reset_token_expires_at',
709
+ 'session_token',
710
+ 'api_key',
711
+ 'secret',
712
+ ]);
713
+ const PRIVATE_CONTENT_KEY_RE = /(?:password|token|secret|api[_-]?key|private[_-]?key|credential|authorization|cookie|hash)/i;
714
+ /** Recursively removes credential-like keys before data reaches a theme. */
715
+ function sanitizePublicValue(value) {
716
+ if (Array.isArray(value))
717
+ return value.map(sanitizePublicValue);
718
+ if (!value || typeof value !== 'object')
719
+ return value;
720
+ return Object.fromEntries(Object.entries(value)
721
+ .filter(([key]) => !PRIVATE_CONTENT_COLUMNS.has(key) && !PRIVATE_CONTENT_KEY_RE.test(key))
722
+ .map(([key, child]) => [key, sanitizePublicValue(child)]));
723
+ }
724
+ /** Removes storage-only and credential fields from the public theme contract. */
725
+ function publicContentRecord(row) {
726
+ return sanitizePublicValue(row);
727
+ }
459
728
  /** Tema sem template para a rota: HTML mínimo com os dados reais (nunca stub). */
460
729
  function renderFallbackPage(input, pluginAssets) {
461
730
  const title = toText((input.contentRow ?? {})['title']) || input.settings.siteTitle;
@@ -464,16 +733,49 @@ function renderFallbackPage(input, pluginAssets) {
464
733
  const canonicalPath = input.resolution.canonicalPath ?? '';
465
734
  const siteUrl = input.settings['siteUrl'] || '';
466
735
  const canonicalUrl = canonicalPath && siteUrl ? new URL(canonicalPath, siteUrl).toString() : '';
467
- const canonicalTag = canonicalUrl ? ` <link rel="canonical" href="${escapeHtml(canonicalUrl)}">\n` : '';
468
- const ogUrlTag = canonicalUrl ? ` <meta property="og:url" content="${escapeHtml(canonicalUrl)}">\n` : '';
469
736
  const pageDescription = (input.contentRow
470
737
  ? input.contentRow['seo_description'] ?? input.contentRow['excerpt']
471
738
  : undefined) ?? input.settings.siteDescription;
739
+ const ogTitle = title;
740
+ const ogDescription = pageDescription;
741
+ const ogImage = '';
742
+ const ogType = 'website';
743
+ const ogSiteName = input.settings.siteTitle;
744
+ const ogLocale = input.settings.language ?? 'pt-BR';
745
+ const twitterCard = 'summary_large_image';
746
+ const twitterTitle = ogTitle;
747
+ const twitterDescription = ogDescription;
748
+ const twitterImage = ogImage;
749
+ const robotsDirective = input.settings['defaultRobots'] ?? 'index,follow';
472
750
  // WP6: ponto de extensão theme:head — plugins injetam tags no <head>
473
751
  const registry = getHookRegistry();
474
752
  const headInjections = registry.applyFilters(HOOK_POINTS.THEME_HEAD, '', { settings: input.settings, activeTheme: input.activeTheme });
753
+ const seoMetaTags = String(registry.applyFilters('okcms.seo.meta.tags', '', { settings: input.settings, activeTheme: input.activeTheme, seo: undefined }));
475
754
  const assetHead = pluginAssets?.head ? `${pluginAssets.head}\n` : '';
476
755
  const assetFooter = pluginAssets?.footer ? `\n${pluginAssets.footer}` : '';
756
+ const canonicalTag = canonicalUrl ? ` <link rel="canonical" href="${escapeHtml(canonicalUrl)}">\n` : '';
757
+ const ogTags = [];
758
+ if (ogTitle)
759
+ ogTags.push(` <meta property="og:title" content="${escapeHtml(ogTitle)}">`);
760
+ if (ogDescription)
761
+ ogTags.push(` <meta property="og:description" content="${escapeHtml(ogDescription)}">`);
762
+ if (ogImage)
763
+ ogTags.push(` <meta property="og:image" content="${escapeHtml(ogImage)}">`);
764
+ ogTags.push(` <meta property="og:type" content="${escapeHtml(ogType)}">`);
765
+ if (ogSiteName)
766
+ ogTags.push(` <meta property="og:site_name" content="${escapeHtml(ogSiteName)}">`);
767
+ if (canonicalUrl)
768
+ ogTags.push(` <meta property="og:url" content="${escapeHtml(canonicalUrl)}">`);
769
+ ogTags.push(` <meta property="og:locale" content="${escapeHtml(ogLocale)}">`);
770
+ const twitterTags = [];
771
+ twitterTags.push(` <meta name="twitter:card" content="${escapeHtml(twitterCard)}">`);
772
+ if (twitterTitle)
773
+ twitterTags.push(` <meta name="twitter:title" content="${escapeHtml(twitterTitle)}">`);
774
+ if (twitterDescription)
775
+ twitterTags.push(` <meta name="twitter:description" content="${escapeHtml(twitterDescription)}">`);
776
+ if (twitterImage)
777
+ twitterTags.push(` <meta name="twitter:image" content="${escapeHtml(twitterImage)}">`);
778
+ const robotsTag = ` <meta name="robots" content="${escapeHtml(robotsDirective)}">`;
477
779
  return `<!DOCTYPE html>
478
780
  <html lang="${lang}">
479
781
  <head>
@@ -481,7 +783,11 @@ function renderFallbackPage(input, pluginAssets) {
481
783
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
482
784
  <title>${escapeHtml(title)} | ${escapeHtml(input.settings.siteTitle)}</title>
483
785
  <meta name="description" content="${escapeHtml(pageDescription)}">
484
- ${canonicalTag}${ogUrlTag} <style>
786
+ ${robotsTag}
787
+ ${canonicalTag}
788
+ ${ogTags.join('\n')}
789
+ ${twitterTags.join('\n')}
790
+ ${seoMetaTags}<style>
485
791
  body { font-family: system-ui, sans-serif; margin: 0; color: #111; }
486
792
  main { max-width: 46rem; margin: 0 auto; padding: 3rem 1.5rem; }
487
793
  .fallback__hint { color: #555; line-height: 1.5; }