-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathga4.js
More file actions
executable file
·194 lines (180 loc) · 6.32 KB
/
Copy pathga4.js
File metadata and controls
executable file
·194 lines (180 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env node
const ACCESS_TOKEN = process.env.GA4_ACCESS_TOKEN
const DATA_API = 'https://analyticsdata.googleapis.com/v1beta'
const ADMIN_API = 'https://analyticsadmin.googleapis.com/v1beta'
const MP_URL = 'https://www.google-analytics.com/mp/collect'
if (!ACCESS_TOKEN) {
console.error(JSON.stringify({ error: 'GA4_ACCESS_TOKEN environment variable required' }))
process.exit(1)
}
async function api(method, baseUrl, path, body) {
if (args['dry-run']) {
return { _dry_run: true, method, url: `${baseUrl}${path}`, headers: { Authorization: '***', 'Content-Type': 'application/json' }, body: body || undefined }
}
const res = await fetch(`${baseUrl}${path}`, {
method,
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
})
const text = await res.text()
try {
return JSON.parse(text)
} catch {
return { status: res.status, body: text }
}
}
async function mpApi(measurementId, apiSecret, body) {
const params = new URLSearchParams({ measurement_id: measurementId, api_secret: apiSecret })
if (args['dry-run']) {
return { _dry_run: true, method: 'POST', url: `${MP_URL}?${new URLSearchParams({ measurement_id: measurementId, api_secret: '***' })}`, headers: { 'Content-Type': 'application/json' }, body: body || undefined }
}
const res = await fetch(`${MP_URL}?${params}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const text = await res.text()
if (!text) return { status: res.status, success: res.ok }
try {
return JSON.parse(text)
} catch {
return { status: res.status, body: text }
}
}
function parseArgs(args) {
const result = { _: [] }
for (let i = 0; i < args.length; i++) {
const arg = args[i]
if (arg.startsWith('--')) {
const key = arg.slice(2)
const next = args[i + 1]
if (next && !next.startsWith('--')) {
result[key] = next
i++
} else {
result[key] = true
}
} else {
result._.push(arg)
}
}
return result
}
const args = parseArgs(process.argv.slice(2))
const [cmd, sub, ...rest] = args._
async function main() {
let result
switch (cmd) {
case 'reports':
switch (sub) {
case 'run': {
const property = args.property
if (!property) { result = { error: '--property required' }; break }
const body = {
dateRanges: [{
startDate: args['start-date'] || '30daysAgo',
endDate: args['end-date'] || 'today',
}],
}
if (args.dimensions) {
body.dimensions = args.dimensions.split(',').map(d => ({ name: d.trim() }))
}
if (args.metrics) {
body.metrics = args.metrics.split(',').map(m => ({ name: m.trim() }))
}
result = await api('POST', DATA_API, `/properties/${property}:runReport`, body)
break
}
default:
result = { error: 'Unknown reports subcommand. Use: run' }
}
break
case 'realtime':
switch (sub) {
case 'run': {
const property = args.property
if (!property) { result = { error: '--property required' }; break }
const body = {}
if (args.dimensions) {
body.dimensions = args.dimensions.split(',').map(d => ({ name: d.trim() }))
}
if (args.metrics) {
body.metrics = args.metrics.split(',').map(m => ({ name: m.trim() }))
}
result = await api('POST', DATA_API, `/properties/${property}:runRealtimeReport`, body)
break
}
default:
result = { error: 'Unknown realtime subcommand. Use: run' }
}
break
case 'conversions':
switch (sub) {
case 'list': {
const property = args.property
if (!property) { result = { error: '--property required' }; break }
result = await api('GET', ADMIN_API, `/properties/${property}/conversionEvents`)
break
}
case 'create': {
const property = args.property
if (!property) { result = { error: '--property required' }; break }
if (!args['event-name']) { result = { error: '--event-name required' }; break }
result = await api('POST', ADMIN_API, `/properties/${property}/conversionEvents`, {
eventName: args['event-name'],
})
break
}
default:
result = { error: 'Unknown conversions subcommand. Use: list, create' }
}
break
case 'events':
switch (sub) {
case 'send': {
if (!args['measurement-id']) { result = { error: '--measurement-id required' }; break }
if (!args['api-secret']) { result = { error: '--api-secret required' }; break }
if (!args['client-id']) { result = { error: '--client-id required' }; break }
if (!args['event-name']) { result = { error: '--event-name required' }; break }
let eventParams = {}
if (args.params) {
try {
eventParams = JSON.parse(args.params)
} catch {
result = { error: 'Invalid JSON in --params' }; break
}
}
const body = {
client_id: args['client-id'],
events: [{
name: args['event-name'],
params: eventParams,
}],
}
result = await mpApi(args['measurement-id'], args['api-secret'], body)
break
}
default:
result = { error: 'Unknown events subcommand. Use: send' }
}
break
default:
result = {
error: 'Unknown command',
usage: {
reports: 'reports run --property <id> [--start-date <date>] [--end-date <date>] [--dimensions <dims>] [--metrics <metrics>]',
realtime: 'realtime run --property <id> [--dimensions <dims>] [--metrics <metrics>]',
conversions: 'conversions [list|create] --property <id> [--event-name <name>]',
events: 'events send --measurement-id <id> --api-secret <secret> --client-id <id> --event-name <name> [--params <json>]',
}
}
}
console.log(JSON.stringify(result, null, 2))
}
main().catch(err => {
console.error(JSON.stringify({ error: err.message }))
process.exit(1)
})