amphora-html 6.0.0-4 → 6.0.0-5

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.
Files changed (40) hide show
  1. package/lib/media.js +1 -1
  2. package/package.json +1 -1
  3. package/.vscode/.history/amphora-html/lib/media.test_20210527151433.js +0 -797
  4. package/.vscode/.history/amphora-html/lib/media.test_20210607095503.js +0 -815
  5. package/.vscode/.history/amphora-html/lib/media.test_20210607095544.js +0 -815
  6. package/.vscode/.history/amphora-html/lib/media.test_20210607100025.js +0 -817
  7. package/.vscode/.history/amphora-html/lib/media.test_20210607100402.js +0 -817
  8. package/.vscode/.history/amphora-html/lib/media.test_20210607100635.js +0 -829
  9. package/.vscode/.history/amphora-html/lib/media.test_20210607105251.js +0 -852
  10. package/.vscode/.history/amphora-html/lib/media.test_20210607120734.js +0 -839
  11. package/.vscode/.history/amphora-html/lib/media.test_20210607121735.js +0 -873
  12. package/.vscode/.history/amphora-html/lib/media.test_20210608203514.js +0 -908
  13. package/.vscode/.history/amphora-html/lib/media_20210803152635.js +0 -456
  14. package/.vscode/.history/amphora-html/lib/media_20210803154356.js +0 -459
  15. package/.vscode/.history/amphora-html/lib/media_20210803154416.js +0 -458
  16. package/.vscode/.history/amphora-html/lib/media_20210803154428.js +0 -429
  17. package/.vscode/.history/amphora-html/lib/media_20210803154955.js +0 -426
  18. package/.vscode/.history/amphora-html/lib/media_20210803155434.js +0 -414
  19. package/.vscode/.history/amphora-html/lib/media_20210803155459.js +0 -413
  20. package/.vscode/.history/amphora-html/lib/media_20210803155524.js +0 -413
  21. package/.vscode/.history/amphora-html/lib/media_20210803161841.js +0 -412
  22. package/.vscode/.history/amphora-html/lib/media_20210803163103.js +0 -411
  23. package/.vscode/.history/amphora-html/lib/media_20210818123839.js +0 -449
  24. package/.vscode/.history/amphora-html/lib/media_20210818124154.js +0 -463
  25. package/.vscode/.history/amphora-html/lib/media_20210818124158.js +0 -463
  26. package/.vscode/.history/amphora-html/lib/media_20210818124413.js +0 -458
  27. package/.vscode/.history/amphora-html/lib/media_20210818124810.js +0 -459
  28. package/.vscode/.history/amphora-html/lib/media_20210818124903.js +0 -454
  29. package/.vscode/.history/amphora-html/lib/media_20210819115533.js +0 -454
  30. package/.vscode/.history/amphora-html/lib/media_20210819115825.js +0 -454
  31. package/.vscode/.history/amphora-html/lib/media_20210819120153.js +0 -454
  32. package/.vscode/.history/amphora-html/lib/media_20210819120237.js +0 -455
  33. package/.vscode/.history/amphora-html/lib/media_20210819120300.js +0 -454
  34. package/.vscode/.history/amphora-html/lib/media_20210819120500.js +0 -455
  35. package/.vscode/.history/amphora-html/lib/media_20210819120508.js +0 -453
  36. package/.vscode/.history/amphora-html/lib/media_20210819120525.js +0 -437
  37. package/.vscode/.history/amphora-html/lib/media_20210819172211.js +0 -437
  38. package/.vscode/.history/amphora-html/lib/media_20210819172412.js +0 -438
  39. package/.vscode/.history/amphora-html/package_20210825103846.json +0 -62
  40. package/.vscode/.history/amphora-html/package_20210825104039.json +0 -62
