-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathupdate-analytics-vendors.js
213 lines (184 loc) · 5.35 KB
/
update-analytics-vendors.js
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/**
* External dependencies
*/
const { once } = require('events');
const fs = require('fs');
const readline = require('readline');
const stream = require('stream');
const { execSync } = require('child_process');
const axios = require('axios');
/**
* File path of the analytics vendors list.
*/
const ANALYTICS_VENDORS_FILE = 'includes/ecosystem-data/analytics-vendors.php';
class UpdateAnalyticsVendors {
/**
* Construct method.
*/
constructor() {
this.vendors = [];
this.content = '';
this.init();
}
/**
* Initialize the script.
*/
async init() {
await this.fetchData();
await this.extractVendors();
this.saveData();
}
/**
* Fetch analytics vendors.
*
* @return {Promise<void>}
*/
async fetchData() {
// Remote URL for analytics vendors.
const url =
'https://raw.githubusercontent.com/ampproject/amphtml/main/extensions/amp-analytics/analytics-vendors-list.md';
const response = await axios.get(url);
// A new readable stream for response data.
const bufferStream = new stream.PassThrough();
bufferStream.end(response.data);
// Create a readline interface to read the file line by line.
const fileContent = readline.createInterface({
input: bufferStream,
crlfDelay: Infinity,
});
this.content = fileContent;
}
/**
* Extract vendors from received data.
*
* @return {Promise<void>}
*/
async extractVendors() {
let commentFlag = false;
let vendorSlug = '';
let vendorTitle = '';
try {
this.content.on('line', (line) => {
// Check if the line is in a comment.
if (line.trim() === '<!--') {
commentFlag = true;
}
if (line.trim() === '-->') {
commentFlag = false;
}
// Check if line contains vendor title.
if (line.indexOf('###') === 0 && !commentFlag) {
vendorTitle = line.replace('###', '').trim();
}
// Check if line contains vendor slug.
if (
line.indexOf('Type attribute value:') === 0 &&
!commentFlag
) {
vendorSlug = line
.replace('Type attribute value:', '')
.trim();
}
// Populate vendors object.
if (vendorSlug && vendorTitle) {
const vendorSlugs = vendorSlug
.replace(/[^\w,\/-]/g, '')
.trim()
.split(',');
// Loop through multiple vendor slugs with same titles and append extra information to title.
vendorSlugs.forEach((slug) => {
if (vendorSlugs.indexOf(slug) === 0) {
/**
* Google Tag Manager will not be supported directly as it requires extra attributes.
* Also, A notice will be thrown if user enters `googletagmanager` as vendor slug.
*/
if (
slug === 'N/A' &&
vendorTitle === 'Google Tag Manager'
) {
return;
}
this.vendors[slug] = vendorTitle
.replace(/(<([^>]+)>)/gi, '')
.trim();
return;
}
slug = slug.trim();
/**
* Get extra information from vendor slug if the title is same.
* remove common prefixes from the vendor slug and convert to sentence case.
*/
const vendorInfo = slug
.replace(/.*_/g, '') // Remove common prefixes.
.replace(/([A-Z]+)/g, ' $1') // Add space before each capital letter.
.toLowerCase(); // Convert to lowercase.
// Strip HTML tags from title if any and append extra information.
this.vendors[slug] = vendorTitle
.replace(/(<([^>]+)>)/gi, '')
.concat(' (', vendorInfo, ')');
});
vendorSlug = '';
vendorTitle = '';
}
});
await once(this.content, 'close');
} catch (error) {
throw error;
}
}
/**
* Save data to JSON file.
*/
saveData() {
const phpcsDisables = [
'Squiz.Commenting.FileComment.Missing',
'WordPress.Arrays.ArrayIndentation',
'WordPress.WhiteSpace.PrecisionAlignment',
'WordPress.Arrays.ArrayDeclarationSpacing',
'Generic.WhiteSpace.DisallowSpaceIndent',
'Generic.Arrays.DisallowLongArraySyntax',
'Squiz.Commenting.FileComment.Missing',
'Generic.Files.EndFileNewline',
'WordPress.Arrays.MultipleStatementAlignment',
];
const phpcsDisableComments = phpcsDisables
.map((rule) => `// phpcs:disable ${rule}\n`)
.join('');
if (this.vendors) {
this.vendors = Object.entries(this.vendors).map(
([value, label]) => {
if ('googleanalytics' === value) {
label = 'Google Analytics (Legacy)';
}
return { value, label };
}
);
// Sort vendors by label.
this.vendors = this.vendors.sort((a, b) => {
return a.label.localeCompare(b.label);
});
let output = this.convertToPhpArray(this.vendors);
// Save vendors to JSON file.
output = `<?php ${phpcsDisableComments}\n// NOTICE: This file was auto-generated with: npm run update-analytics-vendors.\nreturn ${output};`;
fs.writeFileSync(ANALYTICS_VENDORS_FILE, output);
}
}
/**
* Convert JS object into PHP array variable.
*
* @param {Object} object An object that needs to convert into a PHP array.
* @return {string|null} PHP array in string.
*/
convertToPhpArray(object) {
if ('object' !== typeof object) {
return null;
}
const json = JSON.stringify(object);
const command = `php -r 'var_export( json_decode( file_get_contents( "php://stdin" ), true ) );'`;
let output = execSync(command, { input: json });
output = output.toString();
return output && 'NULL' !== output ? output : 'array()';
}
}
// eslint-disable-next-line no-new
new UpdateAnalyticsVendors();