Skip to content

Commit

Permalink
Support for offlineGoogleAnalytics config in workbox-build config (#1610
Browse files Browse the repository at this point in the history
)

* Support for offlineGoogleAnalytics: true

* Fixing a test.

* Support for complex config.
  • Loading branch information
jeffposnick authored Aug 22, 2018
1 parent b723291 commit f2e3165
Show file tree
Hide file tree
Showing 11 changed files with 225 additions and 11 deletions.
4 changes: 4 additions & 0 deletions infra/testing/validator/service-worker-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ function setupSpiesAndContext() {
expiration: {
Plugin: CacheExpirationPlugin,
},
googleAnalytics: {
initialize: sinon.spy(),
},
precaching: {
precacheAndRoute: sinon.spy(),
suppressWarnings: sinon.spy(),
Expand Down Expand Up @@ -61,6 +64,7 @@ function setupSpiesAndContext() {
cacheExpirationPlugin: cacheExpirationPluginSpy,
cacheFirst: workbox.strategies.cacheFirst,
clientsClaim: workbox.clientsClaim,
googleAnalyticsInitialize: workbox.googleAnalytics.initialize,
networkFirst: workbox.strategies.networkFirst,
precacheAndRoute: workbox.precaching.precacheAndRoute,
registerNavigationRoute: workbox.routing.registerNavigationRoute,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ module.exports = baseSchema.keys({
navigateFallback: joi.string().default(defaults.navigateFallback),
navigateFallbackBlacklist: joi.array().items(regExpObject),
navigateFallbackWhitelist: joi.array().items(regExpObject),
offlineGoogleAnalytics: joi.alternatives().try(joi.boolean(), joi.object())
.default(defaults.offlineGoogleAnalytics),
runtimeCaching: joi.array().items(joi.object().keys({
urlPattern: [regExpObject, joi.string()],
handler: [joi.func(), joi.string().valid(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module.exports = {
injectionPointRegexp: /(\.precacheAndRoute\()\s*\[\s*\]\s*(\)|,)/,
maximumFileSizeToCacheInBytes: 2 * 1024 * 1024,
navigateFallback: undefined,
offlineGoogleAnalytics: false,
purgeOnQuotaError: false,
skipWaiting: false,
};
15 changes: 15 additions & 0 deletions packages/workbox-build/src/lib/populate-sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const swTemplate = require('../templates/sw-template');

const errors = require('./errors');
const runtimeCachingConverter = require('./runtime-caching-converter');
const stringifyWithoutComments = require('./stringify-without-comments');

module.exports = ({
cacheId,
Expand All @@ -31,6 +32,7 @@ module.exports = ({
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
workboxSWImport,
Expand All @@ -54,6 +56,18 @@ module.exports = ({
);
}

let offlineAnalyticsConfigString;
if (offlineGoogleAnalytics) {
// If offlineGoogleAnalytics is a truthy value, we need to convert it to the
// format expected by the template.
offlineAnalyticsConfigString = offlineGoogleAnalytics === true ?
// If it's the literal value true, then use an empty config string.
'{}' :
// Otherwise, convert the config object into a more complex string, taking
// into account the fact that functions might need to be stringified.
stringifyWithoutComments(offlineGoogleAnalytics);
}

try {
const populatedTemplate = template(swTemplate)({
cacheId,
Expand All @@ -64,6 +78,7 @@ module.exports = ({
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineAnalyticsConfigString,
precacheOptionsString,
skipWaiting,
runtimeCaching: runtimeCachingConverter(runtimeCaching),
Expand Down
14 changes: 4 additions & 10 deletions packages/workbox-build/src/lib/runtime-caching-converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@
*/

const ol = require('common-tags').oneLine;
const objectStringify = require('stringify-object');
const stripComments = require('strip-comments');
const errors = require('./errors');

const errors = require('./errors');
const stringifyWithoutComments = require('./stringify-without-comments');

/**
* Given a set of options that configures `sw-toolbox`'s behavior, convert it
Expand All @@ -33,13 +32,8 @@ const errors = require('./errors');
function getOptionsString(options = {}) {
let plugins = [];
if (options.plugins) {
// Using libs because JSON.stringify won't handle functions
plugins = options.plugins.map((plugin) =>
objectStringify(plugin, {
transform: (_obj, _prop, str) => stripComments(str),
})
);

// Using libs because JSON.stringify won't handle functions.
plugins = options.plugins.map(stringifyWithoutComments);
delete options.plugins;
}

Expand Down
24 changes: 24 additions & 0 deletions packages/workbox-build/src/lib/stringify-without-comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Copyright 2018 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const objectStringify = require('stringify-object');
const stripComments = require('strip-comments');

module.exports = (obj) => {
return objectStringify(obj, {
transform: (_obj, _prop, str) => stripComments(str),
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ module.exports = async ({
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
swDest,
Expand All @@ -56,6 +57,7 @@ module.exports = async ({
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
workboxSWImport,
Expand Down
4 changes: 3 additions & 1 deletion packages/workbox-build/src/templates/sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,6 @@ if (Array.isArray(self.__precacheManifest)) {
<% if (navigateFallbackBlacklist) { %>blacklist: [<%= navigateFallbackBlacklist %>],<% } %>
}<% } %>);<% } %>
<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>`;
<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>
<% if (offlineAnalyticsConfigString) { %>workbox.googleAnalytics.initialize(<%= offlineAnalyticsConfigString %>);<% } %>`;
39 changes: 39 additions & 0 deletions test/workbox-build/node/entry-points/generate-sw-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe(`[workbox-build] entry-points/generate-sw-string.js (End to End)`, func
'modifyUrlPrefix',
'navigateFallback',
'navigateFallbackWhitelist',
'offlineGoogleAnalytics',
'runtimeCaching',
'skipWaiting',
'templatedUrls',
Expand Down Expand Up @@ -231,6 +232,44 @@ describe(`[workbox-build] entry-points/generate-sw-string.js (End to End)`, func
}]],
}});
});

it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to true`, async function() {
const options = Object.assign({}, BASE_OPTIONS, {
offlineGoogleAnalytics: true,
});

const {swString, warnings} = await generateSWString(options);
expect(warnings).to.be.empty;
await validateServiceWorkerRuntime({swString, expectedMethodCalls: {
importScripts: [[...DEFAULT_IMPORT_SCRIPTS]],
suppressWarnings: [[]],
precacheAndRoute: [[[], {}]],
googleAnalyticsInitialize: [[{}]],
}});
});

it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to a config`, async function() {
const options = Object.assign({}, BASE_OPTIONS, {
offlineGoogleAnalytics: {
parameterOverrides: {
cd1: 'offline',
},
},
});

const {swString, warnings} = await generateSWString(options);
expect(warnings).to.be.empty;
await validateServiceWorkerRuntime({swString, expectedMethodCalls: {
importScripts: [[...DEFAULT_IMPORT_SCRIPTS]],
suppressWarnings: [[]],
precacheAndRoute: [[[], {}]],
googleAnalyticsInitialize: [[{
parameterOverrides: {
cd1: 'offline',
},
}]],
}});
});
});

describe(`[workbox-build] behavior with 'runtimeCaching'`, function() {
Expand Down
83 changes: 83 additions & 0 deletions test/workbox-build/node/entry-points/generate-sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe(`[workbox-build] entry-points/generate-sw.js (End to End)`, function()
'manifestTransforms',
'maximumFileSizeToCacheInBytes',
'modifyUrlPrefix',
'offlineGoogleAnalytics',
'navigateFallback',
'navigateFallbackWhitelist',
'runtimeCaching',
Expand Down Expand Up @@ -462,6 +463,88 @@ describe(`[workbox-build] entry-points/generate-sw.js (End to End)`, function()
}], {}]],
}});
});

it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to true`, async function() {
const swDest = tempy.file();
const options = Object.assign({}, BASE_OPTIONS, {
swDest,
offlineGoogleAnalytics: true,
});

const {count, size, warnings} = await generateSW(options);
expect(warnings).to.be.empty;
expect(count).to.eql(6);
expect(size).to.eql(2421);
await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: {
importScripts: [[WORKBOX_SW_CDN_URL]],
suppressWarnings: [[]],
precacheAndRoute: [[[{
url: 'index.html',
revision: '3883c45b119c9d7e9ad75a1b4a4672ac',
}, {
url: 'page-1.html',
revision: '544658ab25ee8762dc241e8b1c5ed96d',
}, {
url: 'page-2.html',
revision: 'a3a71ce0b9b43c459cf58bd37e911b74',
}, {
url: 'styles/stylesheet-1.css',
revision: '934823cbc67ccf0d67aa2a2eeb798f12',
}, {
url: 'styles/stylesheet-2.css',
revision: '884f6853a4fc655e4c2dc0c0f27a227c',
}, {
url: 'webpackEntry.js',
revision: 'd41d8cd98f00b204e9800998ecf8427e',
}], {}]],
googleAnalyticsInitialize: [[{}]],
}});
});

it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to a config`, async function() {
const swDest = tempy.file();
const options = Object.assign({}, BASE_OPTIONS, {
swDest,
offlineGoogleAnalytics: {
parameterOverrides: {
cd1: 'offline',
},
},
});

const {count, size, warnings} = await generateSW(options);
expect(warnings).to.be.empty;
expect(count).to.eql(6);
expect(size).to.eql(2421);
await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: {
importScripts: [[WORKBOX_SW_CDN_URL]],
suppressWarnings: [[]],
precacheAndRoute: [[[{
url: 'index.html',
revision: '3883c45b119c9d7e9ad75a1b4a4672ac',
}, {
url: 'page-1.html',
revision: '544658ab25ee8762dc241e8b1c5ed96d',
}, {
url: 'page-2.html',
revision: 'a3a71ce0b9b43c459cf58bd37e911b74',
}, {
url: 'styles/stylesheet-1.css',
revision: '934823cbc67ccf0d67aa2a2eeb798f12',
}, {
url: 'styles/stylesheet-2.css',
revision: '884f6853a4fc655e4c2dc0c0f27a227c',
}, {
url: 'webpackEntry.js',
revision: 'd41d8cd98f00b204e9800998ecf8427e',
}], {}]],
googleAnalyticsInitialize: [[{
parameterOverrides: {
cd1: 'offline',
},
}]],
}});
});
});

describe(`[workbox-build] behavior with 'runtimeCaching'`, function() {
Expand Down
48 changes: 48 additions & 0 deletions test/workbox-build/node/lib/populate-sw-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
navigateFallback: undefined,
navigateFallbackBlacklist: undefined,
navigateFallbackWhitelist: undefined,
offlineAnalyticsConfigString: undefined,
precacheOptionsString,
runtimeCaching: runtimeCachingPlaceholder,
skipWaiting: undefined,
Expand All @@ -66,6 +67,8 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
const navigateFallback = '/shell.html';
const navigateFallbackBlacklist = [/another-test/];
const navigateFallbackWhitelist = [/test/];
const offlineGoogleAnalytics = true;
const offlineAnalyticsConfigString = '{}';
const runtimeCaching = [];
const runtimeCachingPlaceholder = 'runtime-caching-placeholder';
const skipWaiting = true;
Expand Down Expand Up @@ -97,6 +100,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
workboxSWImport,
Expand All @@ -112,10 +116,54 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() {
navigateFallback,
navigateFallbackBlacklist,
navigateFallbackWhitelist,
offlineAnalyticsConfigString,
runtimeCaching: runtimeCachingPlaceholder,
precacheOptionsString,
skipWaiting,
workboxSWImport,
}]);
});

it(`should handle a complex offlineGoogleAnalytics value when populating the template`, function() {
const runtimeCachingPlaceholder = 'runtime-caching-placeholder';
const swTemplate = 'template';
const precacheOptionsString = '{}';
const offlineGoogleAnalytics = {
parameterOverrides: {
cd1: 'offline',
},
hitFilter: (params) => {
// Comments are stripped.
params.set('cm1', params.get('qt'));
},
};
const offlineAnalyticsConfigString = `{\n\tparameterOverrides: {\n\t\tcd1: 'offline'\n\t},\n\thitFilter: (params) => {\n \n params.set('cm1', params.get('qt'));\n }\n}`;

const innerStub = sinon.stub().returns('');
const outerStub = sinon.stub().returns(innerStub);
const populateSWTemplate = proxyquire(MODULE_PATH, {
'lodash.template': outerStub,
'./runtime-caching-converter': () => runtimeCachingPlaceholder,
'../templates/sw-template': swTemplate,
});

populateSWTemplate({offlineGoogleAnalytics});

expect(outerStub.alwaysCalledWith(swTemplate)).to.be.true;
expect(innerStub.args[0]).to.eql([{
cacheId: undefined,
clientsClaim: undefined,
importScripts: undefined,
manifestEntries: undefined,
modulePathPrefix: undefined,
navigateFallback: undefined,
navigateFallbackBlacklist: undefined,
navigateFallbackWhitelist: undefined,
offlineAnalyticsConfigString,
precacheOptionsString,
runtimeCaching: runtimeCachingPlaceholder,
skipWaiting: undefined,
workboxSWImport: undefined,
}]);
});
});

0 comments on commit f2e3165

Please sign in to comment.