forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiments.js
413 lines (372 loc) · 12.2 KB
/
experiments.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import '#polyfills';
import '#service/timer-impl';
import {Deferred} from '#core/data-structures/promise';
import {onDocumentReady} from '#core/document/ready';
import {isExperimentOn, toggleExperiment} from '#experiments';
import {listenOnce} from '#utils/event-helper';
import {devAssert, initLogConstructor, setReportError} from '#utils/log';
import {EXPERIMENTS} from './experiments-config';
import {SameSite_Enum, getCookie, setCookie} from '../../src/cookies';
import {reportError} from '../../src/error-reporting';
import {getMode} from '../../src/mode';
import {parseUrlDeprecated} from '../../src/url';
//TODO(@cramforce): For type. Replace with forward declaration.
initLogConstructor();
setReportError(reportError);
const COOKIE_MAX_AGE_DAYS = 180; // 6 month
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const COOKIE_MAX_AGE_MS = COOKIE_MAX_AGE_DAYS * MS_PER_DAY;
const RTV_COOKIE_MAX_AGE_MS = MS_PER_DAY / 2;
const RTV_PATTERN = /^\d{15}$/;
/**
* @typedef {{
* id: string,
* name: string,
* spec: string,
* cleanupIssue: string,
* }}
*/
let ExperimentDef;
/**
* These experiments are special because they use a different mechanism that is
* interpreted by the server to deliver a different version of the AMP
* JS libraries.
*/
const EXPERIMENTAL_CHANNEL_ID = 'experimental-channel';
const BETA_CHANNEL_ID = 'beta-channel';
const NIGHTLY_CHANNEL_ID = 'nightly-channel';
const RTV_CHANNEL_ID = 'rtv-channel';
/**
* The different states of the __Host-AMP_OPT_IN cookie.
*/
const AMP_OPT_IN_COOKIE = {
DISABLED: '0',
EXPERIMENTAL: 'experimental',
BETA: 'beta',
NIGHTLY: 'nightly',
};
/** @const {!Array<!ExperimentDef>} */
const CHANNELS = [
{
id: EXPERIMENTAL_CHANNEL_ID,
name: 'AMP Experimental Channel (more info)',
spec: 'https://github.com/ampproject/amphtml/blob/main/docs/release-schedule.md#amp-experimental-and-beta-channels',
},
{
id: BETA_CHANNEL_ID,
name: 'AMP Beta Channel (more info)',
spec: 'https://github.com/ampproject/amphtml/blob/main/docs/release-schedule.md#amp-experimental-and-beta-channels',
},
{
id: NIGHTLY_CHANNEL_ID,
name: 'AMP Nightly Channel (more info)',
spec: 'https://github.com/ampproject/amphtml/blob/main/docs/release-schedule.md#amp-experimental-and-beta-channels',
},
];
if (getMode().localDev) {
EXPERIMENTS.forEach((experiment) => {
devAssert(
experiment.cleanupIssue,
`experiment ${experiment.name} must have a \`cleanupIssue\` field.`
);
});
}
/**
* Builds the expriments table.
*/
function build() {
const {host} = window.location;
const subdomain = document.getElementById('subdomain');
subdomain.textContent = host;
// #redirect contains UI that generates a subdomain experiments page link
// given a "google.com/amp/..." viewer URL.
const redirect = document.getElementById('redirect');
const input = redirect.querySelector('input');
const button = redirect.querySelector('button');
const anchor = redirect.querySelector('a');
button.addEventListener('click', function () {
let urlString = input.value.trim();
// Avoid protocol-less urlString from being parsed as a relative URL.
const hasProtocol = /^https?:\/\//.test(urlString);
if (!hasProtocol) {
urlString = 'https://' + urlString;
}
const url = parseUrlDeprecated(urlString);
if (url) {
const subdomain = url.hostname.replace(/\./g, '-');
const href = `https://${subdomain}.cdn.ampproject.org/experiments.html`;
anchor.href = href;
anchor.textContent = href;
}
});
const channelsTable = document.getElementById('channels-table');
CHANNELS.forEach(function (experiment) {
channelsTable.appendChild(buildExperimentRow(experiment));
});
const experimentsTable = document.getElementById('experiments-table');
EXPERIMENTS.forEach(function (experiment) {
experimentsTable.appendChild(buildExperimentRow(experiment));
});
if (host === 'cdn.ampproject.org') {
const experimentsDesc = document.getElementById('experiments-desc');
experimentsDesc.setAttribute('hidden', '');
experimentsTable.setAttribute('hidden', '');
} else {
redirect.setAttribute('hidden', '');
}
const rtvInput = document.getElementById('rtv');
const rtvButton = document.getElementById('rtv-submit');
rtvInput.addEventListener('input', () => {
rtvButton.disabled = rtvInput.value && !RTV_PATTERN.test(rtvInput.value);
rtvButton.textContent = rtvInput.value ? 'opt-in' : 'opt-out';
});
rtvButton.addEventListener('click', () => {
if (!rtvInput.value) {
showConfirmation_(
'Do you really want to opt out of RTV?',
setAmpOptInCookie_.bind(null, AMP_OPT_IN_COOKIE.DISABLED)
);
} else if (RTV_PATTERN.test(rtvInput.value)) {
showConfirmation_(
`Do you really want to opt in to RTV ${rtvInput.value}?`,
setAmpOptInCookie_.bind(null, rtvInput.value)
);
}
});
if (isExperimentOn_(RTV_CHANNEL_ID)) {
rtvInput.value = getCookie(window, '__Host-AMP_OPT_IN');
rtvInput.dispatchEvent(new Event('input'));
document.getElementById('rtv-details').open = true;
}
}
/**
* Builds one row in the channel or experiments table.
* @param {!ExperimentDef} experiment
* @return {*} TODO(#23582): Specify return type
*/
function buildExperimentRow(experiment) {
const tr = document.createElement('tr');
tr.id = 'exp-tr-' + experiment.id;
const tdId = document.createElement('td');
tdId.appendChild(buildLinkMaybe(experiment.id, experiment.spec));
tr.appendChild(tdId);
const tdName = document.createElement('td');
tdName.appendChild(buildLinkMaybe(experiment.name, experiment.spec));
tr.appendChild(tdName);
const tdOn = document.createElement('td');
tdOn.classList.add('button-cell');
tr.appendChild(tdOn);
const button = document.createElement('button');
tdOn.appendChild(button);
const buttonOn = document.createElement('div');
buttonOn.classList.add('on');
buttonOn.textContent = 'On';
button.appendChild(buttonOn);
const buttonDefault = document.createElement('div');
buttonDefault.classList.add('default');
buttonDefault.textContent = 'Default on';
button.appendChild(buttonDefault);
const buttonOff = document.createElement('div');
buttonOff.classList.add('off');
buttonOff.textContent = 'Off';
button.appendChild(buttonOff);
button.addEventListener(
'click',
toggleExperiment_.bind(null, experiment.id, experiment.name, undefined)
);
return tr;
}
/**
* If link is available, builds the anchor. Otherwise, it'd return a basic span.
* @param {string} text
* @param {?string} link
* @return {!Element}
*/
function buildLinkMaybe(text, link) {
let element;
if (link) {
element = document.createElement('a');
element.setAttribute('href', link);
element.setAttribute('target', '_blank');
} else {
element = document.createElement('span');
}
element.textContent = text;
return element;
}
/**
* Updates states of all experiments in the table.
*/
function update() {
CHANNELS.concat(EXPERIMENTS).forEach(function (experiment) {
updateExperimentRow(experiment);
});
}
/**
* Updates the state of a single experiment.
* @param {!ExperimentDef} experiment
*/
function updateExperimentRow(experiment) {
const tr = document.getElementById('exp-tr-' + experiment.id);
if (!tr) {
return;
}
let state = isExperimentOn_(experiment.id) ? 1 : 0;
if (self.AMP_CONFIG[experiment.id]) {
state = 'default';
}
tr.setAttribute('data-on', state);
}
/**
* Returns whether the experiment is on or off.
* @param {string} id
* @return {boolean}
*/
function isExperimentOn_(id) {
const optInCookieValue = getCookie(window, '__Host-AMP_OPT_IN');
switch (id) {
case EXPERIMENTAL_CHANNEL_ID:
return optInCookieValue == AMP_OPT_IN_COOKIE.EXPERIMENTAL;
case BETA_CHANNEL_ID:
return optInCookieValue == AMP_OPT_IN_COOKIE.BETA;
case NIGHTLY_CHANNEL_ID:
return optInCookieValue == AMP_OPT_IN_COOKIE.NIGHTLY;
case RTV_CHANNEL_ID:
return RTV_PATTERN.test(optInCookieValue);
default:
return isExperimentOn(window, /*OK*/ id);
}
}
/**
* Opts in to / out of the pre-release channels or a specific RTV by setting the
* __Host-AMP_OPT_IN cookie.
* @param {string} cookieState One of the AMP_OPT_IN_COOKIE enum values, or a
* 15-digit RTV.
*/
function setAmpOptInCookie_(cookieState) {
let validUntil = 0;
if (RTV_PATTERN.test(cookieState)) {
validUntil = Date.now() + RTV_COOKIE_MAX_AGE_MS;
} else if (cookieState != AMP_OPT_IN_COOKIE.DISABLED) {
validUntil = Date.now() + COOKIE_MAX_AGE_MS;
}
const cookieOptions = {
allowOnProxyOrigin: true,
// Make sure the cookie is available for the script loads coming from
// other domains. Chrome's default of LAX would otherwise prevent it
// from being sent.
sameSite: SameSite_Enum.NONE,
secure: true,
};
setCookie(
window,
'__Host-AMP_OPT_IN',
cookieState,
validUntil,
cookieOptions
);
// Reflect default experiment state.
self.location.reload();
}
/**
* Toggles the experiment.
* @param {string} id
* @param {string} name
* @param {boolean=} opt_on
*/
function toggleExperiment_(id, name, opt_on) {
const currentlyOn = isExperimentOn_(id);
const on = opt_on === undefined ? !currentlyOn : opt_on;
// Protect against accidental choice.
const confirmMessage = on
? 'Do you really want to activate the AMP experiment?'
: 'Do you really want to deactivate the AMP experiment?';
showConfirmation_(`${confirmMessage}: "${name}"`, () => {
switch (id) {
case EXPERIMENTAL_CHANNEL_ID:
setAmpOptInCookie_(
on ? AMP_OPT_IN_COOKIE.EXPERIMENTAL : AMP_OPT_IN_COOKIE.DISABLED
);
break;
case BETA_CHANNEL_ID:
setAmpOptInCookie_(
on ? AMP_OPT_IN_COOKIE.BETA : AMP_OPT_IN_COOKIE.DISABLED
);
break;
case NIGHTLY_CHANNEL_ID:
setAmpOptInCookie_(
on ? AMP_OPT_IN_COOKIE.NIGHTLY : AMP_OPT_IN_COOKIE.DISABLED
);
break;
default:
toggleExperiment(window, id, on);
}
update();
});
}
/**
* Shows confirmation and calls callback if it's approved.
* @param {string} message
* @param {function()} callback
*/
function showConfirmation_(message, callback) {
const container = devAssert(document.getElementById('popup-container'));
const messageElement = devAssert(document.getElementById('popup-message'));
const confirmButton = devAssert(document.getElementById('popup-button-ok'));
const cancelButton = devAssert(
document.getElementById('popup-button-cancel')
);
const unlistenSet = [];
const closePopup = (affirmative) => {
container.classList.remove('show');
unlistenSet.forEach((unlisten) => unlisten());
if (affirmative) {
callback();
}
};
messageElement.textContent = message;
unlistenSet.push(listenOnce(confirmButton, 'click', () => closePopup(true)));
unlistenSet.push(listenOnce(cancelButton, 'click', () => closePopup(false)));
container.classList.add('show');
}
/**
* Loads the AMP_CONFIG objects from whatever the v0.js is that the user has
* (depends on whether they opted into one of the pre-release channels or into a
* specific RTV) so that experiment state can reflect the default activated
* experiments.
* @return {Promise<JSON>} the active AMP_CONFIG, parsed as a JSON object
*/
function getAmpConfig() {
const deferred = new Deferred();
const {promise, reject, resolve} = deferred;
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
resolve(xhr.responseText);
});
xhr.addEventListener('error', () => {
reject(new Error(xhr.statusText));
});
// Cache bust, so we immediately reflect cookie changes.
xhr.open('GET', '/v0.js?' + Math.random(), true);
xhr.send(null);
return promise
.then((text) => {
const match = text.match(/self\.AMP_CONFIG=(\{.+?\})/);
if (!match) {
throw new Error("Can't find AMP_CONFIG in: " + text);
}
// Setting global var to make standard experiment code just work.
return (self.AMP_CONFIG = JSON.parse(match[1]));
})
.catch((error) => {
console./*OK*/ error('Error fetching AMP_CONFIG', error);
return {};
});
}
// Start up.
getAmpConfig().then(() => {
onDocumentReady(document, () => {
build();
update();
});
});