doccupine 0.0.127 → 0.0.129

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
@@ -148,7 +148,7 @@ Place these JSON files in your project root (where you run `doccupine`). They ar
148
148
 
149
149
  | File | Purpose |
150
150
  | ----------------- | --------------------------------------------------------------------------------------------------------- |
151
- | `doccupine.json` | CLI config (watchDir, outputDir, port). Auto-generated on first run. |
151
+ | `doccupine.json` | CLI config (watchDir, outputDir, port). Auto-generated on first run. Paths are stored relative to the project root, so the file is safe to commit. |
152
152
  | `config.json` | Site metadata: `name`, `description`, `icon`, `image`, `url` (public site URL for sitemap/robots) |
153
153
  | `theme.json` | Theme overrides for [cherry-styled-components](https://github.com/cherry-design-system/styled-components) |
154
154
  | `navigation.json` | Manual navigation structure (overrides auto-generated) |
package/dist/index.d.ts CHANGED
@@ -1,2 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  export { generateSlug, getFullSlug, escapeTemplateContent, } from "./lib/utils.js";
3
+ /**
4
+ * True when this file is what node was asked to run, rather than a module some
5
+ * other process imported. The test suite imports this file for its exported
6
+ * helpers; without this guard, that import parses argv, falls through to the
7
+ * default `watch` command, and prompts for config / starts file watchers.
8
+ *
9
+ * Compares realpaths because npm installs the bin as a symlink
10
+ * (`node_modules/.bin/doccupine` -> `dist/index.js`), so `process.argv[1]` and
11
+ * `import.meta.url` can name the same file by different paths.
12
+ */
13
+ export declare function isProcessEntrypoint(entry?: string | undefined, self?: string): boolean;
package/dist/index.js CHANGED
@@ -1250,6 +1250,8 @@ program
1250
1250
  port: options.port,
1251
1251
  });
1252
1252
  const generator = new MDXToNextJSGenerator(config.watchDir, config.outputDir);
1253
+ // Config paths are project-relative; child processes get an absolute cwd.
1254
+ const outputDir = path.resolve(process.cwd(), config.outputDir);
1253
1255
  await generator.init();
1254
1256
  let devServer = null;
1255
1257
  console.log(chalk.blue("📦 Installing dependencies..."));
@@ -1260,7 +1262,7 @@ program
1260
1262
  const packageManager = resolvePackageManager(options.packageManager ?? config.packageManager);
1261
1263
  console.log(chalk.blue(`📦 Using ${packageManager.name}...`));
1262
1264
  const install = spawn(packageManager.bin, ["install"], {
1263
- cwd: config.outputDir,
1265
+ cwd: outputDir,
1264
1266
  stdio: "inherit",
1265
1267
  });
