@github/hydro-analytics-client 2.3.2 → 2.4.0

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.
@@ -0,0 +1,30 @@
1
+ export declare type Context = Record<string, string>;
2
+ export interface AnalyticsClientOptions {
3
+ collectorUrl: string;
4
+ clientId?: string;
5
+ baseContext?: Context;
6
+ maxBatchSize?: number;
7
+ idleTimeout?: number;
8
+ }
9
+ export declare class AnalyticsClient {
10
+ readonly options: AnalyticsClientOptions;
11
+ private eventBatch;
12
+ private idleCallbackId;
13
+ private fallbackTimerId;
14
+ constructor(options: AnalyticsClientOptions);
15
+ get collectorUrl(): string;
16
+ get clientId(): string;
17
+ private get maxBatchSize();
18
+ private get idleTimeout();
19
+ private createEvent;
20
+ sendPageView(context?: Context): void;
21
+ sendEvent(type: string, context: Context): void;
22
+ sendBatchedEvent(type: string, context: Context): void;
23
+ flushBatch(): void;
24
+ destroy(): void;
25
+ private scheduleFlush;
26
+ private cancelScheduledFlush;
27
+ private onVisibilityChange;
28
+ private boundFlush;
29
+ private send;
30
+ }
@@ -0,0 +1,140 @@
1
+ import { getRequestContext } from './request-context.js';
2
+ import { getMarketingContext } from './marketing-context.js';
3
+ import { getOrCreateClientId } from './client-id.js';
4
+ export class AnalyticsClient {
5
+ constructor(options) {
6
+ this.options = options;
7
+ this.eventBatch = [];
8
+ this.idleCallbackId = null;
9
+ this.fallbackTimerId = null;
10
+ this.onVisibilityChange = () => {
11
+ if (document.visibilityState === 'hidden') {
12
+ this.flushBatch();
13
+ }
14
+ };
15
+ this.boundFlush = () => this.flushBatch();
16
+ if (typeof document !== 'undefined') {
17
+ document.addEventListener('visibilitychange', this.onVisibilityChange);
18
+ }
19
+ if (typeof window !== 'undefined') {
20
+ window.addEventListener('pagehide', this.boundFlush);
21
+ }
22
+ }
23
+ get collectorUrl() {
24
+ return this.options.collectorUrl;
25
+ }
26
+ get clientId() {
27
+ if (this.options.clientId) {
28
+ return this.options.clientId;
29
+ }
30
+ return getOrCreateClientId();
31
+ }
32
+ get maxBatchSize() {
33
+ return this.options.maxBatchSize ?? 10;
34
+ }
35
+ get idleTimeout() {
36
+ return this.options.idleTimeout ?? 1000;
37
+ }
38
+ createEvent(context) {
39
+ return {
40
+ page: location.href,
41
+ title: document.title,
42
+ context: {
43
+ ...this.options.baseContext,
44
+ ...getMarketingContext(),
45
+ ...context
46
+ }
47
+ };
48
+ }
49
+ sendPageView(context) {
50
+ const pageView = this.createEvent(context);
51
+ this.send({ page_views: [pageView] });
52
+ }
53
+ sendEvent(type, context) {
54
+ const event = {
55
+ ...this.createEvent(context),
56
+ type
57
+ };
58
+ this.send({ events: [event] });
59
+ }
60
+ sendBatchedEvent(type, context) {
61
+ const event = {
62
+ ...this.createEvent(context),
63
+ type
64
+ };
65
+ this.eventBatch.push(event);
66
+ if (this.eventBatch.length >= this.maxBatchSize) {
67
+ this.flushBatch();
68
+ }
69
+ else {
70
+ this.scheduleFlush();
71
+ }
72
+ }
73
+ flushBatch() {
74
+ if (this.eventBatch.length === 0)
75
+ return;
76
+ this.cancelScheduledFlush();
77
+ const events = this.eventBatch;
78
+ this.eventBatch = [];
79
+ this.send({ events });
80
+ }
81
+ destroy() {
82
+ this.flushBatch();
83
+ if (typeof document !== 'undefined') {
84
+ document.removeEventListener('visibilitychange', this.onVisibilityChange);
85
+ }
86
+ if (typeof window !== 'undefined') {
87
+ window.removeEventListener('pagehide', this.boundFlush);
88
+ }
89
+ }
90
+ scheduleFlush() {
91
+ if (this.idleCallbackId !== null || this.fallbackTimerId !== null)
92
+ return;
93
+ if (typeof requestIdleCallback === 'function') {
94
+ this.idleCallbackId = requestIdleCallback(this.boundFlush, {
95
+ timeout: this.idleTimeout
96
+ });
97
+ }
98
+ else {
99
+ this.fallbackTimerId = setTimeout(this.boundFlush, this.idleTimeout);
100
+ }
101
+ }
102
+ cancelScheduledFlush() {
103
+ if (this.idleCallbackId !== null) {
104
+ if (typeof cancelIdleCallback === 'function') {
105
+ cancelIdleCallback(this.idleCallbackId);
106
+ }
107
+ this.idleCallbackId = null;
108
+ }
109
+ if (this.fallbackTimerId !== null) {
110
+ clearTimeout(this.fallbackTimerId);
111
+ this.fallbackTimerId = null;
112
+ }
113
+ }
114
+ send({ page_views, events }) {
115
+ const payload = {
116
+ client_id: this.clientId,
117
+ page_views,
118
+ events,
119
+ request_context: getRequestContext()
120
+ };
121
+ const body = JSON.stringify(payload);
122
+ try {
123
+ if (navigator.sendBeacon) {
124
+ navigator.sendBeacon(this.collectorUrl, body);
125
+ return;
126
+ }
127
+ }
128
+ catch {
129
+ }
130
+ fetch(this.collectorUrl, {
131
+ method: 'POST',
132
+ cache: 'no-cache',
133
+ headers: {
134
+ 'Content-Type': 'application/json'
135
+ },
136
+ body,
137
+ keepalive: false
138
+ });
139
+ }
140
+ }
@@ -0,0 +1 @@
1
+ export declare function getOrCreateClientId(): string;
@@ -0,0 +1,50 @@
1
+ let fallbackClientId;
2
+ function generateClientId() {
3
+ return `${Math.round(Math.random() * (Math.pow(2, 31) - 1))}.${Math.round(Date.now() / 1000)}`;
4
+ }
5
+ function setClientIdCookie(clientId) {
6
+ const value = `GH1.1.${clientId}`;
7
+ const now = Date.now();
8
+ const expires = new Date(now + 1 * 365 * 86400 * 1000).toUTCString();
9
+ let { domain } = document;
10
+ if (domain.endsWith('.github.com')) {
11
+ domain = 'github.com';
12
+ }
13
+ document.cookie = `_octo=${value}; expires=${expires}; path=/; domain=${domain}; secure; samesite=lax`;
14
+ }
15
+ function getClientIdFromCookie() {
16
+ let clientId;
17
+ const cookie = document.cookie;
18
+ const matches = cookie.match(/_octo=([^;]+)/g);
19
+ if (!matches) {
20
+ return;
21
+ }
22
+ let latestVersion = [0, 0];
23
+ for (const match of matches) {
24
+ const [, value] = match.split('=');
25
+ const [, version, ...clientIdPortions] = value.split('.');
26
+ const semanticVersion = version.split('-').map(Number);
27
+ if (semanticVersion > latestVersion) {
28
+ latestVersion = semanticVersion;
29
+ clientId = clientIdPortions.join('.');
30
+ }
31
+ }
32
+ return clientId;
33
+ }
34
+ export function getOrCreateClientId() {
35
+ try {
36
+ const existingId = getClientIdFromCookie();
37
+ if (existingId) {
38
+ return existingId;
39
+ }
40
+ const clientId = generateClientId();
41
+ setClientIdCookie(clientId);
42
+ return clientId;
43
+ }
44
+ catch (_) {
45
+ if (!fallbackClientId) {
46
+ fallbackClientId = generateClientId();
47
+ }
48
+ return fallbackClientId;
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ export * from './analytics-client.js';
2
+ export * from './meta-helpers.js';
3
+ export * from './client-id.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './analytics-client.js';
2
+ export * from './meta-helpers.js';
3
+ export * from './client-id.js';
@@ -0,0 +1,10 @@
1
+ interface MarketingContext {
2
+ scid?: string;
3
+ utm_source?: string;
4
+ utm_medium?: string;
5
+ utm_term?: string;
6
+ utm_campaign?: string;
7
+ utm_content?: string;
8
+ }
9
+ export declare function getMarketingContext(): MarketingContext;
10
+ export {};
@@ -0,0 +1,17 @@
1
+ const MARKETING_PARAMS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'scid'];
2
+ export function getMarketingContext() {
3
+ const marketingContext = {};
4
+ try {
5
+ const urlParams = new URLSearchParams(window.location.search);
6
+ for (const [key, value] of urlParams) {
7
+ const normalizedKey = key.toLowerCase();
8
+ if (MARKETING_PARAMS.includes(normalizedKey)) {
9
+ marketingContext[normalizedKey] = value;
10
+ }
11
+ }
12
+ return marketingContext;
13
+ }
14
+ catch (e) {
15
+ return {};
16
+ }
17
+ }
@@ -0,0 +1,2 @@
1
+ import { AnalyticsClientOptions } from './analytics-client.js';
2
+ export declare function getOptionsFromMeta(prefix?: string): AnalyticsClientOptions;
@@ -0,0 +1,22 @@
1
+ export function getOptionsFromMeta(prefix = 'ha') {
2
+ let collectorUrl;
3
+ const baseContext = {};
4
+ const metaTags = document.head.querySelectorAll(`meta[name^="${prefix}-"]`);
5
+ for (const meta of Array.from(metaTags)) {
6
+ const { name: originalName, content } = meta;
7
+ const name = originalName.replace(`${prefix}-`, '').replace(/-/g, '_');
8
+ if (name === 'url') {
9
+ collectorUrl = content;
10
+ }
11
+ else {
12
+ baseContext[name] = content;
13
+ }
14
+ }
15
+ if (!collectorUrl) {
16
+ throw new Error(`AnalyticsClient ${prefix}-url meta tag not found`);
17
+ }
18
+ return {
19
+ collectorUrl,
20
+ ...(Object.keys(baseContext).length > 0 ? { baseContext } : {})
21
+ };
22
+ }
@@ -0,0 +1,11 @@
1
+ export interface RequestContext {
2
+ referrer?: string;
3
+ user_agent: string;
4
+ screen_resolution: string;
5
+ browser_resolution: string;
6
+ browser_languages: string;
7
+ pixel_ratio: number;
8
+ timestamp: number;
9
+ tz_seconds: number;
10
+ }
11
+ export declare function getRequestContext(): RequestContext;
@@ -0,0 +1,69 @@
1
+ function getReferrer() {
2
+ let referrer;
3
+ try {
4
+ referrer = window.top.document.referrer;
5
+ }
6
+ catch (error) {
7
+ if (window.parent) {
8
+ try {
9
+ referrer = window.parent.document.referrer;
10
+ }
11
+ catch (_) {
12
+ }
13
+ }
14
+ }
15
+ if (referrer === '') {
16
+ referrer = document.referrer;
17
+ }
18
+ return referrer;
19
+ }
20
+ function getScreenResolution() {
21
+ try {
22
+ return `${screen.width}x${screen.height}`;
23
+ }
24
+ catch (error) {
25
+ return 'unknown';
26
+ }
27
+ }
28
+ function getBrowserResolution() {
29
+ let height = 0;
30
+ let width = 0;
31
+ try {
32
+ if (typeof window.innerWidth === 'number') {
33
+ width = window.innerWidth;
34
+ height = window.innerHeight;
35
+ }
36
+ else if (document.documentElement != null && document.documentElement.clientWidth != null) {
37
+ width = document.documentElement.clientWidth;
38
+ height = document.documentElement.clientHeight;
39
+ }
40
+ else if (document.body != null && document.body.clientWidth != null) {
41
+ width = document.body.clientWidth;
42
+ height = document.body.clientHeight;
43
+ }
44
+ return `${width}x${height}`;
45
+ }
46
+ catch (error) {
47
+ return 'unknown';
48
+ }
49
+ }
50
+ function getBrowserLanguages() {
51
+ if (navigator.languages) {
52
+ return navigator.languages.join(',');
53
+ }
54
+ else {
55
+ return navigator.language || '';
56
+ }
57
+ }
58
+ export function getRequestContext() {
59
+ return {
60
+ referrer: getReferrer(),
61
+ user_agent: navigator.userAgent,
62
+ screen_resolution: getScreenResolution(),
63
+ browser_resolution: getBrowserResolution(),
64
+ browser_languages: getBrowserLanguages(),
65
+ pixel_ratio: window.devicePixelRatio,
66
+ timestamp: Date.now(),
67
+ tz_seconds: new Date().getTimezoneOffset() * -60
68
+ };
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@github/hydro-analytics-client",
3
- "version": "2.3.2",
3
+ "version": "2.4.0",
4
4
  "description": "Client SDK for Hydro Analytics",
5
5
  "main": "./dist/index.js",
6
6
  "module": "dist/index.js",