Reusable Astro components, integrations, a Starlight plugin, and a Docusaurus
plugin for HagiCode sites. This repository publishes five npm packages, all authored in
TypeScript and shipped as ESM with generated .d.ts declarations. Astro
components, Astro route entry points, styles, JSON, and images are shipped in
their native formats.
flowchart LR
A["@hagicode/hagilight"] --> C["@hagicode/hagilight-core"]
S["@hagicode/hagilight-starlight"] --> C
D["@hagicode/hagilight-docusaurus"] --> C
M["@hagicode/hagilight-mermaid"]
Every feature package depends on the matching version of the shared core and never on another feature package. Install core directly when your site imports a core entry point.
| Package | npm | Downloads |
|---|---|---|
@hagicode/hagilight-core |
||
@hagicode/hagilight |
||
@hagicode/hagilight-starlight |
||
@hagicode/hagilight-docusaurus |
||
@hagicode/hagilight-mermaid |
@hagicode/hagilight-mermaid renders with Mermaid by default and can render with the optional Pele engine (engine: 'pele', with pele as an optional peer). Its README covers the engine choice, the stored preference, and which diagram types Pele draws in a simplified way.
Shared building blocks for plain Astro, Starlight, and Docusaurus sites. Its Astro components require astro
>=7; it has no Starlight dependency.
| Import | Provides |
|---|---|
@hagicode/hagilight-core/links |
resolveSiteLinks() and the localized header/footer link catalog types |
@hagicode/hagilight-core/favicon |
resolveFaviconHeadEntry() and getHagilightFaviconDataUri() |
@hagicode/hagilight-core/seo |
Metadata, canonical head composition, and JSON-LD builders |
@hagicode/hagilight-core/seo-schema |
seoSchema for optional seo frontmatter |
@hagicode/hagilight-core/rss |
generateRssFeed() and resolveRssLocales() |
@hagicode/hagilight-core/rss-ownership |
Coordination that keeps one integration as the RSS route owner |
@hagicode/hagilight-core/promotions |
Typed promotion campaign loader |
@hagicode/hagilight-core/promoto-banner |
definePromotoBannerElement(), the promotion banner custom element used by the Docusaurus package |
@hagicode/hagilight-core/posthog |
Browser-safe posthogInitScript() with typed defaults and validated custom keys |
@hagicode/hagilight-core/analytics-events |
Google Analytics click-event tags (gaEventAttributes(), siteLinkGaAttributes()) and the tracked-link table |
@hagicode/hagilight-core/Footer |
Localized footer with generated RSS and sitemap links |
@hagicode/hagilight-core/Copyright, /PromotoBanner, /GoogleAnalytics, /PostHog, /Analytics51LA |
Astro components |
@hagicode/hagilight-core/logo.png, /favicon.ico |
Brand assets. logo.png is only the default icon of RootTransit, replaceable with its logo prop; the Starlight plugin no longer supplies it (see the Starlight README) |
Plain Astro integrations and components (astro >=7):
| Import | Provides |
|---|---|
@hagicode/hagilight/integration |
hagilight() (sitemap, robots.txt, and RSS feeds by default), hagilightFavicon(), and their option types |
@hagicode/hagilight/SEOHead |
Canonical, Open Graph, Twitter, and JSON-LD head entries |
@hagicode/hagilight/Footer |
Shared footer with Powered By hagilight@<version> attribution |
The plain-Astro Footer reads the exact build-time version from its own
@hagicode/hagilight package manifest; it does not report an astro framework
version. Existing sites that import @hagicode/hagilight-core/Footer can keep
that core-only footer (with no feature-package attribution) or switch to
@hagicode/hagilight/Footer to display the Hagilight version.
A Starlight plugin (@astrojs/starlight ^0.42.4, astro ^7.3.5) that adds
the localized header, language chooser, and footer links; content-width toggle;
custom 404 page; end-of-article HagiCode introduction; floating promotion
banner; AI translation or authorship disclosures; SEO metadata and multilingual
page discovery; RSS feeds; Google Analytics, PostHog and 51LA; and the shared favicon.
Its Footer appends Powered By hagilight-starlight@<version> using the exact
build-time version from the @hagicode/hagilight-starlight manifest, not the
Astro or Starlight dependency version.
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import hagilight from '@hagicode/hagilight-starlight';
import { locales } from '@hagicode/hagilight-starlight/locales';
export default defineConfig({
site: 'https://docs.example.test',
integrations: [starlight({ title: 'Docs', locales, plugins: [hagilight({ rss: { includeDocs: false } })] })],
});// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
import { hagilightSchema } from '@hagicode/hagilight-starlight/schema';
export const collections = { docs: defineCollection({ loader: docsLoader(), schema: docsSchema({ extend: hagilightSchema }) }) };HagilightStarlightOptions types every plugin option, so misspelled or
mistyped options fail type-checking in astro.config.ts or JSDoc-checked
configs; the plugin still validates options at runtime. Components such as
@hagicode/hagilight-starlight/Header and /MarkdownContent remain importable
for sites that compose their own Starlight overrides.
A Docusaurus 3 plugin that adds the Hagilight footer, promotion banner, analytics, SEO metadata, and discovery files (sitemap.xml, robots.txt, rss.xml) to a Docusaurus site. It peers on @docusaurus/core and @docusaurus/theme-classic ^3.9.2, depends only on the shared core, and exports the locale catalog from @hagicode/hagilight-docusaurus/locales.
// docusaurus.config.mjs
import { hagilightDocusaurus } from '@hagicode/hagilight-docusaurus';
import { i18n } from '@hagicode/hagilight-docusaurus/locales';
export default {
title: 'My docs',
url: 'https://docs.example.com',
baseUrl: '/',
i18n,
plugins: [
hagilightDocusaurus({
analytics: {
googleAnalytics: { measurementId: 'G-XXXXXXXXXX' },
fiftyOneLa: { enabled: false },
},
}),
],
themeConfig: {
navbar: { items: [{ type: 'localeDropdown' }] },
},
};The built-in analytics IDs belong to HagiCode, so set your own IDs or disable each provider. Every option, its default, and the sitemap, robots.txt, and RSS rules are in the package README. The demo in examples/demo-docusaurus-web is published at https://docusaurus.hagicode.com/.
Starlight's hagilight() and Docusaurus's hagilightDocusaurus() enable PostHog without configuration or a consumer key. The supplied defaults are HagiCode's own PostHog project key, API host https://t.hagicode.com (HagiCode's managed proxy), UI host https://us.posthog.com, person profiles identified_only, and SDK defaults 2026-05-30. It loads asynchronously from https://t.hagicode.com/static/array.js, only in production, once per document. Sites with a strict script or connect policy must allow t.hagicode.com.
For plain Astro, hagilight() from @hagicode/hagilight/integration injects the same loader into the head of every page of a production build, and injects nothing when @astrojs/starlight is registered because the Starlight plugin then owns PostHog. To own the initialization yourself, set analytics: { posthog: { enabled: false } } and compose import PostHog from '@hagicode/hagilight-core/PostHog' and <PostHog /> once in the common layout's <head>, alongside @hagicode/hagilight-core/GoogleAnalytics when configured. Non-Astro consumers use posthogInitScript() from @hagicode/hagilight-core/posthog without requiring Astro.
Hagilight also sends a closed set of interaction events (404 views, Starlight search, code copies, language changes, and the end-of-article promotion impression): see the core README for the events, their properties and the privacy rules. Search text is never sent by default. analytics.posthog.searchQuery: 'zero-results' (Starlight and Docusaurus) allows it for searches with no results only.
All three integrations accept analytics.posthog: { enabled?, apiKey?, searchQuery? }, like Google Analytics: omitted options use the shared default; {} disables the provider; an explicit enabled: true requires a valid key. Use { apiKey: 'phc_Custom123' } for another project or { enabled: false } to opt out independently. The built-in project belongs to HagiCode. SDK defaults own PostHog navigation behavior. Keep one initialization owner; disable the provider if the site supplies PostHog itself. Starlight's generated Head owns SEO, GA and PostHog; preserving a custom Head requires disabling these features and composing them explicitly. See the core, Starlight, and Docusaurus usage.
By default every visitor must accept before Google Analytics, 51LA or PostHog load. A site can let visitors in regions that do not require consent start analytics without a click by setting analytics.consent.regions. Without it the output and behavior are unchanged. The same options, names and defaults are accepted by hagilight() in the Starlight and plain-Astro integrations and by hagilightDocusaurus(), all under analytics.consent:
hagilight({
analytics: {
consent: { regions: 'default', settingsEntry: 'requiredOnly', sessionReplay: 'optIn' },
},
});| Option | Default | Values and errors |
|---|---|---|
regions |
absent (global consent) | 'default' for the default country set, or an array of upper-case ISO 3166-1 alpha-2 codes that replaces the whole set. regions with enabled: false fails configuration. |
countryCode |
none | One upper-case ISO code that overrides detection. Requires regions. |
regionHook |
none | Name of a function the site defines on window, such as siteRegion or site.region. It returns 'required', 'notRequired', 'unknown', a boolean (true required, false not required) or a promise of one of these. Requires regions. |
settingsEntry |
'requiredOnly' |
requiredOnly shows the footer "Cookie settings" entry only to required and unknown visitors; always shows it to everyone. Requires regions. |
sessionReplay |
'optIn' |
optIn: replay stays off in not-required regions until the visitor allows it in the footer. projectDefault: replay follows the PostHog project. off: never replay in not-required regions and no opt-in entry. Requires regions. |
An invalid value, a country code that is not an assigned upper-case ISO code, a regionHook name that is not a valid identifier or dotted path, or a regional-only option (countryCode, regionHook, settingsEntry, sessionReplay) without regions stops the build with an error that names the option.
Default consent-required countries (a product configuration, not a legal determination): EU27 (AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE), EEA (IS LI NO), GB, CH and BR. China, South Korea, India and other regions are not in the set. A visitor from a country outside the set does not require consent.
Resolution order. The decision is made once per page and shared by the popup, the footer and the analytics gate:
- The explicit
countryCode. - The
regionHook. - The same-origin
/cdn-cgi/traceendpoint, with a 1200 ms timeout. Only itslocline is read. The IP address is never read, stored or sent, and no request goes to a third-party host. - A coarse fallback from the browser's
Intltime zone.Europe/*, Iceland, EU/EEA territories, Cyprus, Brazil and the French outermost regions require consent; otherAmerica/*,Asia/*,Australia/*andPacific/*zones do not;UTC,Etc/*, otherAfrica/*andIndian/*zones,Antarctica/*, and empty or unreadable values are unknown. - Otherwise
unknown.
The whole decision has a 1800 ms deadline. If nothing has answered by then the result is required, and a later answer does not change it.
Fail-closed. unknown, a hook that throws, rejects, never settles or returns an unrecognized value, a timeout, an invalid countryCode and an uncertain time zone all require consent: the popup appears and no provider loads until the visitor accepts. An explicit granted or denied record is honored in every region, and a visitor with a valid record does not wait for the decision.
Cloudflare dependency. /cdn-cgi/trace answers only for hostnames proxied through Cloudflare. It was verified on the docs, design and omniroute hagicode.com subdomains. www.hagicode.com returned no loc, so on www the time-zone fallback decides, unless the site sets countryCode or regionHook for exact behavior.
Consent records and Consent Mode. A visitor whose analytics start because of a not-required decision gets no consent record, and getConsent() still reports undecided. The hagicode_consent cookie, the hagicode:consent key, their format and their 180-day lifetime are unchanged, and an explicit denied record blocks analytics in every region. Google Consent Mode and cookieless pings stay off, and no gtag consent default is added.
Session replay opt-in. In a not-required region with sessionReplay: 'optIn', PostHog session replay is held off even when the PostHog project enables it. The footer then offers "Allow session replay". Allowing it stores a normal granted record and starts replay on the current page, and replay follows the PostHog project setting on later visits. "Not now" stores nothing. The replay hold was verified with the real PostHog SDK in headless Chromium (test/fixtures/posthog-replay-facts.json).
Measurement discontinuity. For a site that enables regional mode, GA4 and PostHog collection expands again after deployment. Data from then on is a second discontinuity and is not directly comparable with data collected since 2026-10-29. Operators must annotate the deployment date in GA4. The monorepo's docs/google-analytics-integration-reference.md has the full rules.
Metadata. When consent is on, .well-known/hagilight.metadata.json reports features.consentMode as globalRequired (every visitor requires consent) or regional (the site sets regions). It never contains the country list or the hook name.
Legal notice: This feature is product configuration and is not legal advice. The default country set, the inclusion of Brazil and the default hiding of "Cookie settings" for not-required visitors need confirmation by legal counsel. Site privacy notices may need matching updates; this project does not provide their wording. The monorepo reference
docs/google-analytics-integration-reference.md(section 3.2) has the full rules.
Shared links classify each destination as same-origin, first-party (hagicode.com and its subdomains, plus github.com/HagiCode-org), or third-party. First-party and same-origin new-tab links use rel="noopener"; third-party links keep rel="noopener noreferrer". Setting links.siteId adds utm_source=<siteId>&utm_medium=footer (or promoto for the banner) to first-party hagicode.com footer and banner destinations, after deduplication and never on GitHub, third-party, or same-origin links. The Google Analytics cross-domain linker is not configured, because every first-party host that runs the shared gtag shares the hagicode.com cookie domain. The full rules, options and the linker decision are in the core package README.
GoogleAnalytics (included by the Starlight plugin) reports clicks on key links and download buttons as GA4 events, with no configuration. Events are sent only on production pages where Google Analytics is enabled, never on the 404 page, and are skipped when gtag is missing.
- Event name (action):
download_clickfor thedownloadcategory,store_visitforstore, andlink_clickfornavigation,community, andpromotion. - Categories: use
downloadfor installers and download-hub entry points, andstorefor store listing pages (Microsoft Store, Steam). A single click reports under one category only. - Parameters:
event_category,event_label(the link's stable id, not its localized text),link_location(header,footer,footer_brand,article_promotion,promoto_banner, or your own value),link_url, andtransport_type: 'beacon'. No link text, form values, or visitor identifiers are sent. - Tracked links: header
home,blog,support; footerdownloadClient(download),microsoftStore(store),dockerCompose,productDocs,blogPosts(navigation),github,discord,issueFeedback(community); the HagiCode showcase calls to action, Microsoft Store badge (store, and its fallback link), and all-downloads link (download); and the floating promotion banner call to action, labelled with the promotion id.TRACKED_SITE_LINKSinpackages/core/src/analytics-events.tsis authoritative; renaming a link id changes its GA label. Related sites, RSS, sitemap, about, contact, filings, andextraLinksare not tracked. - Your own links: spread
gaEventAttributes({ category, label, location })from@hagicode/hagilight-core/analytics-eventsonto an anchor. Usecategory: 'store'for a store listing andcategory: 'download'for an installer. Unknown categories (including action names such asstore_visit) throw at build time and are ignored at click time. - Reports: register
event_category,event_label,link_location, andlink_urlas GA4 custom dimensions to see them in standard reports.
See the core package README for the full contract.
@hagicode/hagilight-core ships agent skills for building a site with hagilight. After you install it, they are in node_modules/@hagicode/hagilight-core/skills/:
hagilight/SKILL.mdis the entry point and routes to the guides below.hagilight-site-from-scratch/SKILL.mdcovers the shared start for an empty project.hagilight-docs-site/SKILL.mdcovers documentation sites on Starlight or Docusaurus.hagilight-official-website/SKILL.mdcovers official websites on plain Astro.
Not every agent discovers skills under node_modules. Point your agent at the entry skill, for example by asking it to read node_modules/@hagicode/hagilight-core/skills/hagilight/SKILL.md before it sets up a site.
Every JavaScript entry point has a types export condition, so TypeScript
resolves declarations with moduleResolution NodeNext, Node16, or
Bundler without application-level module declarations. For example, type the
module passed to hagilight({ rss: { getFeed } }):
// src/rss-feed.ts
import type { RssFeedCallback } from '@hagicode/hagilight/integration';
const getFeed: RssFeedCallback = async ({ lang }) => ({
title: 'Updates',
description: `Updates in ${lang}`,
items: [{ title: 'Release notes', link: '/blog/release/', date: new Date() }],
});
export default getFeed;Register the plain-Astro integration in astro.config.mjs (importing a component alone
cannot register an Astro integration):
import { defineConfig } from 'astro/config';
import { hagilight } from '@hagicode/hagilight/integration';
export default defineConfig({
site: 'https://example.test',
integrations: [hagilight()],
});With an absolute HTTP(S) site, Astro's sitemap integration generates
sitemap-index.xml and Hagilight generates robots.txt with an absolute
Sitemap: URL to that index. For base: '/manual/', verify
https://example.test/manual/sitemap-index.xml and the sitemap entries under
https://example.test/manual/; the localized Footer sitemap link uses that
same base-aware path. Set hagilight({ enabled: false }) to disable both
generated outputs. An existing @astrojs/sitemap integration or Starlight owns
sitemap generation instead; a consumer-owned public/robots.txt or
src/pages/robots.txt.* remains authoritative.
If you need a site-specific crawl policy, own public/robots.txt and include
the absolute URL of the deployed sitemap index:
User-agent: *
Allow: /
Disallow: /private/
Sitemap: https://example.test/manual/sitemap-index.xml
Hagilight does not generate llms.txt. To publish AI discovery links, add your
own public/llms.txt with only the localized pages you want to expose:
# Example documentation
- [English](https://example.test/manual/)
- [简体中文](https://example.test/manual/zh-CN/)
If you do not want AI discovery, do not add an llms.txt file. Deployments
under a base path must still serve /robots.txt at the origin root, because
crawlers look for that exact URL.
hagilight() from @hagicode/hagilight/integration generates localized RSS feeds
by default, so integrating it is enough to publish /rss.xml and
/rss.<language>.xml. Sites can keep owning RSS routes and call
generateRssFeed from @hagicode/hagilight-core/rss, or customize the generated
feeds with the rss option:
import { defineConfig } from 'astro/config';
import { hagilight } from '@hagicode/hagilight/integration';
export default defineConfig({
site: 'https://example.test',
integrations: [
hagilight({
rss: { getFeed: './src/rss-feed.ts' },
}),
],
});When rss is omitted (the default) or rss: true, the integration derives the
feed locales from the Astro i18n config and serves a built-in empty feed.
Pass rss: false to disable RSS entirely. The getFeed path is resolved
relative to the Astro project root. Its module must default-export an
RssFeedCallback that receives { route, lang } for each configured locale and
returns { title, description, items }. Items use the same title, link,
optional description, and optional date/pubDate shape accepted by
generateRssFeed. The integration requires an absolute HTTP(S) site URL and a
valid callback module and result when getFeed is supplied.
The integration prerenders /rss.xml, /rss.en.xml, and
/rss.<language>.xml for each configured non-English language. /rss.xml and
/rss.en.xml use the configured English callback result. If no English locale
is configured, both are valid empty English feeds; Hagilight does not invoke a
different language's callback or borrow its content. A generated filename
conflicting with a page or public file fails the build rather than replacing
consumer-owned output. Setting rss: false leaves route and Footer behavior
unchanged.
Generated route and item URLs honor Astro's base, for example
base: '/manual/' generates /manual/rss.xml and resolves relative item links
under https://example.test/manual/. The core Footer gets the default feed
link and, on configured non-English pages, a current-language link from
request-local integration context. Explicit links.rssFeedUrl,
links.rssLocaleFeedUrl, link overrides, and existing removal options remain
authoritative.
When both Hagilight integrations are active, Starlight remains the sole RSS
owner if its RSS generation is enabled; the plain-Astro hagilight() then adds
neither routes nor Footer URLs. Both packages coordinate through
@hagicode/hagilight-core/rss-ownership. Having both packages installed does not enable
either integration. If the Starlight integration is present with RSS explicitly
disabled, the plain-Astro hagilight() owns the RSS routes instead.