1266
1268
  await new Promise((resolve, reject) => {
@@ -1285,7 +1287,7 @@ program
1285
1287
  ? ["run", "dev", "--", "--port", portStr]
1286
1288
  : ["run", "dev", "--port", portStr];
1287
1289
  devServer = spawn(packageManager.bin, devArgs, {
1288
- cwd: config.outputDir,
1290
+ cwd: outputDir,
1289
1291
  stdio: ["ignore", "pipe", "pipe"],
1290
1292
  });
1291
1293
  devServer.stdout?.on("data", (data) => {
@@ -1370,4 +1372,29 @@ program
1370
1372
  console.log(chalk.blue("Use --show to display configuration or --reset to reset it"));
1371
1373
  }
1372
1374
  });
1373
- program.parse();
1375
+ /**
1376
+ * True when this file is what node was asked to run, rather than a module some
1377
+ * other process imported. The test suite imports this file for its exported
1378
+ * helpers; without this guard, that import parses argv, falls through to the
1379
+ * default `watch` command, and prompts for config / starts file watchers.
1380
+ *
1381
+ * Compares realpaths because npm installs the bin as a symlink
1382
+ * (`node_modules/.bin/doccupine` -> `dist/index.js`), so `process.argv[1]` and
1383
+ * `import.meta.url` can name the same file by different paths.
1384
+ */
1385
+ export function isProcessEntrypoint(entry = process.argv[1], self = __filename) {
1386
+ if (!entry)
1387
+ return false;
1388
+ // Windows paths are case-insensitive; a false negative here would make the
1389
+ // CLI exit silently without running any command.
1390
+ const normalize = (filePath) => process.platform === "win32" ? filePath.toLowerCase() : filePath;
1391
+ try {
1392
+ return (normalize(fs.realpathSync(entry)) === normalize(fs.realpathSync(self)));
1393
+ }
1394
+ catch {
1395
+ return false;
1396
+ }
1397
+ }
1398
+ if (isProcessEntrypoint()) {
1399
+ program.parse();
1400
+ }
@@ -1,4 +1,22 @@
1
1
  import type { DoccupineConfig } from "./types.js";
2
+ /**
3
+ * Rewrites a path as project-relative so `doccupine.json` stays portable
4
+ * across machines, CI and containers (an absolute `/Users/you/...` breaks for
5
+ * every other contributor and leaks the local directory layout).
6
+ *
7
+ * Paths outside the project root have no portable form, so they are kept
8
+ * absolute - reads go through `path.resolve()`, which accepts both.
9
+ */
10
+ export declare function toProjectRelativePath(targetPath: string, rootDir?: string): string;
11
+ /**
12
+ * Migrates configs written by older versions, which stored absolute paths.
13
+ * Returns the normalized config plus whether anything actually changed, so
14
+ * callers only rewrite the file when needed.
15
+ */
16
+ export declare function normalizeConfigPaths(config: DoccupineConfig, rootDir?: string): {
17
+ config: DoccupineConfig;
18
+ changed: boolean;
19
+ };
2
20
  export declare class ConfigManager {
3
21
  private configPath;
4
22
  constructor(configPath?: string);
@@ -2,6 +2,46 @@ import fs from "fs-extra";
2
2
  import path from "path";
3
3
  import chalk from "chalk";
4
4
  import prompts from "prompts";
5
+ /**
6
+ * Rewrites a path as project-relative so `doccupine.json` stays portable
7
+ * across machines, CI and containers (an absolute `/Users/you/...` breaks for
8
+ * every other contributor and leaks the local directory layout).
9
+ *
10
+ * Paths outside the project root have no portable form, so they are kept
11
+ * absolute - reads go through `path.resolve()`, which accepts both.
12
+ */
13
+ export function toProjectRelativePath(targetPath, rootDir = process.cwd()) {
14
+ // A hand-edited config can hold anything; leave junk untouched rather than
15
+ // throwing inside path.*.
16
+ if (typeof targetPath !== "string" || !targetPath)
17
+ return targetPath;
18
+ if (!path.isAbsolute(targetPath))
19
+ return targetPath;
20
+ const relativePath = path.relative(rootDir, targetPath);
21
+ // Empty means the path *is* the root; ".." or an absolute result (Windows
22
+ // cross-drive) means it escapes the root - neither is portable.
23
+ if (!relativePath)
24
+ return ".";
25
+ if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`)) {
26
+ return targetPath;
27
+ }
28
+ if (path.isAbsolute(relativePath))
29
+ return targetPath;
30
+ // Always store POSIX separators so a config written on Windows still
31
+ // resolves on macOS/Linux.
32
+ return relativePath.split(path.sep).join("/");
33
+ }
34
+ /**
35
+ * Migrates configs written by older versions, which stored absolute paths.
36
+ * Returns the normalized config plus whether anything actually changed, so
37
+ * callers only rewrite the file when needed.
38
+ */
39
+ export function normalizeConfigPaths(config, rootDir = process.cwd()) {
40
+ const watchDir = toProjectRelativePath(config.watchDir, rootDir);
41
+ const outputDir = toProjectRelativePath(config.outputDir, rootDir);
42
+ const changed = watchDir !== config.watchDir || outputDir !== config.outputDir;
43
+ return { config: { ...config, watchDir, outputDir }, changed };
44
+ }
5
45
  export class ConfigManager {
6
46
  configPath;
7
47
  constructor(configPath = "doccupine.json") {
@@ -23,7 +63,7 @@ export class ConfigManager {
23
63
  }
24
64
  async saveConfig(config) {
25
65
  try {
26
- await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), "utf8");
66
+ await fs.writeFile(this.configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
27
67
  console.log(chalk.green("💾 Configuration saved to doccupine.json"));
28
68
  }
29
69
  catch (error) {
@@ -50,24 +90,40 @@ export class ConfigManager {
50
90
  console.log(chalk.yellow("\n⚠️ Setup cancelled."));
51
91
  process.exit(0);
52
92
  }
93
+ // Resolve first so "./docs" and "docs/" collapse to the same value, then
94
+ // store project-relative for portability.
53
95
  return {
54
- watchDir: path.resolve(process.cwd(), watchDir),
55
- outputDir: path.resolve(process.cwd(), outputDir),
96
+ watchDir: toProjectRelativePath(path.resolve(process.cwd(), watchDir)),
97
+ outputDir: toProjectRelativePath(path.resolve(process.cwd(), outputDir)),
56
98
  port: existingConfig?.port || "3000",
57
99
  };
58
100
  }
59
101
  async getConfig(options = {}) {
60
102
  let config = null;
103
+ let dirty = false;
61
104
  if (!options.reset) {
62
105
  config = await this.loadConfig();
63
106
  }
64
107
  if (!config || options.reset) {
65
108
  console.log(chalk.blue("🔧 Setting up Doccupine configuration..."));
66
109
  config = await this.promptForConfig(config || {});
67
- await this.saveConfig(config);
110
+ dirty = true;
111
+ }
112
+ else {
113
+ // Configs written before 0.0.129 stored absolute paths; rewrite them in
114
+ // place so the file can be committed and shared.
115
+ const normalized = normalizeConfigPaths(config);
116
+ if (normalized.changed) {
117
+ config = normalized.config;
118
+ dirty = true;
119
+ console.log(chalk.blue("🔁 Rewriting doccupine.json paths as project-relative"));
120
+ }
68
121
  }
69
122
  if (options.port) {
70
123
  config.port = options.port;
124
+ dirty = true;
125
+ }
126
+ if (dirty) {
71
127
  await this.saveConfig(config);
72
128
  }
73
129
  return config;
@@ -1 +1 @@
1
- export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (initRef.current || !posthogKey) return;\n initRef.current = true;\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host: analyticsConfig.posthog?.host || \"https://us.posthog.com\",\n capture_pageview: false,\n capture_pageleave: true,\n loaded: onReady,\n });\n }, [onReady]);\n\n return null;\n}\n\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n\n useEffect(() => {\n if (pathname) {\n const url = searchParams?.size\n ? `${pathname}?${searchParams.toString()}`\n : pathname;\n posthog.capture(\"$pageview\", { $current_url: url });\n }\n }, [pathname, searchParams]);\n\n return null;\n}\n\nexport function PostHogSetup() {\n const [ready, setReady] = useState(false);\n\n if (!posthogKey) {\n return null;\n }\n\n return (\n <>\n <PostHogInit onReady={() => setReady(true)} />\n <Suspense fallback={null}>{ready && <PostHogPageviewTracker />}</Suspense>\n </>\n );\n}\n";
1
+ export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\n// `host` is the *ingestion* endpoint (us.i.posthog.com); `ui_host` wants the\n// dashboard it belongs to (us.posthog.com), which is what \"view in PostHog\"\n// links and the toolbar point at. Self-hosted instances serve both from one\n// origin, so leaving those untouched is correct.\nconst uiHost = (analyticsConfig.posthog?.host || \"https://us.i.posthog.com\")\n .replace(\".i.posthog.com\", \".posthog.com\");\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (initRef.current || !posthogKey) return;\n initRef.current = true;\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host: uiHost,\n capture_pageview: false,\n capture_pageleave: true,\n loaded: onReady,\n });\n }, [onReady]);\n\n return null;\n}\n\n/**\n * Captures soft navigations only.\n *\n * The document load that got the reader here was already captured in the\n * middleware (see proxy.ts), so counting it again here is what produced two\n * `$pageview` events per page load. Server owns document loads, client owns\n * soft navigations: disjoint, so neither double-counts nor leaves a gap.\n */\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n return;\n }\n if (pathname) {\n const url = searchParams?.size\n ? `${pathname}?${searchParams.toString()}`\n : pathname;\n posthog.capture(\"$pageview\", { $current_url: url });\n }\n }, [pathname, searchParams]);\n\n return null;\n}\n\nexport function PostHogSetup() {\n const [ready, setReady] = useState(false);\n\n if (!posthogKey) {\n return null;\n }\n\n return (\n <>\n <PostHogInit onReady={() => setReady(true)} />\n <Suspense fallback={null}>{ready && <PostHogPageviewTracker />}</Suspense>\n </>\n );\n}\n";
@@ -18,6 +18,13 @@ const analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;
18
18
  const posthogKey =
19
19
  analyticsConfig?.provider === "posthog" ? analyticsConfig.posthog?.key : null;
20
20
 
21
+ // \`host\` is the *ingestion* endpoint (us.i.posthog.com); \`ui_host\` wants the
22
+ // dashboard it belongs to (us.posthog.com), which is what "view in PostHog"
23
+ // links and the toolbar point at. Self-hosted instances serve both from one
24
+ // origin, so leaving those untouched is correct.
25
+ const uiHost = (analyticsConfig.posthog?.host || "https://us.i.posthog.com")
26
+ .replace(".i.posthog.com", ".posthog.com");
27
+
21
28
  function PostHogInit({ onReady }: { onReady: () => void }) {
22
29
  const initRef = useRef(false);
23
30
 
@@ -27,7 +34,7 @@ function PostHogInit({ onReady }: { onReady: () => void }) {
27
34
 
28
35
  posthog.init(posthogKey, {
29
36
  api_host: "/ingest",
30
- ui_host: analyticsConfig.posthog?.host || "https://us.posthog.com",
37
+ ui_host: uiHost,
31
38
  capture_pageview: false,
32
39
  capture_pageleave: true,
33
40
  loaded: onReady,
@@ -37,11 +44,24 @@ function PostHogInit({ onReady }: { onReady: () => void }) {
37
44
  return null;
38
45
  }
39
46
 
47
+ /**
48
+ * Captures soft navigations only.
49
+ *
50
+ * The document load that got the reader here was already captured in the
51
+ * middleware (see proxy.ts), so counting it again here is what produced two
52
+ * \`$pageview\` events per page load. Server owns document loads, client owns
53
+ * soft navigations: disjoint, so neither double-counts nor leaves a gap.
54
+ */
40
55
  function PostHogPageviewTracker() {
41
56
  const pathname = usePathname();
42
57
  const searchParams = useSearchParams();
58
+ const isFirstRun = useRef(true);
43
59
 
44
60
  useEffect(() => {
61
+ if (isFirstRun.current) {
62
+ isFirstRun.current = false;
63
+ return;
64
+ }
45
65
  if (pathname) {
46
66
  const url = searchParams?.size
47
67
  ? \`\${pathname}?\${searchParams.toString()}\`
@@ -1 +1 @@
1
- export declare const analyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Add PostHog analytics to your documentation site with an analytics.json file for both client-side and server-side tracking.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 3\norder: 10\n---\n# Analytics\n\nTrack how users interact with your documentation using PostHog. Doccupine supports both client-side and server-side tracking out of the box, with a privacy-first proxy that routes analytics through your own domain.\n\n## analytics.json\n\nPlace an `analytics.json` at your project root (the same directory where you execute `npx doccupine`).\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\n## Fields\n\n- **provider**: The analytics provider to use. Currently only `\"posthog\"` is supported.\n- **posthog.key**: Your PostHog project API key. You can find this in your PostHog project settings under \"Project API Key\". This is a public identifier - it is safe to commit to version control.\n- **posthog.host**: The PostHog ingestion endpoint. Use `https://us.i.posthog.com` for US Cloud or `https://eu.i.posthog.com` for EU Cloud. If you self-host PostHog, use your instance URL.\n\n<Callout type=\"note\">\n The PostHog project API key is a public identifier used to send events. It is not a secret and is safe to include in your repository.\n</Callout>\n\n## What gets tracked\n\nWhen `analytics.json` is configured, Doccupine enables two layers of tracking:\n\n### Client-side\n\n- **Page views**: Captured on every client-side navigation using Next.js router hooks.\n- **Page leave**: Automatically captured when a user navigates away from a page.\n\n### Server-side\n\n- **Page views**: Captured in middleware on every page request, including the initial server render.\n- **Request metadata**: URL, pathname, host, referrer, and user agent are sent with each event.\n- **Smart filtering**: API routes, internal Next.js routes, and prefetch requests are automatically excluded.\n\n## Privacy proxy\n\nDoccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\nThis means:\n\n- No third-party domains appear in network requests.\n- Ad blockers are less likely to interfere with tracking.\n- Your users' browsing data stays within your domain boundary before reaching PostHog.\n\nThe proxy destinations are derived automatically from the `host` field in your configuration.\n\n## Getting a PostHog key\n\n1. Sign up at [posthog.com](https://posthog.com) (free tier available).\n2. Create a new project.\n3. Go to **Project Settings** and copy the **Project API Key**.\n4. Paste it into your `analytics.json` as the `posthog.key` value.\n\n## Behavior\n\n- **Placement**: Put `analytics.json` in the project root alongside `config.json` and `theme.json`.\n- **Hot reload**: Changes to `analytics.json` are picked up automatically in watch mode. The layout, middleware, and Next.js config are regenerated.\n- **Graceful degradation**: If `analytics.json` is missing, empty, or has an invalid configuration, no tracking code runs. Your site works exactly the same without it.\n- **Dev server restart**: After adding or removing `analytics.json` for the first time, you may need to restart the Next.js dev server for proxy rewrites to take effect.\n\n<Callout type=\"warning\">\n After adding `analytics.json` for the first time, restart the dev server so the proxy rewrites are picked up by Next.js.\n</Callout>\n\n## Regions\n\nPostHog offers two cloud regions. Set the `host` field accordingly:\n\n| Region | Host |\n| -------- | -------------------------- |\n| US Cloud | `https://us.i.posthog.com` |\n| EU Cloud | `https://eu.i.posthog.com` |\n\nIf you omit the `host` field, it defaults to the US Cloud endpoint.\n\n## Example\n\n### Minimal configuration (US Cloud)\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\"\n }\n}\n```\n\n### EU Cloud\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://eu.i.posthog.com\"\n }\n}\n```\n\n## Tips\n\n- **Start simple**: Add the config with just your key and verify events appear in your PostHog dashboard before customizing further.\n- **Check your dashboard**: After deploying, visit your PostHog project to confirm page view events are flowing in.\n- **Production only**: Consider adding `analytics.json` only in your production/deployment setup to avoid tracking local development traffic.";
1
+ export declare const analyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Add PostHog analytics to your documentation site with an analytics.json file for both client-side and server-side tracking.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 3\norder: 10\n---\n# Analytics\n\nTrack how users interact with your documentation using PostHog. Doccupine captures page views in two layers out of the box - in the browser and on the server - so readers running ad blockers are still counted. Browser traffic is proxied through your own domain rather than going to PostHog directly.\n\n## analytics.json\n\nPlace an `analytics.json` at your project root (the same directory where you execute `npx doccupine`).\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\n## Fields\n\n- **provider**: The analytics provider to use. Currently only `\"posthog\"` is supported.\n- **posthog.key**: Your PostHog project API key. You can find this in your PostHog project settings under \"Project API Key\". This is a public identifier - it is safe to commit to version control.\n- **posthog.host**: The PostHog ingestion endpoint. Use `https://us.i.posthog.com` for US Cloud or `https://eu.i.posthog.com` for EU Cloud. If you self-host PostHog, use your instance URL.\n\n<Callout type=\"note\">\n The PostHog project API key is a public identifier used to send events. It is not a secret and is safe to include in your repository.\n</Callout>\n\n## What gets tracked\n\nWhen `analytics.json` is configured, Doccupine enables two layers of tracking:\n\n### Client-side\n\n- **Page views**: Captured on client-side (soft) navigations using Next.js router hooks. The initial page load is counted by the server instead, so one view is never counted twice.\n- **Page leave**: Automatically captured when a user navigates away from a page.\n\n### Server-side\n\n- **Page views**: Captured in middleware on document requests - the initial load of a page. Requests behind client-side navigations carry an `RSC` header and are skipped, because the browser already counts those.\n- **Request metadata**: URL, pathname, host, referrer, and user agent are sent with each event.\n- **Smart filtering**: API routes, internal Next.js routes, and prefetch requests are automatically excluded.\n- **Ad-blocked readers**: because this half runs on your server, readers who block PostHog in the browser are still counted.\n\n## Privacy proxy\n\nDoccupine routes **browser** analytics traffic through your documentation domain using Next.js rewrites. Instead of the browser talking to PostHog directly (which ad blockers intercept), requests go through `/ingest` on your own domain and are proxied on.\n\nThis means:\n\n- No third-party domains appear in the browser's network requests.\n- Ad blockers are less likely to interfere with tracking.\n- Your users' browsing data stays within your domain boundary before reaching PostHog.\n\nThe proxy destinations are derived automatically from the `host` field in your configuration.\n\n<Callout type=\"warning\">\n The proxy covers browser traffic only. Server-side page views are sent from\n your server straight to PostHog - that is exactly what lets them survive an\n ad blocker.\n</Callout>\n\n## Cookies\n\nAn analytics-enabled site sets two first-party cookies:\n\n- `ph_<key>_posthog` - set by posthog-js, holding its anonymous distinct id and session.\n- `dcp_anon_id` - httpOnly, one year, set by the server so an ad-blocked reader (who never receives the posthog-js cookie) counts as one person instead of a new person on every request.\n\nBoth hold nothing but a random identifier. Whether they require a consent notice\nunder GDPR/ePrivacy depends on your jurisdiction and what you do with the data;\nthat call is yours.\n\n## Getting a PostHog key\n\n1. Sign up at [posthog.com](https://posthog.com) (free tier available).\n2. Create a new project.\n3. Go to **Project Settings** and copy the **Project API Key**.\n4. Paste it into your `analytics.json` as the `posthog.key` value.\n\n## Behavior\n\n- **Placement**: Put `analytics.json` in the project root alongside `config.json` and `theme.json`.\n- **Hot reload**: Changes to `analytics.json` are picked up automatically in watch mode. The layout, middleware, and Next.js config are regenerated.\n- **Graceful degradation**: If `analytics.json` is missing, empty, or has an invalid configuration, no tracking code runs. Your site works exactly the same without it.\n- **Dev server restart**: After adding or removing `analytics.json` for the first time, you may need to restart the Next.js dev server for proxy rewrites to take effect.\n\n<Callout type=\"warning\">\n After adding `analytics.json` for the first time, restart the dev server so the proxy rewrites are picked up by Next.js.\n</Callout>\n\n## Regions\n\nPostHog offers two cloud regions. Set the `host` field accordingly:\n\n| Region | Host |\n| -------- | -------------------------- |\n| US Cloud | `https://us.i.posthog.com` |\n| EU Cloud | `https://eu.i.posthog.com` |\n\nIf you omit the `host` field, it defaults to the US Cloud endpoint.\n\n## Example\n\n### Minimal configuration (US Cloud)\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\"\n }\n}\n```\n\n### EU Cloud\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://eu.i.posthog.com\"\n }\n}\n```\n\n## Tips\n\n- **Start simple**: Add the config with just your key and verify events appear in your PostHog dashboard before customizing further.\n- **Check your dashboard**: After deploying, visit your PostHog project to confirm page view events are flowing in.\n- **Production only**: Consider adding `analytics.json` only in your production/deployment setup to avoid tracking local development traffic.";
@@ -8,7 +8,7 @@ order: 10
8
8
  ---
9
9
  # Analytics
10
10
 
11
- Track how users interact with your documentation using PostHog. Doccupine supports both client-side and server-side tracking out of the box, with a privacy-first proxy that routes analytics through your own domain.
11
+ Track how users interact with your documentation using PostHog. Doccupine captures page views in two layers out of the box - in the browser and on the server - so readers running ad blockers are still counted. Browser traffic is proxied through your own domain rather than going to PostHog directly.
12
12
 
13
13
  ## analytics.json
14
14
 
@@ -40,27 +40,45 @@ When \`analytics.json\` is configured, Doccupine enables two layers of tracking:
40
40
 
41
41
  ### Client-side
42
42
 
43
- - **Page views**: Captured on every client-side navigation using Next.js router hooks.
43
+ - **Page views**: Captured on client-side (soft) navigations using Next.js router hooks. The initial page load is counted by the server instead, so one view is never counted twice.
44
44
  - **Page leave**: Automatically captured when a user navigates away from a page.
45
45
 
46
46
  ### Server-side
47
47
 
48
- - **Page views**: Captured in middleware on every page request, including the initial server render.
48
+ - **Page views**: Captured in middleware on document requests - the initial load of a page. Requests behind client-side navigations carry an \`RSC\` header and are skipped, because the browser already counts those.
49
49
  - **Request metadata**: URL, pathname, host, referrer, and user agent are sent with each event.
50
50
  - **Smart filtering**: API routes, internal Next.js routes, and prefetch requests are automatically excluded.
51
+ - **Ad-blocked readers**: because this half runs on your server, readers who block PostHog in the browser are still counted.
51
52
 
52
53
  ## Privacy proxy
53
54
 
54
- Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through \`/ingest\` on your own domain and are proxied to PostHog.
55
+ Doccupine routes **browser** analytics traffic through your documentation domain using Next.js rewrites. Instead of the browser talking to PostHog directly (which ad blockers intercept), requests go through \`/ingest\` on your own domain and are proxied on.
55
56
 
56
57
  This means:
57
58
 
58
- - No third-party domains appear in network requests.
59
+ - No third-party domains appear in the browser's network requests.
59
60
  - Ad blockers are less likely to interfere with tracking.
60
61
  - Your users' browsing data stays within your domain boundary before reaching PostHog.
61
62
 
62
63
  The proxy destinations are derived automatically from the \`host\` field in your configuration.
63
64
 
65
+ <Callout type="warning">
66
+ The proxy covers browser traffic only. Server-side page views are sent from
67
+ your server straight to PostHog - that is exactly what lets them survive an
68
+ ad blocker.
69
+ </Callout>
70
+
71
+ ## Cookies
72
+
73
+ An analytics-enabled site sets two first-party cookies:
74
+
75
+ - \`ph_<key>_posthog\` - set by posthog-js, holding its anonymous distinct id and session.
76
+ - \`dcp_anon_id\` - httpOnly, one year, set by the server so an ad-blocked reader (who never receives the posthog-js cookie) counts as one person instead of a new person on every request.
77
+
78
+ Both hold nothing but a random identifier. Whether they require a consent notice
79
+ under GDPR/ePrivacy depends on your jurisdiction and what you do with the data;
80
+ that call is yours.
81
+
64
82
  ## Getting a PostHog key
65
83
 
66
84
  1. Sign up at [posthog.com](https://posthog.com) (free tier available).
@@ -1 +1 @@
1
- export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are tracked client-side and proxied through your own domain for privacy - no data is sent directly to PostHog.\n\n## Enabling analytics\n\nUse the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.\n\n## Configuration\n\n### PostHog Project API Key\n\nYour project API key from PostHog (starts with `phc_`). This is a public identifier and is safe to commit to your repository.\n\nTo find your key:\n\n1. Log in to [PostHog](https://posthog.com).\n2. Open your project settings.\n3. Copy the **Project API Key**.\n\n### Region\n\nSelect the PostHog cloud region that matches your project:\n\n- **US Cloud** - `us.i.posthog.com`\n- **EU Cloud** - `eu.i.posthog.com`\n\n## How it works\n\nAnalytics settings are stored in `analytics.json` at the root of your repository. Here's an example:\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\nWhen enabled, Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\n<Callout type=\"note\">\n Changes to analytics settings are staged as pending changes. Click **Publish** to commit them to your repository and trigger a deploy.\n</Callout>\n\nSee the [Analytics](/analytics) page for the full configuration reference and additional details on the privacy proxy.";
1
+ export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.\n\n## Enabling analytics\n\nUse the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.\n\n## Configuration\n\n### PostHog Project API Key\n\nYour project API key from PostHog (starts with `phc_`). This is a public identifier and is safe to commit to your repository.\n\nTo find your key:\n\n1. Log in to [PostHog](https://posthog.com).\n2. Open your project settings.\n3. Copy the **Project API Key**.\n\n### Region\n\nSelect the PostHog cloud region that matches your project:\n\n- **US Cloud** - `us.i.posthog.com`\n- **EU Cloud** - `eu.i.posthog.com`\n\n## How it works\n\nAnalytics settings are stored in `analytics.json` at the root of your repository. Here's an example:\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\nWhen enabled, Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\n<Callout type=\"note\">\n Changes to analytics settings are staged as pending changes. Click **Publish** to commit them to your repository and trigger a deploy.\n</Callout>\n\nSee the [Analytics](/analytics) page for the full configuration reference and additional details on the privacy proxy.";
@@ -9,7 +9,7 @@ section: "Platform"
9
9
  ---
10
10
  # Analytics
11
11
 
12
- The Analytics settings page lets you add PostHog analytics to your documentation site. Page views are tracked client-side and proxied through your own domain for privacy - no data is sent directly to PostHog.
12
+ The Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.
13
13
 
14
14
  ## Enabling analytics
15
15
 
@@ -19,10 +19,11 @@ export default nextConfig;
19
19
  `;
20
20
  }
21
21
  const host = analyticsConfig.posthog.host || "https://us.i.posthog.com";
22
- // Derive the assets host from the API host (e.g. https://us.i.posthog.com -> https://us-assets.i.posthog.com)
23
- const assetsHost = host
24
- .replace("://", "://" + "")
25
- .replace(".i.", "-assets.i.");
22
+ // Derive the assets host from the API host
23
+ // (https://us.i.posthog.com -> https://us-assets.i.posthog.com). Self-hosted
24
+ // instances have no ".i." segment and serve assets from the same origin, so
25
+ // they correctly fall through unchanged.
26
+ const assetsHost = host.replace(".i.", "-assets.i.");
26
27
  return `import type { NextConfig } from "next";
27
28
 
28
29
  const nextConfig: NextConfig = {
@@ -17,7 +17,6 @@ export const packageJsonTemplate = JSON.stringify({
17
17
  "@langchain/openai": "^1.5.5",
18
18
  "@mdx-js/react": "^3.1.1",
19
19
  "@modelcontextprotocol/sdk": "^1.29.0",
20
- "@posthog/react": "^1.10.3",
21
20
  "beautiful-mermaid": "^1.1.3",
22
21
  "cherry-styled-components": "^0.2.11",
23
22
  langchain: "^1.5.3",
@@ -25,8 +24,8 @@ export const packageJsonTemplate = JSON.stringify({
25
24
  minisearch: "^7.2.0",
26
25
  next: "16.2.10",
27
26
  "next-mdx-remote": "^6.0.0",
28
- "posthog-js": "^1.404.1",
29
- "posthog-node": "^5.45.2",
27
+ "posthog-js": "^1.405.3",
28
+ "posthog-node": "^5.46.0",
30
29
  react: "19.2.7",
31
30
  "react-dom": "19.2.7",
32
31
  "rehype-highlight": "^7.0.2",
@@ -43,8 +42,8 @@ export const packageJsonTemplate = JSON.stringify({
43
42
  "@types/node": "^26",
44
43
  "@types/react": "^19",
45
44
  "@types/react-dom": "^19",
46
- "@typescript-eslint/eslint-plugin": "^8.64.0",
47
- "@typescript-eslint/parser": "^8.64.0",
45
+ "@typescript-eslint/eslint-plugin": "^8.65.0",
46
+ "@typescript-eslint/parser": "^8.65.0",
48
47
  "@typescript/native-preview": "^7.0.0-dev.20260707.2",
49
48
  eslint: "^10",
50
49
  "eslint-plugin-import": "^2.32.0",
@@ -52,7 +51,7 @@ export const packageJsonTemplate = JSON.stringify({
52
51
  "eslint-plugin-react": "^7.37.5",
53
52
  "eslint-plugin-react-hooks": "^7.1.1",
54
53
  globals: "^17.7.0",
55
- prettier: "^3.9.5",
54
+ prettier: "^3.9.6",
56
55
  tsx: "^4.23.1",
57
56
  typescript: "npm:@typescript/typescript6@^6.0.2",
58
57
  },
@@ -8,36 +8,96 @@ export const proxyTemplate = (analyticsConfig = null) => {
8
8
  ? `
9
9
  const SKIP_PAGEVIEW_PATTERN = /^\\/(api|ingest|_next)\\//;
10
10
 
11
- function captureServerPageview(req: NextRequest, event: NextFetchEvent) {
12
- const pathname = req.nextUrl.pathname;
13
-
14
- if (SKIP_PAGEVIEW_PATTERN.test(pathname)) return;
15
-
16
- const isPrefetch =
17
- req.headers.get("next-router-prefetch") === "1" ||
18
- req.headers.get("purpose") === "prefetch";
19
- if (isPrefetch) return;
11
+ /**
12
+ * First-party anonymous id.
13
+ *
14
+ * posthog-js keeps its own id in \`ph_<key>_posthog\`, but an ad blocker stops
15
+ * that script from ever running, so a blocked reader never gets one. Without an
16
+ * id of our own we minted a fresh UUID per request, which made every single
17
+ * pageview a brand-new "person" and badly inflated unique-visitor counts. This
18
+ * cookie is what makes one anonymous reader one person across requests.
19
+ *
20
+ * It is first-party and httpOnly: only the edge reads it, and it never leaves
21
+ * your domain except as a PostHog distinct_id.
22
+ */
23
+ const ANON_ID_COOKIE = "dcp_anon_id";
24
+
25
+ const ANON_ID_MAX_AGE = 60 * 60 * 24 * 365;
26
+
27
+ interface TrackingIdentity {
28
+ distinctId: string;
29
+ /** Set only when the id was just minted and still needs writing to a cookie. */
30
+ anonIdToPersist?: string;
31
+ sessionId?: string;
32
+ deviceId?: string;
33
+ }
20
34
 
21
- const posthog = getPostHogServerClient();
22
- if (!posthog) return;
35
+ /**
36
+ * Resolves who this pageview belongs to: whatever posthog-js already
37
+ * established for this browser, else our own anonymous cookie, else a fresh id
38
+ * that the caller persists.
39
+ */
40
+ function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
41
+ let distinctId: string | undefined;
42
+ let sessionId: string | undefined;
43
+ let deviceId: string | undefined;
23
44
 
24
45
  const phCookie = req.cookies.get(
25
46
  "ph_${analyticsConfig.posthog.key}_posthog",
26
47
  )?.value;
27
- let distinctId: string | undefined;
28
48
  if (phCookie) {
29
49
  try {
30
- distinctId = JSON.parse(phCookie).distinct_id;
50
+ const parsed = JSON.parse(phCookie);
51
+ if (typeof parsed.distinct_id === "string") distinctId = parsed.distinct_id;
52
+ // \`$sesid\` is [lastActivityTs, sessionId, sessionStartTs]. Forwarding it
53
+ // keeps server events inside the client's session instead of floating free.
54
+ if (Array.isArray(parsed.$sesid) && typeof parsed.$sesid[1] === "string") {
55
+ sessionId = parsed.$sesid[1];
56
+ }
57
+ if (typeof parsed.$device_id === "string") deviceId = parsed.$device_id;
31
58
  } catch {
32
59
  // ignore malformed cookie
33
60
  }
34
61
  }
35
- if (!distinctId) {
36
- distinctId = crypto.randomUUID();
37
- }
62
+
63
+ if (distinctId) return { distinctId, sessionId, deviceId };
64
+
65
+ const anonId = req.cookies.get(ANON_ID_COOKIE)?.value;
66
+ if (anonId) return { distinctId: anonId, sessionId, deviceId };
67
+
68
+ const minted = crypto.randomUUID();
69
+ return { distinctId: minted, anonIdToPersist: minted, sessionId, deviceId };
70
+ }
71
+
72
+ /**
73
+ * Server captures document loads; the client tracker captures soft navigations.
74
+ * Splitting by navigation type is what stops the two from both counting the
75
+ * same view — previously every page load produced two \`$pageview\` events.
76
+ */
77
+ function captureServerPageview(
78
+ req: NextRequest,
79
+ event: NextFetchEvent,
80
+ ): TrackingIdentity | null {
81
+ const pathname = req.nextUrl.pathname;
82
+
83
+ if (SKIP_PAGEVIEW_PATTERN.test(pathname)) return null;
84
+
85
+ const isPrefetch =
86
+ req.headers.get("next-router-prefetch") === "1" ||
87
+ req.headers.get("purpose") === "prefetch";
88
+ if (isPrefetch) return null;
89
+
90
+ // A soft navigation fetches an RSC payload rather than a document, and
91
+ // carries this header. The client tracker owns those.
92
+ if (req.headers.get("RSC")) return null;
93
+
94
+ const posthog = getPostHogServerClient();
95
+ if (!posthog) return null;
96
+
97
+ const identity = resolveTrackingIdentity(req);
38
98
 
39
99
  posthog.capture({
40
- distinctId,
100
+ distinctId: identity.distinctId,
41
101
  event: "$pageview",
42
102
  properties: {
43
103
  $current_url: req.url,
@@ -45,16 +105,46 @@ function captureServerPageview(req: NextRequest, event: NextFetchEvent) {
45
105
  $host: req.headers.get("host") ?? undefined,
46
106
  $referrer: req.headers.get("referer") ?? undefined,
47
107
  $user_agent: req.headers.get("user-agent") ?? undefined,
108
+ $session_id: identity.sessionId,
109
+ $device_id: identity.deviceId,
48
110
  _server_side: true,
49
111
  },
50
112
  });
51
113
  event.waitUntil(posthog.flush());
114
+
115
+ return identity;
52
116
  }
53
117
  `
54
118
  : "";
55
- const posthogCall = hasPostHog
56
- ? ` captureServerPageview(req, event);\n`
57
- : "";
119
+ // Applied at every exit so the anonymous id is persisted whichever branch the
120
+ // request takes (gate rewrite, redirect, or the normal response). Without it
121
+ // a reader stuck behind the password gate would keep minting new ids.
122
+ const applyTrackingFn = hasPostHog
123
+ ? `
124
+ function applyTracking(
125
+ res: NextResponse,
126
+ tracking: TrackingIdentity | null,
127
+ ): NextResponse {
128
+ if (tracking?.anonIdToPersist) {
129
+ res.cookies.set(ANON_ID_COOKIE, tracking.anonIdToPersist, {
130
+ path: "/",
131
+ maxAge: ANON_ID_MAX_AGE,
132
+ sameSite: "lax",
133
+ httpOnly: true,
134
+ secure: process.env.NODE_ENV === "production",
135
+ });
136
+ }
137
+ return res;
138
+ }
139
+ `
140
+ : `
141
+ function applyTracking(res: NextResponse, _tracking: null): NextResponse {
142
+ return res;
143
+ }
144
+ `;
145
+ const trackingInit = hasPostHog
146
+ ? ` const tracking = captureServerPageview(req, event);\n`
147
+ : ` const tracking = null;\n`;
58
148
  const fnSignature = hasPostHog
59
149
  ? `export async function proxy(req: NextRequest, event: NextFetchEvent)`
60
150
  : `export async function proxy(req: NextRequest)`;
@@ -73,9 +163,9 @@ function captureServerPageview(req: NextRequest, event: NextFetchEvent) {
73
163
  const matcher = `["/:path*"]`;
74
164
  return `import { NextResponse } from "next/server";
75
165
  import type { NextRequest${eventImport} } from "next/server";
76
- ${gateImport}${posthogImport}${posthogPageviewFn}
166
+ ${gateImport}${posthogImport}${posthogPageviewFn}${applyTrackingFn}
77
167
  ${fnSignature} {
78
- ${posthogCall} const pathname = req.nextUrl.pathname;
168
+ ${trackingInit} const pathname = req.nextUrl.pathname;
79
169
  const sitePassword = process.env.SITE_PASSWORD;
80
170
 
81
171
  // API key auth for /api/mcp when DOCS_API_KEY is configured
@@ -119,12 +209,15 @@ ${posthogCall} const pathname = req.nextUrl.pathname;
119
209
  if (!unlocked && !pathname.startsWith("/api") && pathname !== "/gate") {
120
210
  const res = NextResponse.rewrite(new URL("/gate", req.url));
121
211
  res.headers.set("X-Robots-Tag", "noindex, nofollow");
122
- return res;
212
+ return applyTracking(res, tracking);
123
213
  }
124
214
 
125
215
  // Unlocked visitors never need the gate screen.
126
216
  if (unlocked && pathname === "/gate") {
127
- return NextResponse.redirect(new URL("/", req.url));
217
+ return applyTracking(
218
+ NextResponse.redirect(new URL("/", req.url)),
219
+ tracking,
220
+ );
128
221
  }
129
222
  }
130
223
 
@@ -136,7 +229,7 @@ ${posthogCall} const pathname = req.nextUrl.pathname;
136
229
  res.headers.set("X-Robots-Tag", "noindex, nofollow");
137
230
  }
138
231
 
139
- return res;
232
+ return applyTracking(res, tracking);
140
233
  }
141
234
 
142
235
  export const config = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.127",
3
+ "version": "0.0.129",
4
4
  "description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -48,7 +48,7 @@
48
48
  "@types/fs-extra": "^11.0.4",
49
49
  "@types/node": "^26.1.1",
50
50
  "@types/prompts": "^2.4.9",
51
- "prettier": "^3.9.5",
51
+ "prettier": "^3.9.6",
52
52
  "typescript": "^7.0.2",
53
53
  "vitest": "^4.1.10"
54
54
  },