@@ -1,459 +0,0 @@
1
- 'use strict';
2
-
3
- const _ = require('lodash'),
4
- path = require('path'),
5
- files = require('nymag-fs'),
6
- bluebird = require('bluebird'),
7
- setup = require('./setup'),
8
- styleguide = require('./styleguide'),
9
- url = require('url'),
10
- STYLE_TAG = 'style',
11
- SCRIPT_TAG = 'scripts',
12
- ASYNC_SCRIPT_TAG = 'async',
13
- DEFER_SCRIPT_TAG = 'defer',
14
- ASYNC_DEFER_SCRIPT_TAG = 'async-defer',
15
- MEDIA_DIRECTORY = path.join(process.cwd(), 'public');
16
-
17
- /**
18
- * @param {string} str
19
- * @returns {number}
20
- */
21
- function findBottom(str) {
22
- var index = str.lastIndexOf('</body>');
23
-
24
- if (index === -1) {
25
- index = str.lastIndexOf('</');
26
- }
27
-
28
- return index;
29
- }
30
-
31
- /**
32
- * @param {string} str
33
- * @returns {number}
34
- */
35
- function findTop(str) {
36
- var index = str.indexOf('</head>');
37
-
38
- if (index === -1) {
39
- index = str.indexOf('>') + 1;
40
- }
41
- return index;
42
- }
43
-
44
- /**
45
- * Put items at index in the very large target string.
46
- *
47
- * @param {string} str
48
- * @param {number} index
49
- * @param {[string]} items
50
- * @returns {string}
51
- */
52
- function splice(str, index, items) {
53
- return str.substr(0, index) + items + str.substr(index);
54
- }
55
-
56
- /**
57
- * Get the contents of a string that come after specified characters.
58
- *
59
- * @param {string} str Any string to split
60
- * @param {string} dir The directory the file is in
61
- * @return {string}
62
- */
63
- function getFileName(str, dir) {
64
- return str.split(dir)[1];
65
- }
66
-
67
- /**
68
- * Retrieve the contents of a file
69
- *
70
- * @param {array} fileArray An array of file names
71
- * @param {string} targetDir The directory to retrieve files from
72
- * @param {string} filePrefix The string that comes right before the file name
73
- * @return {Promise}
74
- */
75
- function getContentsOfFiles(fileArray, targetDir, filePrefix) {
76
- var allPromises = [],
77
- currentDir = process.cwd();
78
-
79
- fileArray.forEach(file => {
80
- allPromises.push(files.readFilePromise(path.join(currentDir, targetDir, getFileName(file, filePrefix))));
81
- });
82
-
83
- return Promise.all(allPromises)
84
- .catch(err => {
85
- throw err;
86
- });
87
- }
88
-
89
- /**
90
- * Wraps a string with HTML tags
91
- * @param {string} string The string to wrap
92
- * @param {string} tag The HTML tag to use
93
- * @return {string}
94
- */
95
- function wrapWithTags(string, tag) {
96
- if (tag === SCRIPT_TAG) {
97
- return `<script type="text/javascript">
98
- // <![CDATA[
99
- ${string}
100
- // ]]
101
- </script>`;
102
- } else {
103
- return `<style>${string}</style>`;
104
- }
105
- }
106
-
107
- /**
108
- * Concatenates an array of files into one string.
109
- *
110
- * @param {array} fileArray An array of files
111
- * @param {string} directory The directory in which `fs` will look for the file
112
- * @param {string} filePrefix The directory path before the filename
113
- * @param {string|null} tag The type of tag to wrap the contents in.
114
- * @return {string}
115
- */
116
- function combineFileContents(fileArray, directory, filePrefix, tag) {
117
- if (!fileArray || !fileArray.length) {
118
- return false;
119
- }
120
-
121
- // If there are files, retrieve contents
122
- return getContentsOfFiles(fileArray, directory, filePrefix)
123
- .then(function (fileContents) {
124
- return wrapWithTags(fileContents.join(''), tag);
125
- });
126
- }
127
-
128
- /**
129
- * Append at the bottom of the head tag, or if no head tag, then the top of root tag.
130
- *
131
- * @param {array} styles
132
- * @param {string} html
133
- * @returns {string}
134
- */
135
- function appendMediaToTop(styles, html) {
136
- var index = findTop(html);
137
-
138
- return splice(html, index, styles);
139
- }
140
-
141
- /**
142
- * Append at the bottom of the body tag, or if no body tag, then the bottom of the root tag.
143
- * @param {Array} scripts
144
- * @param {string} html
145
- * @returns {string}
146
- */
147
- function appendMediaToBottom(scripts, html) {
148
- var index = findBottom(html);
149
-
150
- return splice(html, index, scripts);
151
- }
152
-
153
- function injectTags(fileArray, site, tag) {
154
- var buster = module.exports.cacheBuster ? `?version=${module.exports.cacheBuster}` : '';
155
-
156
- return bluebird.resolve(_.map(fileArray, function (file) {
157
- if (tag === STYLE_TAG) {
158
- return `<link rel="stylesheet" type="text/css" href="${file}${buster}">`;
159
- } else if (tag === ASYNC_SCRIPT_TAG) {
160
- return `<script async src="${file}" type="text/javascript"></script>`;
161
- } else if (tag === DEFER_SCRIPT_TAG) {
162
- return `<script defer src="${file}" type="text/javascript"></script>`;
163
- } else if (tag === ASYNC_DEFER_SCRIPT_TAG) {
164
- return `<script async defer src="${file}" type="text/javascript"></script>`;
165
- } else {
166
- return `<script type="text/javascript" src="${file}${buster}"></script>`;
167
- }
168
- }).join('\n'));
169
- }
170
-
171
- /**
172
- * Filter the components rendered in this request, removing Webpack-managed
173
- * assets so that we can fall back on Browserify.
174
- *
175
- * @param {Object} state - Amphora render state.
176
- * @returns {string[]} - A list of components not available through Webpack.
177
- */
178
- function filterManifestComponents(state) {
179
- const site = state.locals.site,
180
- assetDir = site && site.assetDir || MEDIA_DIRECTORY,
181
- manifestName = site && site.manifestName || 'assets-manifest.json',
182
- manifestFile = path.resolve(path.join(assetDir, manifestName));
183
- let manifest;
184
-
185
- try {
186
- manifest = files.tryRequire(manifestFile);
187
- } catch (err) {
188
- return state._components;
189
- }
190
-
191
-
192
- return state._components
193
- .filter(componentName => !manifest.hasOwnProperty(`${ componentName }.js`));
194
- }
195
-
196
- /**
197
- * Gets a list of all css and js needed for the components listed.
198
- * @param {Object} state
199
- * @returns {{styles: Array, scripts: Array}}
200
- */
201
- function getMediaMap(state) {
202
- return {
203
- styles: module.exports.getStyleFiles(state),
204
- scripts: [],
205
- manifestAssets: module.exports.getManifestAssets(state)
206
- };
207
- }
208
-
209
- /* eslint-disable complexity */
210
- /**
211
- * Get the proper styles for the component. If a styleguide is configured, use
212
- * that css. Defaults to the site slug
213
- *
214
- * @param {Object} state
215
- * @returns {array}
216
- */
217
- function getStyleFiles(state) {
218
- const { site } = state.locals,
219
- assetDir = site && site.assetDir || MEDIA_DIRECTORY,
220
- assetPath = site && site.assetPath || '',
221
- assetHost = site && site.assetHost || '',
222
- siteStyleguide = site && site.styleguide,
223
- layoutName = _.get(state, '_layoutData.name');
224
- let cssFilePaths = [], layoutBasePath;
225
-
226
- // legacy behavior: load <component>.css and <component>.<site>.css
227
- if (!site.styleguide) {
228
- const siteSlug = site && site.slug;
229
-
230
- cssFilePaths = state._components
231
- .reduce((acc, curr) => {
232
- acc.push(
233
- path.join(assetDir, 'css', `${curr}.css`),
234
- path.join(assetDir, 'css', `${curr}.${siteSlug}.css`)
235
- );
236
- return acc;
237
- }, []);
238
- // in edit mode, grab all variations
239
- } else if (state.locals.edit) {
240
- const availableVariations = styleguide.getVariations(siteStyleguide);
241
-
242
- cssFilePaths = state._components
243
- .reduce((acc, cmptName) => {
244
- acc.push(cmptName, ...availableVariations[cmptName] || []);
245
- return acc;
246
- }, [])
247
- .map(baseName => {
248
- const basePath = path.join(assetDir, 'css', `${baseName}.${siteStyleguide}.css`);
249
-
250
- return files.fileExists(basePath) ?
251
- basePath :
252
- path.join(assetDir, 'css', `${baseName}._default.css`);
253
- });
254
- // in view mode, grab only used variations
255
- } else if (state._usedVariations) {
256
- cssFilePaths = state._usedVariations
257
- .map(variation => {
258
- const styleguideVariationPath = path.join(assetDir, 'css', `${variation}.${siteStyleguide}.css`);
259
-
260
- return files.fileExists(styleguideVariationPath) ?
261
- styleguideVariationPath :
262
- path.join(assetDir, 'css', `${variation}._default.css`);
263
- });
264
- }
265
-
266
- // add the layout css
267
- if (layoutName) {
268
- layoutBasePath = path.join(assetDir, 'css', `${layoutName}.${siteStyleguide}.css`);
269
-
270
- if (files.fileExists(layoutBasePath)) {
271
- cssFilePaths.push(layoutBasePath);
272
- } else {
273
- cssFilePaths.push(path.join(assetDir, 'css', `${layoutName}._default.css`));
274
- }
275
- }
276
-
277
- return cssFilePaths
278
- .filter(files.fileExists)
279
- .map(pathJoin(assetHost, assetPath, assetDir));
280
- }
281
- /* eslint-enable complexity */
282
-
283
- /**
284
- * Get the proper scripts for the component
285
- *
286
- * @param {string} name
287
- * @param {object} site
288
- * @returns {array}
289
- */
290
-
291
- function getScriptFiles(state) {
292
- const site = state.locals.site,
293
- slug = site.slug,
294
- assetDir = site && site.assetDir || MEDIA_DIRECTORY,
295
- assetPath = site && site.assetPath || '',
296
- assetHost = site && site.assetHost || '',
297
- manifestName = site && site.manifestName || 'assets-manifest.json',
298
- manifestFile = path.resolve(path.join(assetDir, manifestName)),
299
- manifestData = files.readFile(manifestFile);
300
-
301
- if (manifestData) {
302
- const manifest = JSON.parse(manifestData),
303
- entries = _.get(manifest, 'entrypoints', {}),
304
- scripts = _.flatMap(entries, entry => _.get(entry, 'assets.js', []));
305
-
306
- return _.uniq(scripts);
307
- }
308
-
309
- return filterManifestComponents(state)
310
- .reduce((prev, name) => {
311
- prev.push(
312
- path.join(assetDir, 'js', `${name}.js`),
313
- path.join(assetDir, 'js', `${name}.${slug}.js`),
314
- path.join(assetDir, 'js', `${name}.client.js`)
315
- );
316
- return prev;
317
- }, [])
318
- .filter(files.fileExists)
319
- .map(pathJoin(assetHost, assetPath, assetDir));
320
- }
321
-
322
- /**
323
- * Read the asset manifest generated by the `clay pack` bundling command and
324
- * check for scripts which match the rendered component names. The manifest for
325
- * each asset lists its complete set of dependencies, so we dedupe them.
326
- * Webpack's runtime is added to the beginning of the list, downstream legacy
327
- * globals and Clay CLI's init script to the end.
328
- *
329
- * @param {Object} state - Amphora's render state.
330
- * @return {string[]} A list of component assets.
331
- */
332
- function getManifestAssets(state) {
333
- const site = state.locals.site,
334
- assetDir = site && site.assetDir || MEDIA_DIRECTORY,
335
- assetHost = site && site.assetHost || '/',
336
- manifestName = site && site.manifestName || 'assets-manifest.json',
337
- manifestFile = path.resolve(path.join(assetDir, manifestName));
338
- let manifest;
339
-
340
- try {
341
- manifest = files.tryRequire(manifestFile);
342
- } catch (err) {
343
- return [];
344
- }
345
-
346
- const scriptFiles = _.get(manifest, ['entrypoints', 'main', 'assets', 'js'], []);
347
-
348
- return scriptFiles.map(script => url.resolve(assetHost, script));
349
- }
350
-
351
- /**
352
- * Trim the path on the file system bythe link of the
353
- * asset directory and then join it with either the assetHost
354
- * value of the site or the assetPath value (found in the
355
- * site's config file)
356
- *
357
- * @param {String} assetHost
358
- * @param {String} assetPath
359
- * @param {String} assetDir
360
- * @return {Function}
361
- */
362
- function pathJoin(assetHost, assetPath, assetDir) {
363
- var assetDirLen = assetDir.length;
364
-
365
- return function (filePath) {
366
- var pathToFile = filePath.substr(assetDirLen);
367
-
368
- if (assetHost) return `${assetHost}${pathToFile}`;
369
- return path.join(assetPath, pathToFile);
370
- };
371
- }
372
-
373
- /**
374
- * Set the values for inlining vs tagging edit mode styles/scripts
375
- *
376
- * @param {object|boolean} options
377
- * @param {string} [cacheBuster]
378
- */
379
- function configure(options, cacheBuster = '') {
380
- if (options && _.isObject(options)) {
381
- module.exports.editStylesTags = options.styles || false;
382
- module.exports.editScriptsTags = options.scripts || false;
383
- } else {
384
- module.exports.editStylesTags = options;
385
- module.exports.editScriptsTags = options;
386
- }
387
- // Assign cacheBuster
388
- module.exports.cacheBuster = cacheBuster;
389
- }
390
-
391
- /**
392
- * Given the state and html string...
393
- *
394
- * 1. Find all associated scripts/styles
395
- * 2. Run `resolveMedia`
396
- * 3. Stitch in the assets' contents
397
- * 4. Return the HTML string
398
- *
399
- * @param {Object} state
400
- * @return {Function}
401
- */
402
- function injectScriptsAndStyles(state) {
403
- const { locals } = state;
404
-
405
- return function (html) {
406
- var mediaMap = {};
407
-
408
- // Check that HTML is string
409
- if (typeof html !== 'string') {
410
- throw new Error('Missing html parameter');
411
- }
412
-
413
- // We've got a string so let's actually get the map of styles
414
- mediaMap = module.exports.getMediaMap(state);
415
-
416
- // allow site to change the media map before applying it
417
- if (setup.resolveMedia) mediaMap = setup.resolveMedia(mediaMap, locals) || mediaMap;
418
-
419
- if (!locals.edit) {
420
- mediaMap.styles = combineFileContents(mediaMap.styles, 'public/css', '/css/', STYLE_TAG);
421
- mediaMap.scripts = combineFileContents(mediaMap.scripts, 'public/js', '/js/', SCRIPT_TAG);
422
-
423
- // TODO: Ideally, we'd load these scripts asynchronously or after the DOM
424
- // is ready, setting the `async` attribute, the `defer` attribute, or
425
- // both. Because the order in which they're parsed and executed currently
426
- // matters, we can't do that safely.
427
- mediaMap.manifestAssets = injectTags(mediaMap.manifestAssets, locals.site, SCRIPT_TAG);
428
- } else {
429
- mediaMap.styles = module.exports.editStylesTags ? injectTags(mediaMap.styles, locals.site, STYLE_TAG) : combineFileContents(mediaMap.styles, 'public/css', '/css/', STYLE_TAG);
430
- mediaMap.scripts = module.exports.editScriptsTags ? injectTags(mediaMap.scripts, locals.site, SCRIPT_TAG) : combineFileContents(mediaMap.scripts, 'public/js', '/js/', SCRIPT_TAG);
431
-
432
- // FIXME: Some of the logic which excludes client-side scripts from edit
433
- // mode sits with nymag/sites, in the `resolve-media` module, and some
434
- // lives here. Since we're currently not using Webpack for Kiln and model
435
- // assets, this feels like the best place to null out client scripts.
436
- mediaMap.manifestAssets = null;
437
- }
438
-
439
- return bluebird.props(mediaMap)
440
- .then(combinedFiles => {
441
- html = combinedFiles.styles ? appendMediaToTop(combinedFiles.styles, html) : html; // If there are styles, append them
442
- html = combinedFiles.manifestAssets ? appendMediaToBottom(combinedFiles.manifestAssets, html) : html; // If there are assets registered with the manifest, append them
443
- html = combinedFiles.scripts ? appendMediaToBottom(combinedFiles.scripts, html) : html; // If there are scripts, append them
444
- return html; // Return the compiled HTML
445
- });
446
- };
447
- }
448
-
449
- module.exports.injectScriptsAndStyles = injectScriptsAndStyles;
450
- module.exports.getMediaMap = getMediaMap;
451
- module.exports.cacheBuster = '';
452
- module.exports.configure = configure;
453
- module.exports.editStylesTags = false;
454
- module.exports.editScriptsTags = false;
455
-
456
- // For testing
457
- module.exports.getManifestAssets = getManifestAssets;
458
- module.exports.getScriptFiles = getScriptFiles;
459
- module.exports.getStyleFiles = getStyleFiles;