@minihog/nuxt 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +127 -2
- package/dist/module.d.ts +5 -0
- package/dist/module.d.ts.map +1 -0
- package/dist/module.js +92 -0
- package/dist/module.js.map +1 -0
- package/dist/runtime/composable.d.ts +4 -0
- package/dist/runtime/composable.d.ts.map +1 -0
- package/dist/runtime/composable.js +6 -0
- package/dist/runtime/composable.js.map +1 -0
- package/dist/runtime/controller.d.ts +6 -0
- package/dist/runtime/controller.d.ts.map +1 -0
- package/dist/runtime/controller.js +52 -0
- package/dist/runtime/controller.js.map +1 -0
- package/dist/runtime/plugin.d.ts +7 -0
- package/dist/runtime/plugin.d.ts.map +1 -0
- package/dist/runtime/plugin.js +20 -0
- package/dist/runtime/plugin.js.map +1 -0
- package/dist/runtime/server/body.d.ts +4 -0
- package/dist/runtime/server/body.d.ts.map +1 -0
- package/dist/runtime/server/body.js +28 -0
- package/dist/runtime/server/body.js.map +1 -0
- package/dist/runtime/server/proxy.d.ts +3 -0
- package/dist/runtime/server/proxy.d.ts.map +1 -0
- package/dist/runtime/server/proxy.js +62 -0
- package/dist/runtime/server/proxy.js.map +1 -0
- package/dist/runtime/server/routing.d.ts +4 -0
- package/dist/runtime/server/routing.d.ts.map +1 -0
- package/dist/runtime/server/routing.js +18 -0
- package/dist/runtime/server/routing.js.map +1 -0
- package/dist/templates.d.ts +4 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +88 -0
- package/dist/templates.js.map +1 -0
- package/dist/types.d.ts +46 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +76 -3
- package/src/module.ts +99 -0
- package/src/runtime/composable.ts +7 -0
- package/src/runtime/controller.ts +54 -0
- package/src/runtime/plugin.ts +23 -0
- package/src/runtime/server/body.ts +26 -0
- package/src/runtime/server/proxy.ts +63 -0
- package/src/runtime/server/routing.ts +15 -0
- package/src/shims.d.ts +9 -0
- package/src/templates.ts +91 -0
- package/src/types.ts +59 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Generates imports at build time so disabled features have no output chunks. */
|
|
2
|
+
export function initializerSource(options) {
|
|
3
|
+
const imports = [
|
|
4
|
+
"import { createMiniHog } from '@minihog/core';",
|
|
5
|
+
"import { getRemoteConfig } from '@minihog/core/remote-config';"
|
|
6
|
+
];
|
|
7
|
+
const setup = [];
|
|
8
|
+
if (options.browser !== false) {
|
|
9
|
+
imports.push("import { startBrowserCapture } from '@minihog/core/browser';");
|
|
10
|
+
setup.push(`cleanups.push(startBrowserCapture(client, { ...${JSON.stringify(options.browser ?? {})}, autocapture: remote ? !remote.autocapture_opt_out && ${options.browser?.autocapture !== false} : false }));`);
|
|
11
|
+
}
|
|
12
|
+
if (options.webVitals) {
|
|
13
|
+
setup.push(`if (remote?.capturePerformance?.web_vitals) {
|
|
14
|
+
const { startWebVitals } = await import('@minihog/core/web-vitals');
|
|
15
|
+
if (!valid()) return;
|
|
16
|
+
cleanups.push(startWebVitals(client, remote.capturePerformance.web_vitals_allowed_metrics ?? undefined));
|
|
17
|
+
}`);
|
|
18
|
+
}
|
|
19
|
+
if (options.heatmaps) {
|
|
20
|
+
setup.push(`if (remote?.heatmaps) {
|
|
21
|
+
const rules = remote.heatmaps;
|
|
22
|
+
if (typeof rules === 'object' && rules.urlAllowlistEnforced) {
|
|
23
|
+
console.warn('[minihog] Heatmaps disabled: enforced URL targeting requires an explicit integration.');
|
|
24
|
+
} else {
|
|
25
|
+
const { startHeatmaps } = await import('@minihog/core/heatmaps');
|
|
26
|
+
if (!valid()) return;
|
|
27
|
+
cleanups.push(startHeatmaps(client));
|
|
28
|
+
}
|
|
29
|
+
}`);
|
|
30
|
+
}
|
|
31
|
+
if (options.replay) {
|
|
32
|
+
setup.push(`
|
|
33
|
+
const recording = remote?.sessionRecording;
|
|
34
|
+
if (recording) {
|
|
35
|
+
// Unknown eligibility rules must never broaden who is recorded.
|
|
36
|
+
const unsupported = recording.urlTriggers?.length || recording.urlBlocklist?.length || recording.eventTriggers?.length || recording.linkedFlag || recording.networkPayloadCapture;
|
|
37
|
+
if (unsupported) {
|
|
38
|
+
console.warn('[minihog] Replay disabled: remote targeting or payload rules require an explicit integration.');
|
|
39
|
+
} else {
|
|
40
|
+
const { startSessionReplay } = await import('@minihog/core/replay');
|
|
41
|
+
if (!valid()) return;
|
|
42
|
+
const plugins = [];
|
|
43
|
+
${options.consoleRecording ? "if (recording.consoleLogRecordingEnabled) { const { consoleRecordingPlugin } = await import('@minihog/core/replay-console'); if (!valid()) return; plugins.push(consoleRecordingPlugin()); }" : ''}
|
|
44
|
+
${options.networkTiming ? "if (remote.capturePerformance?.network_timing) { const { networkTimingPlugin } = await import('@minihog/core/replay-network'); if (!valid()) return; plugins.push(networkTimingPlugin(client.apiHost)); }" : ''}
|
|
45
|
+
cleanups.push(startSessionReplay(client, {
|
|
46
|
+
plugins,
|
|
47
|
+
sampleRate: recording.sampleRate == null ? 1 : Number(recording.sampleRate),
|
|
48
|
+
minimumDurationMs: recording.minimumDurationMilliseconds ?? 0,
|
|
49
|
+
recordCanvas: recording.recordCanvas ?? false,
|
|
50
|
+
...recording.masking
|
|
51
|
+
}).stop);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
`);
|
|
55
|
+
}
|
|
56
|
+
if (options.errorCapture) {
|
|
57
|
+
imports.push("import { startErrorCapture } from '@minihog/core/errors';");
|
|
58
|
+
setup.push('cleanups.push(startErrorCapture(client));');
|
|
59
|
+
}
|
|
60
|
+
return `${imports.join('\n')}
|
|
61
|
+
export async function initialize(config, isActive = () => true) {
|
|
62
|
+
const client = createMiniHog(config.key, { ...config.client, apiHost: config.proxyPath });
|
|
63
|
+
const cleanups = [];
|
|
64
|
+
let generation = 0;
|
|
65
|
+
let disposed = false;
|
|
66
|
+
const clear = () => { for (const cleanup of cleanups.splice(0)) cleanup(); };
|
|
67
|
+
async function activate() {
|
|
68
|
+
const version = ++generation;
|
|
69
|
+
clear();
|
|
70
|
+
const valid = () => !disposed && version === generation && isActive() && !client.hasOptedOut();
|
|
71
|
+
if (!valid()) return;
|
|
72
|
+
const remote = await getRemoteConfig(client);
|
|
73
|
+
if (!valid()) return;
|
|
74
|
+
${setup.join('\n')}
|
|
75
|
+
}
|
|
76
|
+
const unsubscribe = client.onConsentChange(() => { void activate().catch(error => console.warn('[minihog] Analytics could not restart.', error)); });
|
|
77
|
+
client.addCleanup(() => { disposed = true; generation++; unsubscribe(); clear(); });
|
|
78
|
+
try {
|
|
79
|
+
await activate();
|
|
80
|
+
return client;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
await client.destroy();
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
`;
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=templates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAEA,kFAAkF;AAClF,MAAM,UAAU,iBAAiB,CAAC,OAAsB;IACtD,MAAM,OAAO,GAAG;QACd,gDAAgD;QAChD,gEAAgE;KACjE,CAAC;IACF,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,OAAO,CAAC,OAAO,KAAK,KAAK,EAAE,CAAC;QAC9B,OAAO,CAAC,IAAI,CAAC,8DAA8D,CAAC,CAAC;QAC7E,KAAK,CAAC,IAAI,CACR,kDAAkD,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,0DAA0D,OAAO,CAAC,OAAO,EAAE,WAAW,KAAK,KAAK,eAAe,CACvM,CAAC;IACJ,CAAC;IACD,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QACtB,KAAK,CAAC,IAAI,CAAC;;;;MAIT,CAAC,CAAC;IACN,CAAC;IACD,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,KAAK,CAAC,IAAI,CAAC;;;;;;;;;MAST,CAAC,CAAC;IACN,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnB,KAAK,CAAC,IAAI,CAAC;;;;;;;;;;;YAWH,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,8LAA8L,CAAC,CAAC,CAAC,EAAE;YAC9N,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,2MAA2M,CAAC,CAAC,CAAC,EAAE;;;;;;;;;;KAU/O,CAAC,CAAC;IACL,CAAC;IACD,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;QAC1E,KAAK,CAAC,IAAI,CAAC,2CAA2C,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;;;;;;;;MAcxB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;;;;;;CAYrB,CAAC;AACF,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { MiniHog, MiniHogOptions } from '@minihog/core';
|
|
2
|
+
import type { BrowserOptions } from '@minihog/core/browser';
|
|
3
|
+
export interface ModuleOptions {
|
|
4
|
+
key?: string;
|
|
5
|
+
host?: string;
|
|
6
|
+
assetsHost?: string;
|
|
7
|
+
proxyPath?: string;
|
|
8
|
+
start?: 'ready' | 'idle' | 'manual';
|
|
9
|
+
browser?: false | BrowserOptions;
|
|
10
|
+
webVitals?: boolean;
|
|
11
|
+
heatmaps?: boolean;
|
|
12
|
+
replay?: boolean;
|
|
13
|
+
consoleRecording?: boolean;
|
|
14
|
+
networkTiming?: boolean;
|
|
15
|
+
errorCapture?: boolean;
|
|
16
|
+
/** Only serializable client options belong in runtime configuration. */
|
|
17
|
+
client?: Pick<MiniHogOptions, 'personProfiles' | 'persistence' | 'migratePostHog' | 'optOutByDefault' | 'respectDnt' | 'sessionTimeoutMs' | 'flushIntervalMs'>;
|
|
18
|
+
}
|
|
19
|
+
export interface PublicOptions {
|
|
20
|
+
key: string;
|
|
21
|
+
proxyPath: string;
|
|
22
|
+
start: 'ready' | 'idle' | 'manual';
|
|
23
|
+
client: NonNullable<ModuleOptions['client']>;
|
|
24
|
+
}
|
|
25
|
+
export interface ProxyOptions {
|
|
26
|
+
host: string;
|
|
27
|
+
assetsHost: string;
|
|
28
|
+
path: string;
|
|
29
|
+
}
|
|
30
|
+
export interface MiniHogController {
|
|
31
|
+
/** Concurrent calls share one initialization. An empty key performs no imports. */
|
|
32
|
+
start(): Promise<MiniHog | undefined>;
|
|
33
|
+
getClient(): MiniHog | undefined;
|
|
34
|
+
stop(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
declare module '#app' {
|
|
37
|
+
interface NuxtApp {
|
|
38
|
+
$minihog: MiniHogController;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
declare module 'vue' {
|
|
42
|
+
interface ComponentCustomProperties {
|
|
43
|
+
$minihog: MiniHogController;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,MAAM,WAAW,aAAa;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;IACpC,OAAO,CAAC,EAAE,KAAK,GAAG,cAAc,CAAC;IACjC,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wEAAwE;IACxE,MAAM,CAAC,EAAE,IAAI,CACX,cAAc,EACZ,gBAAgB,GAChB,aAAa,GACb,gBAAgB,GAChB,iBAAiB,GACjB,YAAY,GACZ,kBAAkB,GAClB,iBAAiB,CACpB,CAAC;CACH;AAED,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;IACnC,MAAM,EAAE,WAAW,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,iBAAiB;IAChC,mFAAmF;IACnF,KAAK,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC;IACtC,SAAS,IAAI,OAAO,GAAG,SAAS,CAAC;IACjC,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED,OAAO,QAAQ,MAAM,CAAC;IACpB,UAAU,OAAO;QACf,QAAQ,EAAE,iBAAiB,CAAC;KAC7B;CACF;AACD,OAAO,QAAQ,KAAK,CAAC;IACnB,UAAU,yBAAyB;QACjC,QAAQ,EAAE,iBAAiB,CAAC;KAC7B;CACF"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minihog/nuxt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Nuxt module for MiniHog with a same-origin PostHog proxy and deferred startup.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md",
|
|
11
|
+
"LICENSE",
|
|
12
|
+
"CHANGELOG.md",
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/module.d.ts",
|
|
18
|
+
"import": "./dist/module.js",
|
|
19
|
+
"default": "./dist/module.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@minihog/core": "^0.1.1"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@nuxt/kit": "^4.6.4",
|
|
34
|
+
"@nuxt/schema": "^4.6.4",
|
|
35
|
+
"h3": "^1.15.11",
|
|
36
|
+
"nuxt": "^4.0.0",
|
|
37
|
+
"vue": "^3.5.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@nuxt/kit": "^4.7.1",
|
|
41
|
+
"@nuxt/schema": "^4.7.1",
|
|
42
|
+
"h3": "^1.15.11",
|
|
43
|
+
"nuxt": "^4.7.1",
|
|
44
|
+
"vue": "^3.5.46"
|
|
45
|
+
},
|
|
46
|
+
"author": "Stefan Popov <hello@stefanpopov.dev>",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/stefashkaa/minihog.git",
|
|
50
|
+
"directory": "packages/nuxt"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/stefashkaa/minihog/issues"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/stefashkaa/minihog/tree/main/packages/nuxt#readme",
|
|
56
|
+
"private": false,
|
|
57
|
+
"keywords": [
|
|
58
|
+
"posthog",
|
|
59
|
+
"analytics",
|
|
60
|
+
"typescript",
|
|
61
|
+
"tree-shaking",
|
|
62
|
+
"minihog",
|
|
63
|
+
"nuxt",
|
|
64
|
+
"nuxt-module",
|
|
65
|
+
"proxy"
|
|
66
|
+
],
|
|
67
|
+
"main": "./dist/module.js",
|
|
68
|
+
"types": "./dist/module.d.ts",
|
|
69
|
+
"scripts": {
|
|
70
|
+
"clean": "rimraf dist coverage",
|
|
71
|
+
"clean:modules": "rimraf node_modules fixtures/consumer/node_modules",
|
|
72
|
+
"build": "rimraf dist && tsc -p tsconfig.json",
|
|
73
|
+
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tests/tsconfig.json",
|
|
74
|
+
"test:unit": "vitest run --config vitest.config.ts",
|
|
75
|
+
"test:unit:coverage": "vitest run --config vitest.config.ts --coverage.enabled",
|
|
76
|
+
"publish:check": "node ../../scripts/check-package.mts --profile esm-only",
|
|
77
|
+
"test:e2e": "playwright test --config playwright.config.ts"
|
|
78
|
+
}
|
|
6
79
|
}
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { addImports, addPlugin, addServerHandler, addTemplate, createResolver, defineNuxtModule } from '@nuxt/kit';
|
|
2
|
+
import { initializerSource } from './templates.js';
|
|
3
|
+
import type { ModuleOptions } from './types.js';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export type { MiniHogController, ModuleOptions } from './types.js';
|
|
7
|
+
|
|
8
|
+
export default defineNuxtModule<ModuleOptions>({
|
|
9
|
+
meta: { name: '@minihog/nuxt', configKey: 'minihog', compatibility: { nuxt: '^4.0.0' } },
|
|
10
|
+
defaults: {
|
|
11
|
+
key: '',
|
|
12
|
+
host: 'https://us.i.posthog.com',
|
|
13
|
+
proxyPath: '/api/_ph',
|
|
14
|
+
start: 'ready',
|
|
15
|
+
browser: {},
|
|
16
|
+
webVitals: false,
|
|
17
|
+
heatmaps: false,
|
|
18
|
+
replay: false,
|
|
19
|
+
consoleRecording: false,
|
|
20
|
+
networkTiming: false,
|
|
21
|
+
errorCapture: false,
|
|
22
|
+
client: {}
|
|
23
|
+
},
|
|
24
|
+
setup(options, nuxt) {
|
|
25
|
+
const resolver = createResolver(import.meta.url);
|
|
26
|
+
const host = new URL(options.host!);
|
|
27
|
+
if (
|
|
28
|
+
!['http:', 'https:'].includes(host.protocol) ||
|
|
29
|
+
host.username ||
|
|
30
|
+
host.password ||
|
|
31
|
+
host.search ||
|
|
32
|
+
host.hash ||
|
|
33
|
+
host.pathname !== '/'
|
|
34
|
+
) {
|
|
35
|
+
throw new Error('minihog.host must be an HTTP(S) origin without credentials, a path, or query parameters.');
|
|
36
|
+
}
|
|
37
|
+
const path = options.proxyPath!.replace(/\/+$/, '');
|
|
38
|
+
if (!/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+$/.test(path))
|
|
39
|
+
throw new Error('minihog.proxyPath must be an absolute local path.');
|
|
40
|
+
const assetsHost =
|
|
41
|
+
options.assetsHost ??
|
|
42
|
+
(host.hostname === 'eu.i.posthog.com'
|
|
43
|
+
? 'https://eu-assets.i.posthog.com'
|
|
44
|
+
: host.hostname === 'us.i.posthog.com'
|
|
45
|
+
? 'https://us-assets.i.posthog.com'
|
|
46
|
+
: host.origin);
|
|
47
|
+
const assets = new URL(assetsHost);
|
|
48
|
+
if (
|
|
49
|
+
!['http:', 'https:'].includes(assets.protocol) ||
|
|
50
|
+
assets.username ||
|
|
51
|
+
assets.password ||
|
|
52
|
+
assets.search ||
|
|
53
|
+
assets.hash ||
|
|
54
|
+
assets.pathname !== '/'
|
|
55
|
+
)
|
|
56
|
+
throw new Error('minihog.assetsHost must be an HTTP(S) origin.');
|
|
57
|
+
nuxt.options.runtimeConfig.minihog = { host: host.origin, assetsHost: assets.origin, path };
|
|
58
|
+
nuxt.options.runtimeConfig.public.minihog = {
|
|
59
|
+
key: options.key ?? '',
|
|
60
|
+
proxyPath: path,
|
|
61
|
+
start: options.start!,
|
|
62
|
+
client: options.client ?? {}
|
|
63
|
+
};
|
|
64
|
+
const template = addTemplate({
|
|
65
|
+
filename: 'minihog/init.mjs',
|
|
66
|
+
getContents: () => initializerSource(options)
|
|
67
|
+
});
|
|
68
|
+
nuxt.options.alias['#minihog-init'] = template.dst;
|
|
69
|
+
// Resolve from the installed module, including when pnpm keeps core transitive.
|
|
70
|
+
// Specific subpaths precede the root because Vite aliases also match prefixes.
|
|
71
|
+
for (const entry of [
|
|
72
|
+
'identity',
|
|
73
|
+
'flags',
|
|
74
|
+
'surveys',
|
|
75
|
+
'package.json',
|
|
76
|
+
'browser',
|
|
77
|
+
'remote-config',
|
|
78
|
+
'web-vitals',
|
|
79
|
+
'heatmaps',
|
|
80
|
+
'replay-console',
|
|
81
|
+
'replay-network',
|
|
82
|
+
'replay',
|
|
83
|
+
'errors',
|
|
84
|
+
''
|
|
85
|
+
]) {
|
|
86
|
+
const specifier = `@minihog/core${entry ? `/${entry}` : ''}`;
|
|
87
|
+
nuxt.options.alias[specifier] = fileURLToPath(import.meta.resolve(specifier));
|
|
88
|
+
}
|
|
89
|
+
addPlugin({ src: resolver.resolve('./runtime/plugin.js'), order: -20 });
|
|
90
|
+
addImports({ name: 'useMiniHog', from: resolver.resolve('./runtime/composable.js') });
|
|
91
|
+
addServerHandler({ route: `${path}/**`, handler: resolver.resolve('./runtime/server/proxy.js') });
|
|
92
|
+
nuxt.hook('build:manifest', (manifest) => {
|
|
93
|
+
// These chunks must follow the application's start() boundary, including replay peers.
|
|
94
|
+
for (const [id, entry] of Object.entries(manifest)) {
|
|
95
|
+
if (/minihog|rrweb|web-vitals/.test(id)) entry.prefetch = false;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { MiniHog } from '@minihog/core';
|
|
2
|
+
import type { MiniHogController, PublicOptions } from '../types.js';
|
|
3
|
+
|
|
4
|
+
type Initialize = (config: PublicOptions, isActive: () => boolean) => Promise<MiniHog>;
|
|
5
|
+
|
|
6
|
+
export function createController(
|
|
7
|
+
config: PublicOptions,
|
|
8
|
+
load: () => Promise<Initialize>,
|
|
9
|
+
onError: (error: unknown) => void
|
|
10
|
+
): MiniHogController {
|
|
11
|
+
let client: MiniHog | undefined;
|
|
12
|
+
let pending: Promise<MiniHog | undefined> | undefined;
|
|
13
|
+
let generation = 0;
|
|
14
|
+
return {
|
|
15
|
+
getClient: () => client,
|
|
16
|
+
start() {
|
|
17
|
+
if (!config.key) return Promise.resolve(undefined);
|
|
18
|
+
if (client) return Promise.resolve(client);
|
|
19
|
+
if (pending) return pending;
|
|
20
|
+
const version = generation;
|
|
21
|
+
const operation = load()
|
|
22
|
+
.then((initialize) => {
|
|
23
|
+
if (version === generation) return initialize(config, () => version === generation);
|
|
24
|
+
})
|
|
25
|
+
.then(async (created) => {
|
|
26
|
+
if (!created) return;
|
|
27
|
+
if (version !== generation) {
|
|
28
|
+
await created.destroy();
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
client = created;
|
|
32
|
+
return client;
|
|
33
|
+
})
|
|
34
|
+
.catch((error: unknown) => {
|
|
35
|
+
onError(error);
|
|
36
|
+
return undefined;
|
|
37
|
+
})
|
|
38
|
+
.finally(() => {
|
|
39
|
+
if (pending === operation) pending = undefined;
|
|
40
|
+
});
|
|
41
|
+
pending = operation;
|
|
42
|
+
return operation;
|
|
43
|
+
},
|
|
44
|
+
async stop() {
|
|
45
|
+
generation++;
|
|
46
|
+
const loading = pending;
|
|
47
|
+
const previous = client;
|
|
48
|
+
pending = undefined;
|
|
49
|
+
client = undefined;
|
|
50
|
+
await loading;
|
|
51
|
+
await previous?.destroy();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { defineNuxtPlugin, onNuxtReady, useRuntimeConfig } from '#app';
|
|
2
|
+
import type { PublicOptions } from '../types.js';
|
|
3
|
+
import { createController } from './controller.js';
|
|
4
|
+
|
|
5
|
+
export default defineNuxtPlugin({
|
|
6
|
+
name: 'minihog',
|
|
7
|
+
setup() {
|
|
8
|
+
const config = useRuntimeConfig().public.minihog as PublicOptions;
|
|
9
|
+
const controller = createController(
|
|
10
|
+
typeof window === 'undefined' ? { ...config, key: '' } : config,
|
|
11
|
+
() => import('#minihog-init').then(({ initialize }) => initialize),
|
|
12
|
+
(error) => console.warn('[minihog] Analytics could not start.', error)
|
|
13
|
+
);
|
|
14
|
+
if (typeof window !== 'undefined' && config.start !== 'manual') {
|
|
15
|
+
onNuxtReady(() => {
|
|
16
|
+
if (config.start === 'idle' && 'requestIdleCallback' in window) {
|
|
17
|
+
window.requestIdleCallback(() => void controller.start(), { timeout: 2000 });
|
|
18
|
+
} else void controller.start();
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return { provide: { minihog: controller } };
|
|
22
|
+
}
|
|
23
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Readable } from 'node:stream';
|
|
2
|
+
|
|
3
|
+
/** Limit body memory without destroying the socket before Nitro can return 413. */
|
|
4
|
+
export async function limitedBody(stream: Readable, limit: number): Promise<string> {
|
|
5
|
+
const reader = stream.iterator({ destroyOnReturn: false });
|
|
6
|
+
const decoder = new TextDecoder();
|
|
7
|
+
let size = 0;
|
|
8
|
+
let body = '';
|
|
9
|
+
try {
|
|
10
|
+
while (true) {
|
|
11
|
+
const chunk = await reader.next();
|
|
12
|
+
if (chunk.done) break;
|
|
13
|
+
size += chunk.value.byteLength;
|
|
14
|
+
if (size > limit) {
|
|
15
|
+
throw new RangeError('Analytics payload too large');
|
|
16
|
+
}
|
|
17
|
+
body += decoder.decode(chunk.value, { stream: true });
|
|
18
|
+
}
|
|
19
|
+
return body + decoder.decode();
|
|
20
|
+
} finally {
|
|
21
|
+
await reader.return?.();
|
|
22
|
+
// Drain unread bytes without retaining them. H3 1.x's Web Stream adapter does
|
|
23
|
+
// not detach its end handler on cancellation and otherwise throws on close.
|
|
24
|
+
if (!stream.readableEnded) stream.resume();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createError,
|
|
3
|
+
defineEventHandler,
|
|
4
|
+
getHeader,
|
|
5
|
+
getRequestHeaders,
|
|
6
|
+
getRequestURL,
|
|
7
|
+
setHeader,
|
|
8
|
+
setResponseStatus
|
|
9
|
+
} from 'h3';
|
|
10
|
+
import { useRuntimeConfig } from '#imports';
|
|
11
|
+
import { proxyTarget } from './routing.js';
|
|
12
|
+
import { limitedBody } from './body.js';
|
|
13
|
+
|
|
14
|
+
export default defineEventHandler(async (event) => {
|
|
15
|
+
const config = useRuntimeConfig(event).minihog;
|
|
16
|
+
const target = proxyTarget(getRequestURL(event), event.method, config);
|
|
17
|
+
if (!target) throw createError({ statusCode: 404, statusMessage: 'Analytics endpoint not found' });
|
|
18
|
+
const length = Number(getHeader(event, 'content-length') ?? 0);
|
|
19
|
+
const limit = 2 * 1024 * 1024;
|
|
20
|
+
if (length > limit) throw createError({ statusCode: 413, statusMessage: 'Analytics payload too large' });
|
|
21
|
+
let body: string | undefined;
|
|
22
|
+
try {
|
|
23
|
+
if (event.method === 'POST') body = await limitedBody(event.node.req, limit);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error instanceof RangeError)
|
|
26
|
+
throw createError({ statusCode: 413, statusMessage: 'Analytics payload too large' });
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
const incoming = getRequestHeaders(event);
|
|
30
|
+
const headers: Record<string, string> = {};
|
|
31
|
+
// Forward browser context for flag runtime detection and GeoIP, never site credentials.
|
|
32
|
+
for (const name of [
|
|
33
|
+
'content-type',
|
|
34
|
+
'user-agent',
|
|
35
|
+
'origin',
|
|
36
|
+
'referer',
|
|
37
|
+
'sec-fetch-site',
|
|
38
|
+
'sec-fetch-mode',
|
|
39
|
+
'x-forwarded-for'
|
|
40
|
+
]) {
|
|
41
|
+
const value = incoming[name];
|
|
42
|
+
if (typeof value === 'string') headers[name] = value;
|
|
43
|
+
}
|
|
44
|
+
let response: Response;
|
|
45
|
+
try {
|
|
46
|
+
response = await fetch(target, {
|
|
47
|
+
method: event.method,
|
|
48
|
+
headers,
|
|
49
|
+
body,
|
|
50
|
+
redirect: 'error',
|
|
51
|
+
signal: AbortSignal.timeout(10000)
|
|
52
|
+
});
|
|
53
|
+
} catch {
|
|
54
|
+
throw createError({ statusCode: 502, statusMessage: 'Analytics upstream unavailable' });
|
|
55
|
+
}
|
|
56
|
+
setResponseStatus(event, response.status);
|
|
57
|
+
for (const name of ['content-type', 'retry-after']) {
|
|
58
|
+
const value = response.headers.get(name);
|
|
59
|
+
if (value) setHeader(event, name, value);
|
|
60
|
+
}
|
|
61
|
+
setHeader(event, 'cache-control', 'no-store');
|
|
62
|
+
return response.body;
|
|
63
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ProxyOptions } from '../../types.js';
|
|
2
|
+
|
|
3
|
+
/** An endpoint allowlist prevents proxying arbitrary URLs, scripts, or management APIs. */
|
|
4
|
+
export function proxyTarget(url: URL, method: string, options: ProxyOptions): string | undefined {
|
|
5
|
+
if (!url.pathname.startsWith(`${options.path}/`)) return;
|
|
6
|
+
const path = url.pathname.slice(options.path.length);
|
|
7
|
+
const ingestion = /^\/(batch|s)\/$/.test(path) || path === '/i/v0/e/';
|
|
8
|
+
const flags = /^\/flags\/?$/.test(path);
|
|
9
|
+
const config = /^\/array\/[a-zA-Z0-9_-]+\/config$/.test(path);
|
|
10
|
+
const surveys = path === '/api/surveys/';
|
|
11
|
+
if ((ingestion || flags) && method !== 'POST') return;
|
|
12
|
+
if ((config || surveys) && method !== 'GET') return;
|
|
13
|
+
if (!ingestion && !flags && !config && !surveys) return;
|
|
14
|
+
return `${config ? options.assetsHost : options.host}${path}${url.search}`;
|
|
15
|
+
}
|
package/src/shims.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
declare module '#minihog-init' {
|
|
2
|
+
export function initialize(
|
|
3
|
+
config: import('./types.js').PublicOptions,
|
|
4
|
+
isActive?: () => boolean
|
|
5
|
+
): Promise<import('@minihog/core').MiniHog>;
|
|
6
|
+
}
|
|
7
|
+
declare module '#imports' {
|
|
8
|
+
export function useRuntimeConfig(event?: unknown): { minihog: import('./types.js').ProxyOptions };
|
|
9
|
+
}
|
package/src/templates.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { ModuleOptions } from './types.js';
|
|
2
|
+
|
|
3
|
+
/** Generates imports at build time so disabled features have no output chunks. */
|
|
4
|
+
export function initializerSource(options: ModuleOptions): string {
|
|
5
|
+
const imports = [
|
|
6
|
+
"import { createMiniHog } from '@minihog/core';",
|
|
7
|
+
"import { getRemoteConfig } from '@minihog/core/remote-config';"
|
|
8
|
+
];
|
|
9
|
+
const setup: string[] = [];
|
|
10
|
+
if (options.browser !== false) {
|
|
11
|
+
imports.push("import { startBrowserCapture } from '@minihog/core/browser';");
|
|
12
|
+
setup.push(
|
|
13
|
+
`cleanups.push(startBrowserCapture(client, { ...${JSON.stringify(options.browser ?? {})}, autocapture: remote ? !remote.autocapture_opt_out && ${options.browser?.autocapture !== false} : false }));`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
if (options.webVitals) {
|
|
17
|
+
setup.push(`if (remote?.capturePerformance?.web_vitals) {
|
|
18
|
+
const { startWebVitals } = await import('@minihog/core/web-vitals');
|
|
19
|
+
if (!valid()) return;
|
|
20
|
+
cleanups.push(startWebVitals(client, remote.capturePerformance.web_vitals_allowed_metrics ?? undefined));
|
|
21
|
+
}`);
|
|
22
|
+
}
|
|
23
|
+
if (options.heatmaps) {
|
|
24
|
+
setup.push(`if (remote?.heatmaps) {
|
|
25
|
+
const rules = remote.heatmaps;
|
|
26
|
+
if (typeof rules === 'object' && rules.urlAllowlistEnforced) {
|
|
27
|
+
console.warn('[minihog] Heatmaps disabled: enforced URL targeting requires an explicit integration.');
|
|
28
|
+
} else {
|
|
29
|
+
const { startHeatmaps } = await import('@minihog/core/heatmaps');
|
|
30
|
+
if (!valid()) return;
|
|
31
|
+
cleanups.push(startHeatmaps(client));
|
|
32
|
+
}
|
|
33
|
+
}`);
|
|
34
|
+
}
|
|
35
|
+
if (options.replay) {
|
|
36
|
+
setup.push(`
|
|
37
|
+
const recording = remote?.sessionRecording;
|
|
38
|
+
if (recording) {
|
|
39
|
+
// Unknown eligibility rules must never broaden who is recorded.
|
|
40
|
+
const unsupported = recording.urlTriggers?.length || recording.urlBlocklist?.length || recording.eventTriggers?.length || recording.linkedFlag || recording.networkPayloadCapture;
|
|
41
|
+
if (unsupported) {
|
|
42
|
+
console.warn('[minihog] Replay disabled: remote targeting or payload rules require an explicit integration.');
|
|
43
|
+
} else {
|
|
44
|
+
const { startSessionReplay } = await import('@minihog/core/replay');
|
|
45
|
+
if (!valid()) return;
|
|
46
|
+
const plugins = [];
|
|
47
|
+
${options.consoleRecording ? "if (recording.consoleLogRecordingEnabled) { const { consoleRecordingPlugin } = await import('@minihog/core/replay-console'); if (!valid()) return; plugins.push(consoleRecordingPlugin()); }" : ''}
|
|
48
|
+
${options.networkTiming ? "if (remote.capturePerformance?.network_timing) { const { networkTimingPlugin } = await import('@minihog/core/replay-network'); if (!valid()) return; plugins.push(networkTimingPlugin(client.apiHost)); }" : ''}
|
|
49
|
+
cleanups.push(startSessionReplay(client, {
|
|
50
|
+
plugins,
|
|
51
|
+
sampleRate: recording.sampleRate == null ? 1 : Number(recording.sampleRate),
|
|
52
|
+
minimumDurationMs: recording.minimumDurationMilliseconds ?? 0,
|
|
53
|
+
recordCanvas: recording.recordCanvas ?? false,
|
|
54
|
+
...recording.masking
|
|
55
|
+
}).stop);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
`);
|
|
59
|
+
}
|
|
60
|
+
if (options.errorCapture) {
|
|
61
|
+
imports.push("import { startErrorCapture } from '@minihog/core/errors';");
|
|
62
|
+
setup.push('cleanups.push(startErrorCapture(client));');
|
|
63
|
+
}
|
|
64
|
+
return `${imports.join('\n')}
|
|
65
|
+
export async function initialize(config, isActive = () => true) {
|
|
66
|
+
const client = createMiniHog(config.key, { ...config.client, apiHost: config.proxyPath });
|
|
67
|
+
const cleanups = [];
|
|
68
|
+
let generation = 0;
|
|
69
|
+
let disposed = false;
|
|
70
|
+
const clear = () => { for (const cleanup of cleanups.splice(0)) cleanup(); };
|
|
71
|
+
async function activate() {
|
|
72
|
+
const version = ++generation;
|
|
73
|
+
clear();
|
|
74
|
+
const valid = () => !disposed && version === generation && isActive() && !client.hasOptedOut();
|
|
75
|
+
if (!valid()) return;
|
|
76
|
+
const remote = await getRemoteConfig(client);
|
|
77
|
+
if (!valid()) return;
|
|
78
|
+
${setup.join('\n')}
|
|
79
|
+
}
|
|
80
|
+
const unsubscribe = client.onConsentChange(() => { void activate().catch(error => console.warn('[minihog] Analytics could not restart.', error)); });
|
|
81
|
+
client.addCleanup(() => { disposed = true; generation++; unsubscribe(); clear(); });
|
|
82
|
+
try {
|
|
83
|
+
await activate();
|
|
84
|
+
return client;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
await client.destroy();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
`;
|
|
91
|
+
}
|