@archangel70/cosmo 1.13.1 → 1.14.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/CHANGELOG.md +7 -0
- package/README.md +7 -3
- package/docs/BROWSER-QA.md +15 -0
- package/docs/ENTITY-MAP.md +29 -1
- package/package.json +1 -1
- package/packages/cli/bin/cosmo.mjs +21 -9
- package/packages/cli/lib/browser-audit.mjs +32 -2
- package/packages/cli/lib/entity-map.mjs +129 -2
- package/plugins/agent-skills/cosmo/.cosmo-agent.json +1 -1
- package/plugins/antigravity/cosmo.md +1 -1
- package/plugins/claude-code/cosmo/.claude-plugin/plugin.json +1 -1
- package/templates/astro-site/.cosmo/entities/config.json +1 -0
- package/templates/astro-site/.cosmo/policies/browser-audit.json +4 -0
- package/templates/astro-site/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
All notable Cosmo changes are recorded here.
|
|
4
4
|
|
|
5
|
+
## 1.14.0 — Native EntityMap and resilient browser signals
|
|
6
|
+
|
|
7
|
+
- Classified browser console messages explicitly marked as report-only CSP observations as visible, non-blocking warnings while keeping enforced CSP failures critical.
|
|
8
|
+
- Added a project-owned browser QA policy for narrow, case-insensitive console-message allowlist patterns without allowing uncaught page errors to be suppressed.
|
|
9
|
+
- Added native Astro EntityMap compilation from the approved route inventory and built HTML without requiring Cosmo Markdown pages or changing preserved source.
|
|
10
|
+
- Added native route classification, noindex filtering, per-route name/type overrides, native enrichment subjects, and build-before-compile command ordering.
|
|
11
|
+
|
|
5
12
|
## 1.13.1 — Resilient adopted-site QA
|
|
6
13
|
|
|
7
14
|
- Changed browser navigation from open-ended network-idle waiting to bounded load navigation, with a short settle period for lazy scripts.
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Cosmo helps an AI coding assistant build a complete, original Astro website for
|
|
|
4
4
|
|
|
5
5
|
You do **not** need to know how to code. Cosmo supports Claude Code, Codex, and Google Antigravity.
|
|
6
6
|
|
|
7
|
-
Current version: **1.
|
|
7
|
+
Current version: **1.14.0**
|
|
8
8
|
|
|
9
9
|
## Quick install
|
|
10
10
|
|
|
@@ -82,7 +82,7 @@ This is the only part of the beginner setup that uses a terminal. It is one inst
|
|
|
82
82
|
cosmo --version
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
You should see `1.
|
|
85
|
+
You should see `1.14.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
|
|
86
86
|
|
|
87
87
|
### On Windows
|
|
88
88
|
|
|
@@ -99,7 +99,7 @@ You should see `1.13.1` or a newer version. Cosmo automatically installs its Cla
|
|
|
99
99
|
cosmo --version
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
You should see `1.
|
|
102
|
+
You should see `1.14.0` or a newer version. Cosmo automatically installs its Claude, Codex, and Antigravity launchers.
|
|
103
103
|
|
|
104
104
|
## Step 4: create your website folder
|
|
105
105
|
|
|
@@ -438,6 +438,8 @@ No paid service is required. Wikidata can suggest public identifiers; Google Kno
|
|
|
438
438
|
|
|
439
439
|
Cosmo publishes `/entitymap.json` and `/entitymap.html`, adds the discovery links, and checks the files during release QA. Automated output remains clearly marked as a draft until you review it. EntityMap complements the site's Schema.org JSON-LD and does not promise higher rankings.
|
|
440
440
|
|
|
441
|
+
On an adopted Astro site, EntityMap uses the approved native route inventory and the site's built HTML. It does not require `src/content/pages`, replace hand-authored `.astro` pages, or change the existing design. Home and about represent the Organization, service and service-area routes become Services and Places, and other routes become Concepts unless a reviewed route override supplies a different name or core type.
|
|
442
|
+
|
|
441
443
|
Advanced users can run:
|
|
442
444
|
|
|
443
445
|
```bash
|
|
@@ -537,6 +539,8 @@ The checks cover:
|
|
|
537
539
|
|
|
538
540
|
Use `--no-build` when a current `dist` already exists. Use `--no-lighthouse` to skip Lighthouse during a browser-only diagnostic. If Chrome is in a non-standard location, set `COSMO_CHROME_PATH` to its executable.
|
|
539
541
|
|
|
542
|
+
Browser console and page errors normally block release. CSP messages explicitly marked `Report Only` are retained as non-blocking warnings, while enforced CSP failures remain critical. If a reviewed third-party tool emits another harmless diagnostic, add a narrow identifying substring to `.cosmo/policies/browser-audit.json`; Cosmo will keep the message visible as a warning instead of silently discarding it. See [Browser QA](docs/BROWSER-QA.md) for the policy format and safety guidance.
|
|
543
|
+
|
|
540
544
|
## Release readiness
|
|
541
545
|
|
|
542
546
|
After workflow, generation, approvals, and QA are complete:
|
package/docs/BROWSER-QA.md
CHANGED
|
@@ -12,6 +12,21 @@ Every generated HTML route is rendered at:
|
|
|
12
12
|
|
|
13
13
|
Each render checks successful navigation, horizontal overflow, console and page errors, WCAG 2 A/AA violations, and whether the first keyboard tab reaches an element with a visible focus treatment. Reduced-motion preference is enabled during the run.
|
|
14
14
|
|
|
15
|
+
Genuine JavaScript console errors and uncaught page errors are critical. Content Security Policy messages explicitly marked `Report Only` are preserved as `browser-console-allowed` warnings because the browser is reporting an observation rather than an enforced failure. An enforced CSP failure remains critical.
|
|
16
|
+
|
|
17
|
+
Projects can classify another known, reviewed console message as non-blocking by adding a distinctive substring to `.cosmo/policies/browser-audit.json`:
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"version": 1,
|
|
22
|
+
"allowedConsolePatterns": [
|
|
23
|
+
"distinctive text from the reviewed third-party diagnostic"
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Matching is case-insensitive and uses literal substrings, not regular expressions. Allowed messages remain visible in the JSON report as warnings, including the pattern that matched. Keep patterns narrow: broad entries such as `error`, a provider name, or a URL could hide unrelated failures. Page errors cannot be allowlisted.
|
|
29
|
+
|
|
15
30
|
Navigation waits for the page load event for at most 45 seconds, then allows a short settle period for lazy scripts. It does not wait for network idle because maps, analytics, and other long-lived third-party requests may never become idle. A timed-out route is recorded as a critical finding for that viewport; Cosmo closes that page and continues checking the remaining routes so the JSON report always contains the partial run and every timeout observed.
|
|
16
31
|
|
|
17
32
|
Normal-state full-page screenshots are written before the keyboard interaction. This keeps the reference captures useful for visual review while still testing the focus path independently.
|
package/docs/ENTITY-MAP.md
CHANGED
|
@@ -18,6 +18,34 @@ When beginning a site, the assistant asks whether the user wants an EntityMap. I
|
|
|
18
18
|
|
|
19
19
|
Only indexable pages are included by default. Set `includeNoindex` only after deciding that publicly accessible noindex pages should be represented.
|
|
20
20
|
|
|
21
|
+
## Existing Astro sites
|
|
22
|
+
|
|
23
|
+
EntityMap supports adopted `native-astro` projects without converting them to Cosmo Markdown pages or changing their components and design. The approved `.cosmo/adoption/route-inventory.json` remains the route authority. Cosmo builds the existing site, then reads each inventoried route from `dist` and extracts its title, meta description, canonical URL, robots directive, H1, and first substantive paragraph.
|
|
24
|
+
|
|
25
|
+
Native routes are classified conservatively:
|
|
26
|
+
|
|
27
|
+
- `/` and `/about` (or `/about-us`) represent the canonical Organization.
|
|
28
|
+
- Routes below `/services/` become Services.
|
|
29
|
+
- Routes below `/service-areas/` become Places.
|
|
30
|
+
- Other routes, including guides, roof types, and calculators, become Concepts.
|
|
31
|
+
|
|
32
|
+
Noindex routes remain excluded unless `includeNoindex` is deliberately enabled. Missing built HTML for an approved route is a clear build/inventory error rather than silently producing an incomplete map.
|
|
33
|
+
|
|
34
|
+
When route structure alone is not specific enough, add a reviewed name or EntityMap v1.0 type override to `.cosmo/entities/config.json`:
|
|
35
|
+
|
|
36
|
+
```json
|
|
37
|
+
{
|
|
38
|
+
"routeOverrides": {
|
|
39
|
+
"/calculators/roof-cost": {
|
|
40
|
+
"name": "Roof Cost Estimator",
|
|
41
|
+
"type": "Metric"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Override keys are normalized site routes. Names must be non-empty and types must come from the EntityMap v1.0 core vocabulary. Organization routes always retain the approved Entity Canon name and identifier. The same native subjects are used by Wikidata, Google Knowledge Graph, Google Places, and TextRazor enrichment.
|
|
48
|
+
|
|
21
49
|
## Commands for advanced users
|
|
22
50
|
|
|
23
51
|
```bash
|
|
@@ -78,7 +106,7 @@ An absent Google or Wikidata result is never treated as proof that a business, p
|
|
|
78
106
|
|
|
79
107
|
| Path | Purpose |
|
|
80
108
|
| --- | --- |
|
|
81
|
-
| `.cosmo/entities/config.json` | Feature status, review record, accepted matches, and provider settings. |
|
|
109
|
+
| `.cosmo/entities/config.json` | Feature status, review record, native route overrides, accepted matches, and provider settings. |
|
|
82
110
|
| `.cosmo/entities/candidates.json` | Private enrichment suggestions and their review state. |
|
|
83
111
|
| `.cosmo/reports/entity-check.json` | Deterministic conformance and integrity report. |
|
|
84
112
|
| `public/entitymap.json` | Generated machine-readable publication. |
|
package/package.json
CHANGED
|
@@ -65,7 +65,7 @@ import {
|
|
|
65
65
|
workflowSummary,
|
|
66
66
|
} from '../lib/workflow.mjs';
|
|
67
67
|
|
|
68
|
-
const VERSION = '1.
|
|
68
|
+
const VERSION = '1.14.0';
|
|
69
69
|
const cliDirectory = path.dirname(fileURLToPath(import.meta.url));
|
|
70
70
|
const templateDirectory = path.resolve(cliDirectory, '../../../templates/astro-site');
|
|
71
71
|
const [command = 'start', ...rawArgs] = process.argv.slice(2);
|
|
@@ -344,18 +344,31 @@ function prepareEntityMap(target) {
|
|
|
344
344
|
return result;
|
|
345
345
|
}
|
|
346
346
|
|
|
347
|
+
function usesNativeEntityMap(target) {
|
|
348
|
+
const project = readProject(target).data;
|
|
349
|
+
const config = readEntityMapConfig(target, { required: false }).data;
|
|
350
|
+
return project.sourceModel === 'native-astro' && config?.enabled === true;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function prepareAndBuild(target, shouldBuild = true) {
|
|
354
|
+
const nativeEntityMap = usesNativeEntityMap(target);
|
|
355
|
+
if (shouldBuild && nativeEntityMap) await run('npm', ['run', 'build'], { cwd: target });
|
|
356
|
+
prepareEntityMap(target);
|
|
357
|
+
if (shouldBuild && !nativeEntityMap) await run('npm', ['run', 'build'], { cwd: target });
|
|
358
|
+
}
|
|
359
|
+
|
|
347
360
|
async function build(args) {
|
|
348
361
|
const { positional } = parseOptions(args);
|
|
349
362
|
const target = projectDirectory(positional[0] ?? '.');
|
|
350
363
|
readProject(target);
|
|
351
|
-
|
|
352
|
-
await run('npm', ['run', 'build'], { cwd: target });
|
|
364
|
+
await prepareAndBuild(target);
|
|
353
365
|
}
|
|
354
366
|
|
|
355
367
|
async function dev(args) {
|
|
356
368
|
const { positional } = parseOptions(args);
|
|
357
369
|
const target = projectDirectory(positional[0] ?? '.');
|
|
358
370
|
readProject(target);
|
|
371
|
+
if (usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
|
|
359
372
|
prepareEntityMap(target);
|
|
360
373
|
await run('npm', ['run', 'dev'], { cwd: target });
|
|
361
374
|
}
|
|
@@ -364,8 +377,7 @@ async function check(args) {
|
|
|
364
377
|
const { options, positional } = parseOptions(args);
|
|
365
378
|
const target = projectDirectory(positional[0] ?? '.');
|
|
366
379
|
readProject(target);
|
|
367
|
-
|
|
368
|
-
if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
|
|
380
|
+
await prepareAndBuild(target, !options['no-build']);
|
|
369
381
|
const report = auditDist(path.join(target, 'dist'));
|
|
370
382
|
const reportFile = writeAuditReport(target, report);
|
|
371
383
|
console.log(`Cosmo QA: ${report.summary.pages} pages, ${report.summary.critical} critical, ${report.summary.warnings} warnings`);
|
|
@@ -470,8 +482,7 @@ async function browserCheck(args) {
|
|
|
470
482
|
const { options, positional } = parseOptions(args);
|
|
471
483
|
const target = projectDirectory(positional[0] ?? '.');
|
|
472
484
|
readProject(target);
|
|
473
|
-
|
|
474
|
-
if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
|
|
485
|
+
await prepareAndBuild(target, !options['no-build']);
|
|
475
486
|
const server = await staticServer(target);
|
|
476
487
|
const port = server.address().port;
|
|
477
488
|
const baseUrl = `http://127.0.0.1:${port}/`;
|
|
@@ -575,6 +586,7 @@ async function entityCommand(args) {
|
|
|
575
586
|
if (subcommand === 'build' || subcommand === 'check') {
|
|
576
587
|
const { positional } = parseOptions(rest);
|
|
577
588
|
const target = projectDirectory(positional[0] ?? '.');
|
|
589
|
+
if (usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
|
|
578
590
|
const result = writeEntityMap(target);
|
|
579
591
|
console.log(`EntityMap: ${result.report.enabled ? `${result.report.summary.entities} entities, ${result.report.summary.chunks} chunks` : 'disabled'}, ${result.report.summary.blocking} blocking, ${result.report.summary.warnings} warnings`);
|
|
580
592
|
console.log(`Report: ${result.reportFile}`);
|
|
@@ -1056,14 +1068,14 @@ async function deployCommand(args) {
|
|
|
1056
1068
|
const { options, positional } = parseOptions(rest);
|
|
1057
1069
|
const target = projectDirectory(positional[0] ?? '.');
|
|
1058
1070
|
readProject(target);
|
|
1059
|
-
|
|
1060
|
-
if (!options['no-build']) await run('npm', ['run', 'build'], { cwd: target });
|
|
1071
|
+
await prepareAndBuild(target, !options['no-build']);
|
|
1061
1072
|
await run('npm', ['run', 'preview', '--', '--host', '127.0.0.1'], { cwd: target });
|
|
1062
1073
|
return;
|
|
1063
1074
|
}
|
|
1064
1075
|
if (['preview', 'production'].includes(subcommand)) {
|
|
1065
1076
|
const { options, positional } = parseOptions(rest);
|
|
1066
1077
|
const target = projectDirectory(positional[0] ?? '.');
|
|
1078
|
+
if (!options['no-build'] && usesNativeEntityMap(target)) await run('npm', ['run', 'build'], { cwd: target });
|
|
1067
1079
|
prepareEntityMap(target);
|
|
1068
1080
|
const record = await deployProject(target, subcommand, { build: !options['no-build'], envFile: options['env-file'] });
|
|
1069
1081
|
console.log(`${subcommand === 'production' ? 'Production' : 'Preview'} deployed: ${record.url ?? record.remoteDir ?? 'URL unavailable in provider output'}`);
|
|
@@ -14,6 +14,30 @@ const VIEWPORTS = [
|
|
|
14
14
|
];
|
|
15
15
|
const NAVIGATION_TIMEOUT_MS = 45_000;
|
|
16
16
|
const PAGE_SETTLE_MS = 250;
|
|
17
|
+
const REPORT_ONLY_CSP = /(?:\[report[ -]?only\]|report[ -]?only).*content security policy|content security policy.*report[ -]?only/i;
|
|
18
|
+
|
|
19
|
+
function browserAuditPolicy(projectDir) {
|
|
20
|
+
const file = path.join(projectDir, '.cosmo', 'policies', 'browser-audit.json');
|
|
21
|
+
if (!fs.existsSync(file)) return { allowedConsolePatterns: [] };
|
|
22
|
+
let policy;
|
|
23
|
+
try {
|
|
24
|
+
policy = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
25
|
+
} catch (error) {
|
|
26
|
+
throw new Error(`Invalid browser-audit policy at ${file}: ${error.message}`);
|
|
27
|
+
}
|
|
28
|
+
if (!Array.isArray(policy.allowedConsolePatterns) || policy.allowedConsolePatterns.some((item) => typeof item !== 'string' || !item.trim())) {
|
|
29
|
+
throw new Error(`Browser-audit policy allowedConsolePatterns must be an array of non-empty strings: ${file}`);
|
|
30
|
+
}
|
|
31
|
+
return { allowedConsolePatterns: policy.allowedConsolePatterns.map((item) => item.trim()) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function classifyConsoleError(message, allowedConsolePatterns = []) {
|
|
35
|
+
const text = String(message);
|
|
36
|
+
if (REPORT_ONLY_CSP.test(text)) return { allowed: true, matchedBy: 'built-in:report-only-csp' };
|
|
37
|
+
const normalized = text.toLowerCase();
|
|
38
|
+
const matched = allowedConsolePatterns.find((pattern) => normalized.includes(String(pattern).trim().toLowerCase()));
|
|
39
|
+
return matched ? { allowed: true, matchedBy: `project:${matched}` } : { allowed: false, matchedBy: null };
|
|
40
|
+
}
|
|
17
41
|
|
|
18
42
|
function walk(directory, suffix) {
|
|
19
43
|
if (!fs.existsSync(directory)) return [];
|
|
@@ -69,6 +93,7 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
|
|
|
69
93
|
const distDir = path.join(projectDir, 'dist');
|
|
70
94
|
const routes = walk(distDir, '.html').map((file) => routeForFile(distDir, file)).sort();
|
|
71
95
|
if (!routes.length) throw new Error('No built HTML routes found for browser QA.');
|
|
96
|
+
const policy = browserAuditPolicy(projectDir);
|
|
72
97
|
const screenshotsDir = path.join(projectDir, '.cosmo', 'reports', 'screenshots');
|
|
73
98
|
fs.mkdirSync(screenshotsDir, { recursive: true });
|
|
74
99
|
const browser = await browserType.launch({ executablePath, headless: true });
|
|
@@ -81,13 +106,17 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
|
|
|
81
106
|
for (const viewport of VIEWPORTS) {
|
|
82
107
|
let page = null;
|
|
83
108
|
const runtimeErrors = [];
|
|
109
|
+
const allowedConsoleErrors = [];
|
|
84
110
|
let stage = 'page-create';
|
|
85
111
|
try {
|
|
86
112
|
page = await browser.newPage({ viewport });
|
|
87
113
|
page.on('console', (message) => {
|
|
88
114
|
if (message.type() === 'error') {
|
|
89
115
|
const location = message.location();
|
|
90
|
-
|
|
116
|
+
const detail = `console: ${message.text()}${location.url ? ` (${location.url})` : ''}`;
|
|
117
|
+
const classification = classifyConsoleError(message.text(), policy.allowedConsolePatterns);
|
|
118
|
+
if (classification.allowed) allowedConsoleErrors.push({ detail, matchedBy: classification.matchedBy });
|
|
119
|
+
else runtimeErrors.push(detail);
|
|
91
120
|
}
|
|
92
121
|
});
|
|
93
122
|
page.on('pageerror', (error) => runtimeErrors.push(`page: ${error.message}`));
|
|
@@ -140,7 +169,8 @@ export async function auditBrowser(projectDir, { baseUrl, lighthouseEnabled = tr
|
|
|
140
169
|
else if (!focus.visible) critical.push({ route, viewport: viewport.width, rule: 'keyboard-focus-invisible', detail: focus });
|
|
141
170
|
|
|
142
171
|
for (const detail of runtimeErrors) critical.push({ route, viewport: viewport.width, rule: 'browser-runtime-error', detail });
|
|
143
|
-
|
|
172
|
+
for (const detail of allowedConsoleErrors) warnings.push({ route, viewport: viewport.width, rule: 'browser-console-allowed', detail });
|
|
173
|
+
pages.push({ route, viewport, dimensions, focus, violations: accessibility.violations.length, runtimeErrors, allowedConsoleErrors, screenshot: path.relative(projectDir, screenshot) });
|
|
144
174
|
} catch (error) {
|
|
145
175
|
critical.push({
|
|
146
176
|
route,
|
|
@@ -3,6 +3,7 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import matter from 'gray-matter';
|
|
5
5
|
import { readProject, slugify, writeJson } from './project.mjs';
|
|
6
|
+
import { normalizeRoute, routeForFile } from './routes.mjs';
|
|
6
7
|
|
|
7
8
|
const SPEC = 'https://entitymap.org/spec/v1.0';
|
|
8
9
|
const TYPES = new Set(['Concept', 'ProprietaryTerm', 'Methodology', 'Metric', 'Taxonomy', 'Person', 'Organization', 'SoftwareProduct', 'PhysicalProduct', 'Service', 'Platform', 'Place', 'Event', 'Standard', 'Regulation']);
|
|
@@ -16,6 +17,7 @@ export const DEFAULT_ENTITY_MAP_CONFIG = {
|
|
|
16
17
|
verificationStatus: 'generator-draft',
|
|
17
18
|
review: { reviewedBy: null, reviewedAt: null },
|
|
18
19
|
approvedMatches: [],
|
|
20
|
+
routeOverrides: {},
|
|
19
21
|
providers: {
|
|
20
22
|
wikidata: { enabled: true },
|
|
21
23
|
googleKnowledgeGraph: { enabled: false, apiKeyEnv: 'COSMO_GOOGLE_KG_API_KEY' },
|
|
@@ -51,6 +53,13 @@ export function readEntityMapConfig(projectDir, { required = true } = {}) {
|
|
|
51
53
|
if (!['generator-draft', 'self-declared'].includes(data.verificationStatus)) throw new Error('EntityMap verificationStatus must be generator-draft or self-declared.');
|
|
52
54
|
if (data.verificationStatus === 'self-declared' && (!data.review?.reviewedBy || !data.review?.reviewedAt)) throw new Error('A self-declared EntityMap requires an explicit human review record.');
|
|
53
55
|
if (!Array.isArray(data.approvedMatches)) throw new Error('EntityMap approvedMatches must be an array.');
|
|
56
|
+
if (data.routeOverrides !== undefined && (!data.routeOverrides || typeof data.routeOverrides !== 'object' || Array.isArray(data.routeOverrides))) throw new Error('EntityMap routeOverrides must be an object keyed by route.');
|
|
57
|
+
for (const [route, override] of Object.entries(data.routeOverrides ?? {})) {
|
|
58
|
+
if (!route.startsWith('/') || !normalizeRoute(route) || !override || typeof override !== 'object' || Array.isArray(override)) throw new Error(`EntityMap route override is invalid: ${route}`);
|
|
59
|
+
if (override.name !== undefined && (typeof override.name !== 'string' || !override.name.trim())) throw new Error(`EntityMap route override name must be a non-empty string: ${route}`);
|
|
60
|
+
if (override.type !== undefined && !TYPES.has(override.type)) throw new Error(`EntityMap route override type is unsupported for ${route}: ${override.type}`);
|
|
61
|
+
}
|
|
62
|
+
data.routeOverrides ??= {};
|
|
54
63
|
return { file, data };
|
|
55
64
|
}
|
|
56
65
|
|
|
@@ -101,6 +110,116 @@ function contentPages(projectDir, includeNoindex) {
|
|
|
101
110
|
}).filter((page) => page.data.path && page.data.title && page.data.description && (includeNoindex || page.data.indexability !== 'noindex'));
|
|
102
111
|
}
|
|
103
112
|
|
|
113
|
+
function walkHtml(directory) {
|
|
114
|
+
if (!fs.existsSync(directory)) return [];
|
|
115
|
+
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
116
|
+
const file = path.join(directory, entry.name);
|
|
117
|
+
return entry.isDirectory() ? walkHtml(file) : file.endsWith('.html') ? [file] : [];
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function decodeHtml(value) {
|
|
122
|
+
const named = { amp: '&', apos: "'", gt: '>', lt: '<', nbsp: ' ', quot: '"' };
|
|
123
|
+
return String(value ?? '').replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
|
|
124
|
+
if (entity[0] === '#') {
|
|
125
|
+
const hexadecimal = entity[1]?.toLowerCase() === 'x';
|
|
126
|
+
const code = Number.parseInt(entity.slice(hexadecimal ? 2 : 1), hexadecimal ? 16 : 10);
|
|
127
|
+
return Number.isFinite(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
|
|
128
|
+
}
|
|
129
|
+
return named[entity.toLowerCase()] ?? match;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function plainText(value) {
|
|
134
|
+
return decodeHtml(String(value ?? '').replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function attribute(tag, name) {
|
|
138
|
+
return tag.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, 'i'))?.[1]?.trim() ?? '';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function metaContent(html, name) {
|
|
142
|
+
const tag = [...html.matchAll(/<meta\b[^>]*>/gi)].map((match) => match[0]).find((item) => attribute(item, 'name').toLowerCase() === name);
|
|
143
|
+
return tag ? decodeHtml(attribute(tag, 'content')) : '';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function canonicalUrl(html) {
|
|
147
|
+
const tag = [...html.matchAll(/<link\b[^>]*>/gi)].map((match) => match[0]).find((item) => attribute(item, 'rel').toLowerCase().split(/\s+/).includes('canonical'));
|
|
148
|
+
return tag ? decodeHtml(attribute(tag, 'href')) : '';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function substantivePassage(html, fallback) {
|
|
152
|
+
const main = html.match(/<main\b[^>]*>([\s\S]*?)<\/main>/i)?.[1] ?? html.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i)?.[1] ?? html;
|
|
153
|
+
const surface = main.replace(/<(?:script|style|noscript|svg|nav|header|footer|form)\b[^>]*>[\s\S]*?<\/(?:script|style|noscript|svg|nav|header|footer|form)>/gi, ' ');
|
|
154
|
+
const passages = [...surface.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/gi)].map((match) => plainText(match[1])).filter((value) => value.length >= 40);
|
|
155
|
+
const selected = passages[0] ?? fallback;
|
|
156
|
+
if (selected.length <= 600) return selected;
|
|
157
|
+
const shortened = selected.slice(0, 600);
|
|
158
|
+
const boundary = shortened.lastIndexOf(' ');
|
|
159
|
+
return shortened.slice(0, boundary > 0 ? boundary : 600).trim();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function inferredNativeType(route) {
|
|
163
|
+
if (route === '/' || /^\/(?:about|about-us)$/.test(route)) return 'Organization';
|
|
164
|
+
if (route.startsWith('/services/')) return 'Service';
|
|
165
|
+
if (route.startsWith('/service-areas/')) return 'Place';
|
|
166
|
+
return 'Concept';
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function nativePages(projectDir, project, config) {
|
|
170
|
+
const inventoryFile = path.join(projectDir, '.cosmo', 'adoption', 'route-inventory.json');
|
|
171
|
+
const inventory = readJson(inventoryFile, 'Native route inventory');
|
|
172
|
+
if (!Array.isArray(inventory.routes)) throw new Error(`Native route inventory routes must be an array: ${inventoryFile}`);
|
|
173
|
+
const distDir = path.join(projectDir, 'dist');
|
|
174
|
+
if (!fs.existsSync(distDir)) throw new Error('Native EntityMap requires built HTML in dist. Run the project build before EntityMap compilation.');
|
|
175
|
+
const htmlByRoute = new Map(walkHtml(distDir).map((file) => [normalizeRoute(routeForFile(distDir, file)), file]));
|
|
176
|
+
const overrides = new Map(Object.entries(config.routeOverrides ?? {}).map(([route, value]) => [normalizeRoute(route), value]));
|
|
177
|
+
const pages = [];
|
|
178
|
+
for (const [index, routeRecord] of inventory.routes.entries()) {
|
|
179
|
+
if (typeof routeRecord.path !== 'string' || !routeRecord.path.trim()) continue;
|
|
180
|
+
const route = normalizeRoute(routeRecord.path);
|
|
181
|
+
const file = htmlByRoute.get(route);
|
|
182
|
+
if (!file) throw new Error(`Native EntityMap could not find built HTML for ${routeRecord.path}. Run the project build and verify the approved route inventory.`);
|
|
183
|
+
const html = fs.readFileSync(file, 'utf8');
|
|
184
|
+
const title = plainText(html.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i)?.[1]);
|
|
185
|
+
const description = metaContent(html, 'description');
|
|
186
|
+
const h1 = plainText(html.match(/<h1\b[^>]*>([\s\S]*?)<\/h1>/i)?.[1]);
|
|
187
|
+
const robots = metaContent(html, 'robots').toLowerCase().split(',').map((item) => item.trim());
|
|
188
|
+
const indexability = routeRecord.indexability === 'noindex' || robots.includes('noindex') ? 'noindex' : 'index';
|
|
189
|
+
if (!config.includeNoindex && indexability === 'noindex') continue;
|
|
190
|
+
if (!title || !description) throw new Error(`Native EntityMap route ${routeRecord.path} requires a built title and meta description.`);
|
|
191
|
+
const canonical = canonicalUrl(html);
|
|
192
|
+
const sourcePath = canonical || new URL(routeRecord.path, project.site).toString();
|
|
193
|
+
const override = overrides.get(route) ?? {};
|
|
194
|
+
const nativeType = override.type ?? inferredNativeType(route);
|
|
195
|
+
pages.push({
|
|
196
|
+
id: routeRecord.id || (route === '/' ? 'home' : slugify(route ?? routeRecord.source ?? `native-route-${index + 1}`)),
|
|
197
|
+
file,
|
|
198
|
+
native: true,
|
|
199
|
+
data: {
|
|
200
|
+
path: sourcePath,
|
|
201
|
+
route,
|
|
202
|
+
title,
|
|
203
|
+
description,
|
|
204
|
+
h1,
|
|
205
|
+
primaryTopic: override.name?.trim() || h1 || title,
|
|
206
|
+
pageType: nativeType === 'Service' ? 'service' : nativeType === 'Place' ? 'location' : 'native',
|
|
207
|
+
indexability,
|
|
208
|
+
nativeType,
|
|
209
|
+
nativeName: override.name?.trim() || null,
|
|
210
|
+
sections: [substantivePassage(html, description)],
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return pages;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function entityPages(projectDir, project, config) {
|
|
218
|
+
return project.sourceModel === 'native-astro'
|
|
219
|
+
? nativePages(projectDir, project, config)
|
|
220
|
+
: contentPages(projectDir, config.includeNoindex === true);
|
|
221
|
+
}
|
|
222
|
+
|
|
104
223
|
function strings(value, key = '') {
|
|
105
224
|
if (typeof value === 'string') return ['href', 'label', 'heading', 'eyebrow', 'title'].includes(key) ? [] : [value.trim()].filter(Boolean);
|
|
106
225
|
if (Array.isArray(value)) return value.flatMap((item) => strings(item, key));
|
|
@@ -115,6 +234,13 @@ function chunkText(page) {
|
|
|
115
234
|
}
|
|
116
235
|
|
|
117
236
|
function entityIdentity(page, publisher) {
|
|
237
|
+
if (page.native) {
|
|
238
|
+
const type = page.data.nativeType;
|
|
239
|
+
if (type === 'Organization') return { entityId: publisher.id, '@type': 'Organization', name: publisher.officialName, description: publisher.descriptions.short };
|
|
240
|
+
const name = page.data.nativeName || page.data.h1 || page.data.title;
|
|
241
|
+
const prefixes = { Service: 'service', Place: 'place', Concept: 'topic' };
|
|
242
|
+
return { entityId: `${prefixes[type] ?? slugify(type)}-${slugify(name)}`, '@type': type, name, description: page.data.description };
|
|
243
|
+
}
|
|
118
244
|
if ((['home', 'standard'].includes(page.data.pageType) && page.data.path === '/') || page.data.schemaType === 'AboutPage') {
|
|
119
245
|
return { entityId: publisher.id, '@type': 'Organization', name: publisher.officialName, description: publisher.descriptions.short };
|
|
120
246
|
}
|
|
@@ -147,7 +273,7 @@ export function compileEntityMap(projectDir) {
|
|
|
147
273
|
const config = readEntityMapConfig(projectDir).data;
|
|
148
274
|
if (!config.enabled) throw new Error('EntityMap is disabled for this project. Run cosmo entity init . --enable.');
|
|
149
275
|
const publisher = readJson(path.join(projectDir, '.cosmo', 'brand', 'entity-canon.json'), 'Entity Canon');
|
|
150
|
-
const pages =
|
|
276
|
+
const pages = entityPages(projectDir, project, config);
|
|
151
277
|
const grouped = new Map();
|
|
152
278
|
for (const page of pages) {
|
|
153
279
|
const identity = entityIdentity(page, publisher);
|
|
@@ -286,9 +412,10 @@ function candidateId(value) {
|
|
|
286
412
|
}
|
|
287
413
|
|
|
288
414
|
function entitySubjects(projectDir) {
|
|
415
|
+
const project = readProject(projectDir).data;
|
|
289
416
|
const publisher = readJson(path.join(projectDir, '.cosmo', 'brand', 'entity-canon.json'), 'Entity Canon');
|
|
290
417
|
const config = readEntityMapConfig(projectDir).data;
|
|
291
|
-
const pages =
|
|
418
|
+
const pages = entityPages(projectDir, project, config);
|
|
292
419
|
const subjects = new Map([[publisher.id, { entityId: publisher.id, name: publisher.officialName, type: 'Organization' }]]);
|
|
293
420
|
for (const page of pages) {
|
|
294
421
|
const identity = entityIdentity(page, publisher);
|