Skip to content

Commit

Permalink
feat: added webAnalytics
Browse files Browse the repository at this point in the history
  • Loading branch information
alexvuka1 committed Feb 23, 2024
1 parent 82ff329 commit b4dbc06
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { getVercelOutput, getFilesFromFolder, copyFilesToFunction, removeDir, wr
import { type VercelImageConfig, getImageConfig, defaultImageConfig } from './lib/image';
import { exposeEnv } from './lib/env';
import { getRedirects } from './lib/redirects';
import { VercelWebAnalyticsConfig, getInjectableWebAnalyticsContent } from './lib/web-analytics';

const PACKAGE_NAME = 'astro-vercel-edge-adapter';

Expand All @@ -26,6 +27,8 @@ const getAdapter = (): AstroAdapter => ({
});

export interface VercelEdgeConfig {
/** Configuration for [Vercel Web Analytics](https://vercel.com/docs/concepts/analytics). */
webAnalytics?: VercelWebAnalyticsConfig;
includeFiles?: string[];
analytics?: boolean;
imageService?: boolean;
Expand All @@ -34,6 +37,7 @@ export interface VercelEdgeConfig {
}

const vercelEdge = ({
webAnalytics,
includeFiles = [],
analytics,
imageService,
Expand All @@ -48,7 +52,15 @@ const vercelEdge = ({
return {
name: PACKAGE_NAME,
hooks: {
'astro:config:setup': ({ command, config, updateConfig, injectScript }) => {
'astro:config:setup': async ({ command, config, updateConfig, injectScript }) => {
if (webAnalytics?.enabled) {
injectScript(
'head-inline',
await getInjectableWebAnalyticsContent({
mode: command === 'dev' ? 'development' : 'production',
})
);
}
if (command === 'build' && analytics) {
injectScript('page', 'import "@astrojs/vercel/analytics"');
}
Expand Down
30 changes: 30 additions & 0 deletions src/lib/web-analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export type VercelWebAnalyticsConfig = {
enabled: boolean;
};

export async function getInjectableWebAnalyticsContent({
mode,
}: {
mode: 'development' | 'production';
}) {
const base = `window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };`;

if (mode === 'development') {
return `
${base}
var script = document.createElement('script');
script.defer = true;
script.src = 'https://cdn.vercel-insights.com/v1/script.debug.js';
var head = document.querySelector('head');
head.appendChild(script);
`;
}

return `${base}
var script = document.createElement('script');
script.defer = true;
script.src = '/_vercel/insights/script.js';
var head = document.querySelector('head');
head.appendChild(script);
`;
}

0 comments on commit b4dbc06

Please sign in to comment.