@hagicode/hagilight-core 0.11.1-dev.129.1.ea757b8 → 0.12.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
@@ -117,6 +117,57 @@ After trimming, `HAGILIGHT_BUILD_BRANCH` must be nonblank and free of control ch
117
117
 
118
118
  The footer shows the commit as its first seven characters, with the full hash in the `title` attribute. The core `Footer` renders this line only when it receives a `buildInfo` prop or the `hagilight()` integration from `@hagicode/hagilight/integration` is registered; otherwise it renders no build text.
119
119
 
120
+ ## Site metadata file
121
+
122
+ The integrations write `.well-known/hagilight.metadata.json` into the build output. This module owns the contract, so the three packages cannot drift apart.
123
+
124
+ - `@hagicode/hagilight-core/site-metadata` is browser-safe. It exports `SITE_METADATA_PATH` (`.well-known/hagilight.metadata.json`, the only place the path is spelled), `buildSiteMetadata`, `validateSiteMetadata` (returns a list of problems; empty means valid), `serializeSiteMetadata` (minified, fixed key order, trailing newline), `detectAnalyticsLoaders` (checks built HTML for each provider's loader markers), `ANALYTICS_LOADER_MARKERS`, and `resolveSiteMetadataOption` (the shared `metadata` option resolver).
125
+ - `@hagicode/hagilight-core/site-metadata-writer` is Node-only. `findDiscoveryOutputs(outDir)` reports which discovery files the build produced, and `writeSiteMetadata({ outDir, metadata, siteOwnedFiles, logger })` writes the file through a temporary file and a rename. An existing file, in the output or in `siteOwnedFiles`, is kept and reported.
126
+ - `@hagicode/hagilight-core/site-metadata-ownership` decides which integration writes the file when plain Astro and Starlight are both registered. Starlight claims at plugin creation, plain Astro defers, and the owner's write runs after every deferring peer has reported its build step.
127
+
128
+ The file follows `schemaVersion: 1`. Fields may be added within version 1. Renaming, removing, or re-typing a field requires a new version.
129
+
130
+ ```json
131
+ {
132
+ "schemaVersion": 1,
133
+ "generator": { "name": "@hagicode/hagilight-starlight", "version": "0.1.0" },
134
+ "site": {
135
+ "name": "HagiCode Docs",
136
+ "url": "https://docs.hagicode.com/",
137
+ "base": "/",
138
+ "description": "Documentation for HagiCode."
139
+ },
140
+ "languages": {
141
+ "default": "en-US",
142
+ "locales": [
143
+ { "code": "en-US", "lang": "en-US", "path": "/" },
144
+ { "code": "zh-CN", "lang": "zh-CN", "path": "/zh-CN/" }
145
+ ]
146
+ },
147
+ "build": {
148
+ "branch": "main",
149
+ "commit": "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678",
150
+ "builtAt": "2026-10-17T08:12:34Z"
151
+ },
152
+ "discovery": {
153
+ "sitemap": "/sitemap-index.xml",
154
+ "robots": "/robots.txt",
155
+ "rss": "/rss.xml",
156
+ "llms": "/llms.txt"
157
+ },
158
+ "analytics": { "googleAnalytics": true, "fiftyOneLa": false, "posthog": true },
159
+ "features": { "seo": true, "promoto": true }
160
+ }
161
+ ```
162
+
163
+ Rules that every writer applies:
164
+
165
+ - `site.name` comes from the `name` option, then the site's own title, then the home page name, then the URL hostname. `site.description` is omitted when no description exists.
166
+ - `build` holds the same branch, commit, and build time as the footer, with `unknown` for any value that cannot be resolved.
167
+ - `discovery` holds site-relative paths, relative to `site.base`, for the artifacts that exist in this build. A key is absent when its file is absent.
168
+ - `analytics` holds three booleans that say whether each provider's loader is in this build. Measurement IDs, 51LA site IDs, and PostHog keys are never written, and neither are environment values, absolute paths, or Git remotes.
169
+ - Only the schema fields are copied from typed inputs, so an extra input field cannot leak into the output.
170
+
120
171
  ## Comparison articles
121
172
 
122
173
  Core ships the 136 `*-vs-hagicode` comparison articles (10 locales) as JSON under `data/comparison-articles/<locale>/<slug>.json`. The files are the `1.0.0` structured-article schema, unchanged from the source they moved from. Two entry points split the API by runtime, following the build-info split:
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Decides which Hagilight integration writes `hagilight.metadata.json` when the
3
+ * plain-Astro integration and the Starlight plugin are both registered. Same
4
+ * `globalThis` pattern as `rss-ownership.ts`, so separately installed copies of
5
+ * this module still see each other.
6
+ *
7
+ * Ownership is decided by claims: the Starlight plugin claims at creation, and the
8
+ * plain-Astro integration asks at config setup. The write is coordinated at build
9
+ * time. The owner hands over its write closure. Each deferring peer reports when
10
+ * its own build hook has finished (for example after `llms.txt`), and the write runs
11
+ * once the owner and every pending peer are done, whichever hook finishes last.
12
+ * Output therefore does not depend on hook or registration order.
13
+ */
14
+ export type SiteMetadataOwnerPackage = 'astro' | 'starlight';
15
+ export interface SiteMetadataOwnerClaim {
16
+ readonly package: SiteMetadataOwnerPackage;
17
+ readonly enabled: boolean;
18
+ }
19
+ /**
20
+ * Record the Starlight claim as soon as the plugin is created, so a plain-Astro
21
+ * integration listed earlier can defer to it. Returns a callback that withdraws it.
22
+ */
23
+ export declare function registerStarlightSiteMetadataOwner(enabled: boolean): () => void;
24
+ /**
25
+ * Return `'starlight'` when an enabled Starlight claim is registered, else `'astro'`.
26
+ * Call it at plain-Astro config setup, after the Starlight plugin was created.
27
+ */
28
+ export declare function resolveSiteMetadataOwner(): SiteMetadataOwnerPackage;
29
+ /**
30
+ * Called by a deferring peer at config setup. The owner waits for this participant
31
+ * until it calls `reportSiteMetadataBuilt` with the returned token.
32
+ */
33
+ export declare function expectSiteMetadataReport(): symbol;
34
+ /** Called by a deferring peer when its build hook has finished. */
35
+ export declare function reportSiteMetadataBuilt(token: symbol): void;
36
+ /**
37
+ * Called by the owner in its build hook with the closure that writes the file.
38
+ * Runs now when no peer is pending, otherwise when the last pending peer reports.
39
+ */
40
+ export declare function completeSiteMetadataOwnerBuild(write: () => void): void;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Decides which Hagilight integration writes `hagilight.metadata.json` when the
3
+ * plain-Astro integration and the Starlight plugin are both registered. Same
4
+ * `globalThis` pattern as `rss-ownership.ts`, so separately installed copies of
5
+ * this module still see each other.
6
+ *
7
+ * Ownership is decided by claims: the Starlight plugin claims at creation, and the
8
+ * plain-Astro integration asks at config setup. The write is coordinated at build
9
+ * time. The owner hands over its write closure. Each deferring peer reports when
10
+ * its own build hook has finished (for example after `llms.txt`), and the write runs
11
+ * once the owner and every pending peer are done, whichever hook finishes last.
12
+ * Output therefore does not depend on hook or registration order.
13
+ */
14
+ const REGISTRY_KEY = Symbol.for('@hagicode/hagilight-core/site-metadata-registry');
15
+ function registry() {
16
+ const host = globalThis;
17
+ host[REGISTRY_KEY] ??= { claims: new Map(), pending: new Set() };
18
+ return host[REGISTRY_KEY];
19
+ }
20
+ /**
21
+ * Record the Starlight claim as soon as the plugin is created, so a plain-Astro
22
+ * integration listed earlier can defer to it. Returns a callback that withdraws it.
23
+ */
24
+ export function registerStarlightSiteMetadataOwner(enabled) {
25
+ if (typeof enabled !== 'boolean') {
26
+ throw new TypeError('Hagilight site metadata owner enabled flag must be a boolean.');
27
+ }
28
+ const token = Symbol('starlight-site-metadata-owner');
29
+ registry().claims.set(token, { package: 'starlight', enabled });
30
+ return () => {
31
+ registry().claims.delete(token);
32
+ };
33
+ }
34
+ /**
35
+ * Return `'starlight'` when an enabled Starlight claim is registered, else `'astro'`.
36
+ * Call it at plain-Astro config setup, after the Starlight plugin was created.
37
+ */
38
+ export function resolveSiteMetadataOwner() {
39
+ const claims = [...registry().claims.values()];
40
+ return claims.some((claim) => claim.package === 'starlight' && claim.enabled) ? 'starlight' : 'astro';
41
+ }
42
+ /**
43
+ * Called by a deferring peer at config setup. The owner waits for this participant
44
+ * until it calls `reportSiteMetadataBuilt` with the returned token.
45
+ */
46
+ export function expectSiteMetadataReport() {
47
+ const token = Symbol('site-metadata-peer');
48
+ registry().pending.add(token);
49
+ return token;
50
+ }
51
+ /** Called by a deferring peer when its build hook has finished. */
52
+ export function reportSiteMetadataBuilt(token) {
53
+ const state = registry();
54
+ state.pending.delete(token);
55
+ flush(state);
56
+ }
57
+ /**
58
+ * Called by the owner in its build hook with the closure that writes the file.
59
+ * Runs now when no peer is pending, otherwise when the last pending peer reports.
60
+ */
61
+ export function completeSiteMetadataOwnerBuild(write) {
62
+ const state = registry();
63
+ state.ownerWrite = write;
64
+ flush(state);
65
+ }
66
+ function flush(state) {
67
+ if (!state.ownerWrite || state.pending.size > 0)
68
+ return;
69
+ const write = state.ownerWrite;
70
+ state.ownerWrite = undefined;
71
+ write();
72
+ }
@@ -0,0 +1,25 @@
1
+ import { type SiteMetadata, type SiteMetadataDiscovery } from './site-metadata.js';
2
+ export interface SiteMetadataLogger {
3
+ info(message: string): void;
4
+ warn(message: string): void;
5
+ }
6
+ /**
7
+ * Report which discovery artifacts exist in the finished build output. Paths are
8
+ * relative to the site base, so `sitemap-index.xml` is reported as `/sitemap-index.xml`.
9
+ */
10
+ export declare function findDiscoveryOutputs(outDir: string): SiteMetadataDiscovery;
11
+ export interface WriteSiteMetadataInput {
12
+ /** Build output directory. */
13
+ outDir: string;
14
+ metadata: SiteMetadata;
15
+ /** Site-owned copies, such as `public/` or `static/` files. A site-owned file is never overwritten. */
16
+ siteOwnedFiles?: readonly string[];
17
+ logger: SiteMetadataLogger;
18
+ }
19
+ export type WriteSiteMetadataResult = 'written' | 'kept';
20
+ /**
21
+ * Write the metadata file into the build output. An existing file, either in the
22
+ * output or among the site-owned files, is kept and reported. The write goes to a
23
+ * temporary file that is renamed into place, so readers never see a partial file.
24
+ */
25
+ export declare function writeSiteMetadata({ outDir, metadata, siteOwnedFiles, logger }: WriteSiteMetadataInput): WriteSiteMetadataResult;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Node-only writer for `.well-known/hagilight.metadata.json`. Kept separate from
3
+ * `site-metadata.ts` so the browser-safe contract never imports `node:` modules.
4
+ */
5
+ import { existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { SITE_METADATA_PATH, serializeSiteMetadata, } from './site-metadata.js';
8
+ /** Candidate file names per discovery key, in preference order. */
9
+ const DISCOVERY_FILES = {
10
+ sitemap: ['sitemap-index.xml', 'sitemap.xml'],
11
+ robots: ['robots.txt'],
12
+ rss: ['rss.xml'],
13
+ llms: ['llms.txt'],
14
+ };
15
+ function isFile(path) {
16
+ return existsSync(path) && statSync(path).isFile();
17
+ }
18
+ /**
19
+ * Report which discovery artifacts exist in the finished build output. Paths are
20
+ * relative to the site base, so `sitemap-index.xml` is reported as `/sitemap-index.xml`.
21
+ */
22
+ export function findDiscoveryOutputs(outDir) {
23
+ const discovery = {};
24
+ for (const [key, names] of Object.entries(DISCOVERY_FILES)) {
25
+ const found = names.find((name) => isFile(join(outDir, name)));
26
+ if (found)
27
+ discovery[key] = `/${found}`;
28
+ }
29
+ return discovery;
30
+ }
31
+ /**
32
+ * Write the metadata file into the build output. An existing file, either in the
33
+ * output or among the site-owned files, is kept and reported. The write goes to a
34
+ * temporary file that is renamed into place, so readers never see a partial file.
35
+ */
36
+ export function writeSiteMetadata({ outDir, metadata, siteOwnedFiles = [], logger }) {
37
+ const target = join(outDir, SITE_METADATA_PATH);
38
+ const existing = [target, ...siteOwnedFiles].find(isFile);
39
+ if (existing) {
40
+ logger.info(`${SITE_METADATA_PATH} already exists (${existing}); leaving it untouched.`);
41
+ return 'kept';
42
+ }
43
+ mkdirSync(dirname(target), { recursive: true });
44
+ const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
45
+ try {
46
+ writeFileSync(temporary, serializeSiteMetadata(metadata), 'utf8');
47
+ renameSync(temporary, target);
48
+ }
49
+ catch (error) {
50
+ rmSync(temporary, { force: true });
51
+ throw error;
52
+ }
53
+ logger.info(`Generated ${SITE_METADATA_PATH}.`);
54
+ return 'written';
55
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Contract for the `.well-known/hagilight.metadata.json` file. Browser-safe and
3
+ * pure: no Node modules. The Node-only writer lives in `site-metadata-writer.ts`.
4
+ *
5
+ * Values are copied field by field from typed inputs, so new input fields can
6
+ * never leak into the output. Analytics appears only as on/off booleans.
7
+ */
8
+ import { type BuildInfo } from './build-info.js';
9
+ export declare const SITE_METADATA_SCHEMA_VERSION = 1;
10
+ /** Site-relative output path. This is the only place the path is spelled. */
11
+ export declare const SITE_METADATA_PATH = ".well-known/hagilight.metadata.json";
12
+ /**
13
+ * Substrings that a provider's loader leaves in built HTML. Each provider needs
14
+ * every marker in one page. A core test pins these to the shipped loaders, so a
15
+ * loader change fails loudly here.
16
+ */
17
+ export declare const ANALYTICS_LOADER_MARKERS: {
18
+ readonly googleAnalytics: readonly ["https://www.googletagmanager.com/gtag/js"];
19
+ readonly fiftyOneLa: readonly ["id=\"LA_COLLECT\"", "https://sdk.51.la/js-sdk-pro.min.js"];
20
+ readonly posthog: readonly ["__hagilightPosthogInitialized"];
21
+ };
22
+ export interface SiteMetadataGenerator {
23
+ readonly name: string;
24
+ readonly version: string;
25
+ }
26
+ export interface SiteMetadataSite {
27
+ readonly name: string;
28
+ /** Absolute HTTP(S) site URL, as configured. */
29
+ readonly url: string;
30
+ /** Base path with a leading and trailing slash. */
31
+ readonly base: string;
32
+ readonly description?: string;
33
+ }
34
+ export interface SiteMetadataLocale {
35
+ /** The integration's locale key; the default locale uses its language tag. */
36
+ readonly code: string;
37
+ /** BCP 47 language tag. */
38
+ readonly lang: string;
39
+ /** Locale URL path, relative to `site.base`. */
40
+ readonly path: string;
41
+ }
42
+ export interface SiteMetadataLanguages {
43
+ readonly default: string;
44
+ readonly locales: readonly SiteMetadataLocale[];
45
+ }
46
+ /** Site-relative paths, relative to `site.base`. A key is present only when the build produced the file. */
47
+ export interface SiteMetadataDiscovery {
48
+ readonly sitemap?: string;
49
+ readonly robots?: string;
50
+ readonly rss?: string;
51
+ readonly llms?: string;
52
+ }
53
+ /** Whether each provider's loader is emitted in this build. */
54
+ export interface SiteMetadataAnalytics {
55
+ readonly googleAnalytics: boolean;
56
+ readonly fiftyOneLa: boolean;
57
+ readonly posthog: boolean;
58
+ }
59
+ export interface SiteMetadataFeatures {
60
+ readonly seo?: boolean;
61
+ readonly promoto?: boolean;
62
+ }
63
+ export interface SiteMetadata {
64
+ readonly schemaVersion: typeof SITE_METADATA_SCHEMA_VERSION;
65
+ readonly generator: SiteMetadataGenerator;
66
+ readonly site: SiteMetadataSite;
67
+ readonly languages: SiteMetadataLanguages;
68
+ readonly build: BuildInfo;
69
+ readonly discovery: SiteMetadataDiscovery;
70
+ readonly analytics: SiteMetadataAnalytics;
71
+ readonly features: SiteMetadataFeatures;
72
+ }
73
+ export interface BuildSiteMetadataInput {
74
+ generator: SiteMetadataGenerator;
75
+ site: {
76
+ /** Explicit name, the site's own title, or the home page name. Falls back to the URL hostname. */
77
+ name?: string | undefined;
78
+ url: string | URL;
79
+ base?: string | undefined;
80
+ description?: string | undefined;
81
+ };
82
+ /** Locales with paths relative to the base. An empty list yields one locale that is also the default. */
83
+ locales?: readonly SiteMetadataLocale[] | undefined;
84
+ defaultLocale?: string | undefined;
85
+ /** Language tag used for the single-locale fallback. Defaults to `en`. */
86
+ fallbackLang?: string | undefined;
87
+ build: unknown;
88
+ discovery?: SiteMetadataDiscovery | undefined;
89
+ analytics?: Partial<SiteMetadataAnalytics> | undefined;
90
+ features?: SiteMetadataFeatures | undefined;
91
+ }
92
+ export interface SiteMetadataOption {
93
+ readonly enabled: boolean;
94
+ readonly name?: string;
95
+ readonly description?: string;
96
+ }
97
+ /** Build a schema-valid object from typed inputs. Pure and deterministic. */
98
+ export declare function buildSiteMetadata(input: BuildSiteMetadataInput): SiteMetadata;
99
+ /** Problems found in an untrusted value. An empty list means the value follows schema version 1. */
100
+ export declare function validateSiteMetadata(value: unknown): readonly string[];
101
+ /** Canonical minified JSON: fixed key order, no indentation, trailing newline. Identical input gives identical bytes. */
102
+ export declare function serializeSiteMetadata(metadata: SiteMetadata): string;
103
+ /**
104
+ * Detect which analytics loaders the built pages contain. A provider is enabled
105
+ * when any page carries all of its markers. Only booleans leave this function.
106
+ */
107
+ export declare function detectAnalyticsLoaders(pages: Iterable<string>): SiteMetadataAnalytics;
108
+ /**
109
+ * Resolve the `metadata` option shared by the three packages. `undefined` and
110
+ * `true` enable the default output, `false` opts out, and an object may override
111
+ * `name` and `description`. Errors name the option.
112
+ */
113
+ export declare function resolveSiteMetadataOption(value: unknown): SiteMetadataOption;
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Contract for the `.well-known/hagilight.metadata.json` file. Browser-safe and
3
+ * pure: no Node modules. The Node-only writer lives in `site-metadata-writer.ts`.
4
+ *
5
+ * Values are copied field by field from typed inputs, so new input fields can
6
+ * never leak into the output. Analytics appears only as on/off booleans.
7
+ */
8
+ import { normalizeBuildInfo, UNKNOWN } from './build-info.js';
9
+ export const SITE_METADATA_SCHEMA_VERSION = 1;
10
+ /** Site-relative output path. This is the only place the path is spelled. */
11
+ export const SITE_METADATA_PATH = '.well-known/hagilight.metadata.json';
12
+ /**
13
+ * Substrings that a provider's loader leaves in built HTML. Each provider needs
14
+ * every marker in one page. A core test pins these to the shipped loaders, so a
15
+ * loader change fails loudly here.
16
+ */
17
+ export const ANALYTICS_LOADER_MARKERS = {
18
+ googleAnalytics: ['https://www.googletagmanager.com/gtag/js'],
19
+ fiftyOneLa: ['id="LA_COLLECT"', 'https://sdk.51.la/js-sdk-pro.min.js'],
20
+ posthog: ['__hagilightPosthogInitialized'],
21
+ };
22
+ const DISCOVERY_KEYS = ['sitemap', 'robots', 'rss', 'llms'];
23
+ const ANALYTICS_KEYS = ['googleAnalytics', 'fiftyOneLa', 'posthog'];
24
+ const FEATURE_KEYS = ['seo', 'promoto'];
25
+ const TOP_LEVEL_KEYS = ['schemaVersion', 'generator', 'site', 'languages', 'build', 'discovery', 'analytics', 'features'];
26
+ function isRecord(value) {
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ }
29
+ function trimmed(value) {
30
+ if (typeof value !== 'string')
31
+ return undefined;
32
+ const text = value.trim();
33
+ return text || undefined;
34
+ }
35
+ /** Leading and trailing slash, `/` for the root. */
36
+ function normalizeBase(value) {
37
+ const inner = (trimmed(value) ?? '').replace(/^\/+|\/+$/gu, '');
38
+ return inner ? `/${inner}/` : '/';
39
+ }
40
+ function hostnameOf(url) {
41
+ try {
42
+ return new URL(url).hostname;
43
+ }
44
+ catch {
45
+ return UNKNOWN;
46
+ }
47
+ }
48
+ function canonicalLang(value) {
49
+ try {
50
+ return Intl.getCanonicalLocales(value)[0];
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ function pickBooleans(input, keys) {
57
+ const record = isRecord(input) ? input : {};
58
+ return Object.fromEntries(keys.map((key) => [key, record[key] === true]));
59
+ }
60
+ /** Build a schema-valid object from typed inputs. Pure and deterministic. */
61
+ export function buildSiteMetadata(input) {
62
+ const url = new URL(input.site.url).href;
63
+ const base = normalizeBase(input.site.base);
64
+ const description = trimmed(input.site.description);
65
+ const fallbackLang = canonicalLang(input.fallbackLang ?? 'en') ?? 'en';
66
+ const rawLocales = (input.locales ?? []).map((locale) => ({
67
+ code: trimmed(locale.code) ?? fallbackLang,
68
+ lang: canonicalLang(locale.lang) ?? fallbackLang,
69
+ path: normalizeBase(locale.path),
70
+ }));
71
+ const locales = rawLocales.length > 0
72
+ ? rawLocales
73
+ : [{ code: fallbackLang, lang: fallbackLang, path: '/' }];
74
+ const defaultLocale = trimmed(input.defaultLocale);
75
+ const defaultCode = defaultLocale !== undefined && locales.some((locale) => locale.code === defaultLocale)
76
+ ? defaultLocale
77
+ : locales[0].code;
78
+ const discovery = {};
79
+ for (const key of DISCOVERY_KEYS) {
80
+ const value = input.discovery?.[key];
81
+ if (typeof value === 'string' && value.startsWith('/'))
82
+ discovery[key] = value;
83
+ }
84
+ const features = {
85
+ ...(typeof input.features?.seo === 'boolean' ? { seo: input.features.seo } : {}),
86
+ ...(typeof input.features?.promoto === 'boolean' ? { promoto: input.features.promoto } : {}),
87
+ };
88
+ return {
89
+ schemaVersion: SITE_METADATA_SCHEMA_VERSION,
90
+ generator: {
91
+ name: trimmed(input.generator.name) ?? UNKNOWN,
92
+ version: trimmed(input.generator.version) ?? UNKNOWN,
93
+ },
94
+ site: {
95
+ name: trimmed(input.site.name) ?? hostnameOf(url),
96
+ url,
97
+ base,
98
+ ...(description === undefined ? {} : { description }),
99
+ },
100
+ languages: {
101
+ default: defaultCode,
102
+ locales,
103
+ },
104
+ build: normalizeBuildInfo(input.build),
105
+ discovery,
106
+ analytics: pickBooleans(input.analytics, ANALYTICS_KEYS),
107
+ features,
108
+ };
109
+ }
110
+ /** Problems found in an untrusted value. An empty list means the value follows schema version 1. */
111
+ export function validateSiteMetadata(value) {
112
+ const problems = [];
113
+ if (!isRecord(value))
114
+ return ['metadata must be an object'];
115
+ for (const key of Object.keys(value)) {
116
+ if (!TOP_LEVEL_KEYS.includes(key))
117
+ problems.push(`unexpected top-level field "${key}"`);
118
+ }
119
+ if (value.schemaVersion !== SITE_METADATA_SCHEMA_VERSION)
120
+ problems.push('schemaVersion must be 1');
121
+ const generator = isRecord(value.generator) ? value.generator : {};
122
+ for (const key of ['name', 'version']) {
123
+ if (!trimmed(generator[key]))
124
+ problems.push(`generator.${key} must be a non-empty string`);
125
+ }
126
+ const site = isRecord(value.site) ? value.site : {};
127
+ if (!trimmed(site.name))
128
+ problems.push('site.name must be a non-empty string');
129
+ if (typeof site.url !== 'string' || !/^https?:\/\//u.test(site.url))
130
+ problems.push('site.url must be an absolute HTTP(S) URL');
131
+ if (typeof site.base !== 'string' || !/^\/(?:.*\/)?$/u.test(site.base))
132
+ problems.push('site.base must start and end with "/"');
133
+ if (site.description !== undefined && !trimmed(site.description))
134
+ problems.push('site.description must be a non-empty string when present');
135
+ const languages = isRecord(value.languages) ? value.languages : {};
136
+ const locales = Array.isArray(languages.locales) ? languages.locales : [];
137
+ if (locales.length === 0)
138
+ problems.push('languages.locales must be a non-empty array');
139
+ const codes = new Set();
140
+ for (const locale of locales) {
141
+ const entry = isRecord(locale) ? locale : {};
142
+ if (!trimmed(entry.code))
143
+ problems.push('languages.locales[].code must be a non-empty string');
144
+ else
145
+ codes.add(entry.code);
146
+ if (typeof entry.lang !== 'string' || canonicalLang(entry.lang) === undefined)
147
+ problems.push('languages.locales[].lang must be a BCP 47 tag');
148
+ if (typeof entry.path !== 'string' || !/^\/(?:.*\/)?$/u.test(entry.path))
149
+ problems.push('languages.locales[].path must start and end with "/"');
150
+ }
151
+ if (typeof languages.default !== 'string' || (locales.length > 0 && !codes.has(languages.default))) {
152
+ problems.push('languages.default must match one of languages.locales[].code');
153
+ }
154
+ const build = isRecord(value.build) ? value.build : {};
155
+ for (const key of ['branch', 'commit', 'builtAt']) {
156
+ if (!trimmed(build[key]))
157
+ problems.push(`build.${key} must be a non-empty string`);
158
+ }
159
+ const discovery = isRecord(value.discovery) ? value.discovery : {};
160
+ for (const key of Object.keys(discovery)) {
161
+ if (!DISCOVERY_KEYS.includes(key))
162
+ problems.push(`unexpected discovery field "${key}"`);
163
+ else if (typeof discovery[key] !== 'string' || !discovery[key].startsWith('/'))
164
+ problems.push(`discovery.${key} must be a site-relative path`);
165
+ }
166
+ const analytics = isRecord(value.analytics) ? value.analytics : {};
167
+ for (const key of ANALYTICS_KEYS) {
168
+ if (typeof analytics[key] !== 'boolean')
169
+ problems.push(`analytics.${key} must be a boolean`);
170
+ }
171
+ const features = isRecord(value.features) ? value.features : {};
172
+ for (const key of FEATURE_KEYS) {
173
+ if (features[key] !== undefined && typeof features[key] !== 'boolean')
174
+ problems.push(`features.${key} must be a boolean`);
175
+ }
176
+ return problems;
177
+ }
178
+ /** Canonical minified JSON: fixed key order, no indentation, trailing newline. Identical input gives identical bytes. */
179
+ export function serializeSiteMetadata(metadata) {
180
+ const canonical = {
181
+ schemaVersion: metadata.schemaVersion,
182
+ generator: { name: metadata.generator.name, version: metadata.generator.version },
183
+ site: {
184
+ name: metadata.site.name,
185
+ url: metadata.site.url,
186
+ base: metadata.site.base,
187
+ ...(metadata.site.description === undefined ? {} : { description: metadata.site.description }),
188
+ },
189
+ languages: {
190
+ default: metadata.languages.default,
191
+ locales: metadata.languages.locales.map(({ code, lang, path }) => ({ code, lang, path })),
192
+ },
193
+ build: { branch: metadata.build.branch, commit: metadata.build.commit, builtAt: metadata.build.builtAt },
194
+ discovery: Object.fromEntries(DISCOVERY_KEYS
195
+ .filter((key) => metadata.discovery[key] !== undefined)
196
+ .map((key) => [key, metadata.discovery[key]])),
197
+ analytics: {
198
+ googleAnalytics: metadata.analytics.googleAnalytics,
199
+ fiftyOneLa: metadata.analytics.fiftyOneLa,
200
+ posthog: metadata.analytics.posthog,
201
+ },
202
+ features: Object.fromEntries(FEATURE_KEYS
203
+ .filter((key) => metadata.features[key] !== undefined)
204
+ .map((key) => [key, metadata.features[key]])),
205
+ };
206
+ return `${JSON.stringify(canonical)}\n`;
207
+ }
208
+ /**
209
+ * Detect which analytics loaders the built pages contain. A provider is enabled
210
+ * when any page carries all of its markers. Only booleans leave this function.
211
+ */
212
+ export function detectAnalyticsLoaders(pages) {
213
+ const found = { googleAnalytics: false, fiftyOneLa: false, posthog: false };
214
+ for (const html of pages) {
215
+ for (const provider of ANALYTICS_KEYS) {
216
+ if (!found[provider] && ANALYTICS_LOADER_MARKERS[provider].every((marker) => html.includes(marker))) {
217
+ found[provider] = true;
218
+ }
219
+ }
220
+ }
221
+ return found;
222
+ }
223
+ /**
224
+ * Resolve the `metadata` option shared by the three packages. `undefined` and
225
+ * `true` enable the default output, `false` opts out, and an object may override
226
+ * `name` and `description`. Errors name the option.
227
+ */
228
+ export function resolveSiteMetadataOption(value) {
229
+ if (value === undefined || value === true)
230
+ return { enabled: true };
231
+ if (value === false)
232
+ return { enabled: false };
233
+ if (!isRecord(value)) {
234
+ throw new TypeError('Hagilight metadata option must be a boolean or an options object.');
235
+ }
236
+ for (const key of Object.keys(value)) {
237
+ if (!['enabled', 'name', 'description'].includes(key)) {
238
+ throw new TypeError(`Hagilight metadata option has an unknown key "${key}".`);
239
+ }
240
+ }
241
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') {
242
+ throw new TypeError('Hagilight metadata enabled option must be a boolean.');
243
+ }
244
+ for (const key of ['name', 'description']) {
245
+ if (value[key] !== undefined && !trimmed(value[key])) {
246
+ throw new TypeError(`Hagilight metadata ${key} must be a non-empty string.`);
247
+ }
248
+ }
249
+ const name = trimmed(value.name);
250
+ const description = trimmed(value.description);
251
+ return {
252
+ enabled: value.enabled !== false,
253
+ ...(name === undefined ? {} : { name }),
254
+ ...(description === undefined ? {} : { description }),
255
+ };
256
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/hagilight-core",
3
- "version": "0.11.1-dev.129.1.ea757b8",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Shared TypeScript utilities, components, and assets for HagiCode Astro and Starlight sites",
6
6
  "repository": {
@@ -47,6 +47,18 @@
47
47
  "types": "./dist/rss-ownership.d.ts",
48
48
  "default": "./dist/rss-ownership.js"
49
49
  },
50
+ "./site-metadata": {
51
+ "types": "./dist/site-metadata.d.ts",
52
+ "default": "./dist/site-metadata.js"
53
+ },
54
+ "./site-metadata-writer": {
55
+ "types": "./dist/site-metadata-writer.d.ts",
56
+ "default": "./dist/site-metadata-writer.js"
57
+ },
58
+ "./site-metadata-ownership": {
59
+ "types": "./dist/site-metadata-ownership.d.ts",
60
+ "default": "./dist/site-metadata-ownership.js"
61
+ },
50
62
  "./promotions": {
51
63
  "types": "./dist/promotions.d.ts",
52
64
  "default": "./dist/promotions.js"