Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update deps #90

Merged
merged 3 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions .eslintrc

This file was deleted.

2 changes: 1 addition & 1 deletion .playground/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default defineAppConfig({
umami: {
host: 'https://ml-umami.netlify.app/',
host: 'https://savory.vercel.app/',
id: '84cc2d28-8689-4df0-b575-2202e34a75aa',
autoTrack: true,
version: 2,
Expand Down
4 changes: 3 additions & 1 deletion .playground/app.vue
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<script setup lang="ts">
const shareUrl = 'https://savory.vercel.app/share/j2f1spIBFqHJKsXv/Nuxt%20Umami';

function testView() {
umTrackView();
}
Expand Down Expand Up @@ -43,7 +45,7 @@ function seePreview() {
Run trackView
</button>
<a
href="https://ml-umami.netlify.app/share/j2f1spIBFqHJKsXv/Nuxt%20Umami"
:href="shareUrl"
target="_blank"
rel="noopener noreferrer"
@click="seePreview"
Expand Down
2 changes: 1 addition & 1 deletion .playground/components/Heading.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
defineProps<{
title: string
title: string;
}>();
</script>

Expand Down
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
[![License](https://img.shields.io/npm/l/nuxt-umami?style=flat-square)](/LICENSE)
[![Sponsor](https://img.shields.io/badge/Sponsor-21262d?style=flat-square&logo=github&logoColor=db61a2)](https://github.com/sponsors/ijkml)


Integrate [**Umami Analytics**](https://umami.is/) into your Nuxt websites / applications.

## Features
Expand Down Expand Up @@ -193,7 +192,6 @@ You can pass a string as the event name, or an object containing a `name` proper
* __Should I sponsor this project?__
* Absolutely, you can do that here: https://github.com/sponsors/ijkml.


## Issues, Bugs, Ideas?

Contributions are welcome, start a discussion, send a PR! If you find an issue, keep it, finders keepers 😅. (Or, open an issue, I'll be happy to help.)
Expand Down
22 changes: 11 additions & 11 deletions app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ declare module '@nuxt/schema' {
* @required true
* @example 'https://ijkml.xyz/'
*/
host?: string
host?: string;
/**
* Unique identifier provided by Umami
*
* @required true
* @example `3c255b6d-678a-42dd-8074-272ee5b78484`
*/
id?: string
id?: string;
/**
* Configure the tracker to only run on specific domains.
* Provide an array or comma delimited list of domains (without 'http').
Expand All @@ -27,51 +27,51 @@ declare module '@nuxt/schema' {
* @example ['mywebsite.com', 'mywebsite2.com']
* @default undefined
*/
domains?: string | string[]
domains?: string | string[];
/**
* Whether to ignore browsers' Do Not Track setting.
*
* Setting this to `false` will totally disable tracking
* on browsers that have the DoNotTrack setting turned on.
* @default true
*/
ignoreDnt?: boolean
ignoreDnt?: boolean;
/**
* Option to automatically track page views.
*
* @default true
*/
autoTrack?: boolean
autoTrack?: boolean;
/**
* Whether or not to track during development (localhost).
*
* @default false
*/
ignoreLocalhost?: boolean
ignoreLocalhost?: boolean;
/**
* Version of Umami used, either `1.x.x` or `2.x.x`
*
* @default 1
*/
version?: 1 | 2
version?: 1 | 2;
/**
* Self-hosted Umami lets you set a COLLECT_API_ENDPOINT, which is:
* - `/api/collect` by default in Umami v1
* - `/api/send` by default in Umami v2. See Umami [Docs](https://umami.is/docs/environment-variables).
*/
customEndpoint?: `/${string}`
customEndpoint?: `/${string}`;
/**
* Enable `v-umami` directive
*
* @default false
*/
useDirective?: boolean
useDirective?: boolean;
/**
* Enable warning and error logs in prod
*
* @default false
*/
debug?: boolean
}
debug?: boolean;
};
}
}
13 changes: 13 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import antfu from '@antfu/eslint-config';

export default antfu({
stylistic: {
semi: true,
overrides: {
curly: ['error', 'multi', 'consistent'],
},
},
// ignores: [
// "!.playground",
// ],
});
11 changes: 4 additions & 7 deletions internal/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ type ErrorType = PreflightErrs | FunctionErrs;
type LogLevel = 'info' | 'warn' | 'error';
type ErrorId = `err-${ErrorType}`;
interface ErrorObj {
level: LogLevel
text: string
level: LogLevel;
text: string;
}

const warnings: Record<ErrorId, ErrorObj> = {
'err-dnt': { level: 'info', text: "Tracking disabled by browser's DoNotTrack" },
'err-dnt': { level: 'info', text: 'Tracking disabled by browser\'s DoNotTrack' },
'err-domain': { level: 'info', text: 'Tracking is disabled for this domain because it is not in the allowed domain config.' },
'err-id': { level: 'error', text: '`id` is missing or incorrectly configured. Check config.' },
'err-host': { level: 'error', text: '`host` is missing or incorrectly configured. Check config.' },
Expand All @@ -22,9 +22,6 @@ const warnings: Record<ErrorId, ErrorObj> = {
'err-event-name': { level: 'warn', text: 'A function/directive event was fired without a name. `#unknown-event` will be used as the event name.' },
};

// eslint-disable-next-line n/prefer-global/process
const envIsProd = process.env.NODE_ENV === 'production';

function detective(id: ErrorId, raw?: any) {
const { level, text } = warnings[id];
// eslint-disable-next-line no-console
Expand All @@ -33,4 +30,4 @@ function detective(id: ErrorId, raw?: any) {
raw && (console[level](raw));
}

export { detective, envIsProd };
export { detective };
18 changes: 9 additions & 9 deletions internal/directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,30 @@ const ATTR_NAME = 'savoryName';
const ATTR_DATA = 'savoryData';

type BindingValue = string | {
name: string
[k: string]: string | boolean | number
name: string;
[k: string]: string | boolean | number;
};

async function setAttributes(el: HTMLElement, value: BindingValue) {
let name = '';
let data = '';

if (typeof value === 'string') {
if (typeof value === 'string')
name = value;
} else {
else
try {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
if (typeof value !== 'object' || value === null || Array.isArray(value))
throw new TypeError(typeof value);
}

const { name: vName = '', ...rawData } = value;
const vData = Object.keys(rawData).length > 0
? JSON.stringify(rawData)
: '';
[name, data] = [vName, vData];
} catch (err) {
}
catch (err) {
helloDebugger.value('err-directive', `Provided ${typeof value}: ${value}`);
}
}

const attr = el.dataset;
[attr[ATTR_NAME], attr[ATTR_DATA]] = [name, data];
Expand All @@ -46,7 +45,8 @@ function getAttributes(el: HTMLElement) {

try {
data = JSON.parse(el.dataset[ATTR_DATA] || '');
} catch (error) {}
}
catch (error) {}

return { name, data };
}
Expand Down
34 changes: 17 additions & 17 deletions internal/types.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
interface BasicPayload {
url: string
website: string
hostname: string
screen: string
language: string
title: string
referrer: string
url: string;
website: string;
hostname: string;
screen: string;
language: string;
title: string;
referrer: string;
}

interface EventData {
[key: string]: string | number | boolean
[key: string]: string | number | boolean;
}

type EventPayloadPartial =
{
name: string
data?: EventData
name: string;
data?: EventData;
} | {
event_name: string
event_data?: EventData
event_name: string;
event_data?: EventData;
};

type EventPayload = BasicPayload & EventPayloadPartial;
Expand All @@ -29,14 +29,14 @@ type PayloadType = 'pageview' | 'event';
type PreflightResult = 'ssr' | 'id' | 'host' | 'domain' | 'dnt' | 'local' | true;

interface ServerPayload {
type: PayloadType
payload: ViewPayload | EventPayload
type: PayloadType;
payload: ViewPayload | EventPayload;
}

interface GetPayloadReturn {
payload: PartialPayload
pageUrl: string
pageReferrer: string
payload: PartialPayload;
pageUrl: string;
pageReferrer: string;
}

export type {
Expand Down
32 changes: 13 additions & 19 deletions internal/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import type {
PreflightResult,
ServerPayload,
} from './types';
import { detective, envIsProd } from './debug';
import { detective } from './debug';

function isValidString(str: unknown): str is string {
return typeof str === 'string' && str.trim() !== '';
}

function isValidHost(host: unknown): host is string {
try {
if (typeof host !== 'string') {
if (typeof host !== 'string')
return false;
}

const url = new URL(host);
return isValidString(url.host) && ['http:', 'https:'].includes(url.protocol);
} catch (error) {
}
catch (error) {
return false;
}
}
Expand Down Expand Up @@ -69,7 +70,7 @@ const umConfig = computed(() => {
});

const helloDebugger = computed(() => {
const enabled = envIsProd ? umConfig.value.debug : true;
const enabled = import.meta.env.DEV ? true : umConfig.value.debug;

type DetectiveParams = Parameters<typeof detective>;

Expand Down Expand Up @@ -100,44 +101,38 @@ const endpoint = computed(() => {
});

const preflight = computed((): PreflightResult => {
if (typeof window === 'undefined') {
if (typeof window === 'undefined')
return 'ssr';
}

const { ignoreDnt, id, host, ignoreLocal } = umConfig.value;

if (!isValidString(id)) {
if (!isValidString(id))
return 'id';
}

if (!host || !isValidHost(endpoint.value)) {
if (!host || !isValidHost(endpoint.value))
return 'host';
}

const {
location: { hostname },
navigator,
} = window;

if (ignoreLocal && hostname === 'localhost') {
if (ignoreLocal && hostname === 'localhost')
return 'local';
}

const domains = domainList.value;

if (domains && !domains.includes(hostname)) {
if (domains && !domains.includes(hostname))
return 'domain';
}

if (!ignoreDnt && [1, '1', 'yes'].includes(
navigator.doNotTrack
// @ts-expect-error `doNotTrack` might not exist on `window`
|| window.doNotTrack
// @ts-expect-error `msDoNotTrack` might not exist on `navigator`
|| navigator.msDoNotTrack,
)) {
))
return 'dnt';
}

return true;
});
Expand Down Expand Up @@ -182,9 +177,8 @@ async function collect(load: ServerPayload) {
body: JSON.stringify(load),
})
.then((res) => {
if (res && !res.ok) {
if (res && !res.ok)
helloDebugger.value('err-collect', res);
}
})
.catch((err) => {
helloDebugger.value('err-collect', err);
Expand Down
Loading