-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Manifest.php
790 lines (729 loc) · 25.1 KB
/
Manifest.php
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
<?php
/**
* Twigpack plugin for Craft CMS 3.x
*
* Twigpack is the conduit between Twig and webpack, with manifest.json &
* webpack-dev-server HMR support
*
* @link https://nystudio107.com/
* @copyright Copyright (c) 2018 nystudio107
*/
namespace nystudio107\twigpack\helpers;
use Craft;
use craft\errors\DeprecationException;
use craft\helpers\Html;
use craft\helpers\Json as JsonHelper;
use craft\helpers\UrlHelper;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use nystudio107\twigpack\models\Settings;
use nystudio107\twigpack\Twigpack;
use Throwable;
use Twig\Error\LoaderError;
use yii\base\Exception;
use yii\caching\ChainedDependency;
use yii\caching\FileDependency;
use yii\caching\TagDependency;
use yii\web\NotFoundHttpException;
/**
* @author nystudio107
* @package Twigpack
* @since 1.0.0
*/
class Manifest
{
// Constants
// =========================================================================
const CACHE_KEY = 'twigpack';
const CACHE_TAG = 'twigpack';
const DEVMODE_CACHE_DURATION = 1;
const CSP_HEADERS = [
'Content-Security-Policy',
'X-Content-Security-Policy',
'X-WebKit-CSP',
];
const SUPPRESS_ERRORS_FOR_MODULES = [
'styles.js',
];
// Protected Static Properties
// =========================================================================
/**
* @var array
*/
protected static $files;
/**
* @var bool
*/
protected static $isHot = false;
// Public Static Methods
// =========================================================================
/**
* @param array $config
* @param string $moduleName
* @param bool $async
* @param array $attributes additional HTML key/value pair attributes to add to the resulting tag
*
* @return string
* @throws NotFoundHttpException
*/
public static function getCssModuleTags(array $config, string $moduleName, bool $async, array $attributes = []): string
{
$legacyModule = self::getModule($config, $moduleName, 'legacy', true);
if ($legacyModule === null) {
return '';
}
$lines = [];
if ($async) {
$lines[] = Html::cssFile($legacyModule, array_merge([
'rel' => 'stylesheet',
'media' => 'print',
'onload' => "this.media='all'",
], $attributes));
$lines[] = Html::cssFile($legacyModule, array_merge([
'rel' => 'stylesheet',
'noscript' => true,
], $attributes));
} else {
$lines[] = Html::cssFile($legacyModule, array_merge([
'rel' => 'stylesheet',
], $attributes));
}
return implode("\r\n", $lines);
}
/**
* @param string $path
* @param array $attributes additional HTML key/value pair attributes to add to the resulting tag
*
* @return string
*/
public static function getCssInlineTags(string $path, array $attributes = []): string
{
$result = self::getFile($path);
if ($result) {
$config = [];
$nonce = self::getNonce();
if ($nonce !== null) {
$config['nonce'] = $nonce;
self::includeNonce($nonce, 'style-src');
}
$result = Html::style($result, array_merge($config, $attributes));
return $result;
}
return '';
}
/**
* @param array $config
* @param null|string $name
* @param array $attributes additional HTML key/value pair attributes to add to the resulting tag
*
* @return string
* @throws LoaderError
*/
public static function getCriticalCssTags(array $config, $name = null, array $attributes = []): string
{
// Resolve the template name
$template = Craft::$app->getView()->resolveTemplate($name ?? Twigpack::$templateName);
if ($template) {
$name = self::combinePaths(
pathinfo($template, PATHINFO_DIRNAME),
pathinfo($template, PATHINFO_FILENAME)
);
$dirPrefix = 'templates/';
if (defined('CRAFT_TEMPLATES_PATH')) {
$dirPrefix = CRAFT_TEMPLATES_PATH;
}
$name = strstr($name, $dirPrefix);
$name = (string)str_replace($dirPrefix, '', $name);
$path = self::combinePaths(
$config['localFiles']['basePath'],
$config['localFiles']['criticalPrefix'],
$name
) . $config['localFiles']['criticalSuffix'];
return self::getCssInlineTags($path, $attributes);
}
return '';
}
/**
* Returns the uglified loadCSS rel=preload Polyfill as per:
* https://github.com/filamentgroup/loadCSS#how-to-use-loadcss-recommended-example
*
* @return string
* @throws DeprecationException
* @deprecated in 1.2.0
*/
public static function getCssRelPreloadPolyfill(): string
{
Craft::$app->getDeprecator()->log('craft.twigpack.includeCssRelPreloadPolyfill()', 'craft.twigpack.includeCssRelPreloadPolyfill() has been deprecated, this function now does nothing. You can safely remove craft.twigpack.includeCssRelPreloadPolyfill() from your templates.');
return '';
}
/**
* @param array $config
* @param string $moduleName
* @param bool $async
* @param array $attributes additional HTML key/value pair attributes to add to the resulting tag
*
* @return null|string
* @throws NotFoundHttpException
*/
public static function getJsModuleTags(array $config, string $moduleName, bool $async, array $attributes = [])
{
$legacyModule = self::getModule($config, $moduleName, 'legacy', true);
if ($legacyModule === null) {
return '';
}
$modernModule = '';
if ($async) {
$modernModule = self::getModule($config, $moduleName, 'modern', true);
if ($modernModule === null) {
return '';
}
}
$lines = [];
if ($async) {
$lines[] = Html::jsFile($modernModule, array_merge([
'type' => 'module',
], $attributes));
$lines[] = Html::jsFile($legacyModule, array_merge([
'nomodule' => true,
], $attributes));
} else {
$lines[] = Html::jsFile($legacyModule, array_merge([
], $attributes));
}
return implode("\r\n", $lines);
}
/**
* Safari 10.1 supports modules, but does not support the `nomodule`
* attribute - it will load <script nomodule> anyway. This snippet solve
* this problem, but only for script tags that load external code, e.g.:
* <script nomodule src="nomodule.js"></script>
*
* Again: this will **not* # prevent inline script, e.g.:
* <script nomodule>alert('no modules');</script>.
*
* This workaround is possible because Safari supports the non-standard
* 'beforeload' event. This allows us to trap the module and nomodule load.
*
* Note also that `nomodule` is supported in later versions of Safari -
* it's just 10.1 that omits this attribute.
*
* c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
*
* @param array $attributes additional HTML key/value pair attributes to add to the resulting tag
*
* @return string
*/
public static function getSafariNomoduleFix(array $attributes = []): string
{
$code = /** @lang JavaScript */
<<<EOT
!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();
EOT;
$config = [];
$nonce = self::getNonce();
if ($nonce !== null) {
$config['nonce'] = $nonce;
self::includeNonce($nonce, 'script-src');
}
return Html::script($code, array_merge($config, $attributes));
}
/**
* Return the URI to a module
*
* @param array $config
* @param string $moduleName
* @param string $type
* @param bool $soft
*
* @return null|string
* @throws NotFoundHttpException
*/
public static function getModule(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
{
// Get the module entry
$module = self::getModuleEntry($config, $moduleName, $type, $soft);
if ($module !== null) {
$prefix = self::$isHot
? $config['devServer']['publicPath']
: $config['server']['publicPath'];
$useAbsoluteUrl = $config['useAbsoluteUrl'];
// If the module isn't a full URL, prefix it as required
if ($useAbsoluteUrl && !UrlHelper::isAbsoluteUrl($module)) {
$module = self::combinePaths($prefix, $module);
}
// Resolve any aliases
$alias = Craft::getAlias($module, false);
if ($alias) {
$module = $alias;
}
// Make sure it's a full URL, as required
try {
if ($useAbsoluteUrl && !UrlHelper::isAbsoluteUrl($module) && !is_file($module)) {
$module = UrlHelper::siteUrl($module);
}
} catch (Exception $e) {
Craft::error($e->getMessage(), __METHOD__);
}
}
return $module;
}
/**
* Return the HASH value from to module
*
* @param array $config
* @param string $moduleName
* @param string $type
* @param bool $soft
*
* @return null|string
*/
public static function getModuleHash(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
{
$moduleHash = '';
try {
// Get the module entry
$module = self::getModuleEntry($config, $moduleName, $type, $soft);
if ($module !== null) {
// Extract only the Hash Value
$modulePath = pathinfo($module);
$moduleFilename = $modulePath['filename'];
$moduleHash = substr($moduleFilename, strpos($moduleFilename, ".") + 1);
}
} catch (Exception $e) {
// return empty string if no module is found
return '';
}
return $moduleHash;
}
/**
* Return a module's raw entry from the manifest
*
* @param array $config
* @param string $moduleName
* @param string $type
* @param bool $soft
*
* @return null|string
* @throws NotFoundHttpException
*/
public static function getModuleEntry(
array $config,
string $moduleName,
string $type = 'modern',
bool $soft = false
) {
$module = null;
// Get the manifest file
$manifest = self::getManifestFile($config, $type);
if ($manifest !== null) {
// Make sure it exists in the manifest
if (empty($manifest[$moduleName])) {
// Don't report errors for any files in SUPPRESS_ERRORS_FOR_MODULES
if (!in_array($moduleName, self::SUPPRESS_ERRORS_FOR_MODULES)) {
self::reportError(Craft::t(
'twigpack',
'Module does not exist in the manifest: {moduleName}',
['moduleName' => $moduleName]
), $soft);
}
return null;
}
$module = $manifest[$moduleName];
}
return $module;
}
/**
* Return a JSON-decoded manifest file
*
* @param array $config
* @param string $type
*
* @return null|array
* @throws NotFoundHttpException
*/
public static function getManifestFile(array $config, string $type = 'modern')
{
$manifest = null;
// Determine whether we should use the devServer for HMR or not
$devMode = Craft::$app->getConfig()->getGeneral()->devMode;
self::$isHot = ($devMode && $config['useDevServer']);
// Try to get the manifest
while ($manifest === null) {
$manifestPath = self::$isHot
? $config['devServer']['manifestPath']
: $config['server']['manifestPath'];
// If this is a dev-server, use the defined build type
$thisType = $type;
if (self::$isHot) {
$thisType = $config['devServerBuildType'] === 'combined'
? $thisType
: $config['devServerBuildType'];
}
// Normalize the path
$path = self::combinePaths($manifestPath, $config['manifest'][$thisType]);
$manifest = self::getJsonFile($path);
// If the manifest isn't found, and it was hot, fall back on non-hot
if ($manifest === null) {
// We couldn't find a manifest; throw an error
self::reportError(Craft::t(
'twigpack',
'Manifest file not found at: {manifestPath}',
['manifestPath' => $manifestPath]
), true);
if (self::$isHot) {
// Try again, but not with home module replacement
self::$isHot = false;
} else {
// Give up and return null
return null;
}
}
}
return $manifest;
}
/**
* Returns the contents of a file from a URI path
*
* @param string $path
*
* @return string
*/
public static function getFile(string $path): string
{
return self::getFileFromUri($path, null, true) ?? '';
}
/**
* @param array $config
* @param string $fileName
* @param string $type
*
* @return string
*/
public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string
{
$path = null;
try {
$path = self::getModuleEntry($config, $fileName, $type, true);
} catch (NotFoundHttpException $e) {
Craft::error($e->getMessage(), __METHOD__);
}
if ($path !== null) {
// Determine whether we should use the devServer for HMR or not
$devMode = Craft::$app->getConfig()->getGeneral()->devMode;
if ($devMode) {
$devServerPrefix = $config['devServer']['publicPath'];
// If we're using the devserver, swap in the deverserver path
if (UrlHelper::isAbsoluteUrl($path) && self::$isHot) {
$path = parse_url($path, PHP_URL_PATH);
}
$devServerPath = self::combinePaths(
$devServerPrefix,
$path
);
$devServerFile = self::getFileFromUri($devServerPath, null);
if ($devServerFile) {
return $devServerFile;
}
}
// Otherwise, try not-hot files
$localPrefix = $config['localFiles']['basePath'];
$localPath = self::combinePaths(
$localPrefix,
$path
);
$alias = Craft::getAlias($localPath, false);
if ($alias && is_string($alias)) {
$localPath = $alias;
}
try {
if (is_file($localPath)) {
return self::getFile($localPath);
}
} catch (Exception $e) {
Craft::error($e->getMessage(), __METHOD__);
}
}
return '';
}
/**
* Invalidate all of the manifest caches
*/
public static function invalidateCaches()
{
$cache = Craft::$app->getCache();
TagDependency::invalidate($cache, self::CACHE_TAG);
Craft::info('All manifest caches cleared', __METHOD__);
}
/**
* Return the contents of a JSON file from a URI path
*
* @param string $path
*
* @return null|array
*/
protected static function getJsonFile(string $path)
{
return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
}
// Protected Static Methods
// =========================================================================
/**
* Return the contents of a file from a URI path
*
* @param string $path
* @param callable|null $callback
* @param bool $pathOnly
*
* @return null|mixed
*/
protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false)
{
// Resolve any aliases
$alias = Craft::getAlias($path, false);
if ($alias && is_string($alias)) {
$path = $alias;
}
// If we only want the file via path, make sure it exists
try {
if ($pathOnly && !is_file($path)) {
Craft::warning(Craft::t(
'twigpack',
'File does not exist: {path}',
['path' => $path]
), __METHOD__);
return '';
}
} catch (Exception $e) {
Craft::error($e->getMessage(), __METHOD__);
}
// Make sure it's a full URL
try {
if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
$path = UrlHelper::siteUrl($path);
}
} catch (Exception $e) {
Craft::error($e->getMessage(), __METHOD__);
}
return self::getFileContents($path, $callback);
}
/**
* Return the contents of a file from the passed in path
*
* @param string $path
* @param callable $callback
*
* @return null|mixed
*/
protected static function getFileContents(string $path, callable $callback = null)
{
// Return the memoized manifest if it exists
if (!empty(self::$files[$path])) {
return self::$files[$path];
}
// Create the dependency tags
$dependency = new TagDependency([
'tags' => [
self::CACHE_TAG,
self::CACHE_TAG . $path,
],
]);
// If this is a file path such as for the `manifest.json`, add a FileDependency so it's cache bust if the file changes
if (!UrlHelper::isAbsoluteUrl($path)) {
$dependency = new ChainedDependency([
'dependencies' => [
new FileDependency([
'fileName' => $path,
]),
$dependency,
],
]);
}
// Set the cache duration based on devMode
$cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
? self::DEVMODE_CACHE_DURATION
: null;
// Get the result from the cache, or parse the file
$cache = Craft::$app->getCache();
$settings = Twigpack::$plugin->getSettings();
$cacheKeySuffix = $settings->cacheKeySuffix ?? '';
$file = $cache->getOrSet(
self::CACHE_KEY . $cacheKeySuffix . $path,
function() use ($path, $callback) {
$result = null;
$contents = null;
if (UrlHelper::isAbsoluteUrl($path)) {
$clientOptions = [
RequestOptions::HTTP_ERRORS => false,
RequestOptions::CONNECT_TIMEOUT => 3,
RequestOptions::VERIFY => false,
RequestOptions::TIMEOUT => 5,
];
// If we're hot, insert a short 50ms delay in fetching remove files, to handle a webpack-dev-server/
// Tailwind CSS JIT race condition
if (self::$isHot) {
$clientOptions = array_merge($clientOptions, [
RequestOptions::DELAY => 100,
]);
}
$client = new Client($clientOptions);
try {
$response = $client->request('GET', $path, [
RequestOptions::HEADERS => [
'User-Agent' => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13",
'Accept' => '*/*',
],
]);
if ($response->getStatusCode() === 200) {
$contents = $response->getBody()->getContents();
}
} catch (Throwable $e) {
Craft::error($e->getMessage(), __METHOD__);
}
} else {
$contents = @file_get_contents($path);
}
if ($contents) {
$result = $contents;
if ($callback) {
$result = $callback($result);
}
}
return $result;
},
$cacheDuration,
$dependency
);
self::$files[$path] = $file;
return $file;
}
/**
* Get the response code from a given $url
*
* @param $url
* @param $context
* @return false|string
*/
protected static function getHttpResponseCode($url, $context)
{
$headers = @get_headers($url, false, $context);
if (empty($headers)) {
return '404';
}
return substr($headers[0], 9, 3);
}
/**
* Combined the passed in paths, whether file system or URL
*
* @param string ...$paths
*
* @return string
*/
protected static function combinePaths(string ...$paths): string
{
$last_key = count($paths) - 1;
array_walk($paths, function(&$val, $key) use ($last_key) {
switch ($key) {
case 0:
$val = rtrim($val, '/ ');
break;
case $last_key:
$val = ltrim($val, '/ ');
break;
default:
$val = trim($val, '/ ');
break;
}
});
$first = array_shift($paths);
$last = array_pop($paths);
$paths = array_filter($paths);
array_unshift($paths, $first);
$paths[] = $last;
return implode('/', $paths);
}
/**
* @param string $error
* @param bool $soft
*
* @throws NotFoundHttpException
*/
protected static function reportError(string $error, $soft = false)
{
$devMode = Craft::$app->getConfig()->getGeneral()->devMode;
if ($devMode && !$soft) {
throw new NotFoundHttpException($error);
}
if (self::$isHot) {
Craft::warning($error, __METHOD__);
} else {
Craft::error($error, __METHOD__);
}
}
// Private Static Methods
// =========================================================================
/**
* @param string $nonce
* @param string $cspDirective
*/
private static function includeNonce(string $nonce, string $cspDirective)
{
$cspNonceType = self::getCspNonceType();
if ($cspNonceType) {
$cspValue = "{$cspDirective} 'nonce-$nonce'";
foreach (self::CSP_HEADERS as $cspHeader) {
switch ($cspNonceType) {
case 'tag':
Craft::$app->getView()->registerMetaTag([
'httpEquiv' => $cspHeader,
'value' => $cspValue,
]);
break;
case 'header':
Craft::$app->getResponse()->getHeaders()->add($cspHeader, $cspValue . ';');
break;
default:
break;
}
}
}
}
/**
* @return string|null
*/
private static function getCspNonceType()
{
/** @var Settings $settings */
$settings = Twigpack::$plugin->getSettings();
$cspNonceType = !empty($settings->cspNonce) ? strtolower($settings->cspNonce) : null;
return $cspNonceType;
}
/**
* @return string|null
*/
private static function getNonce()
{
$result = null;
if (self::getCspNonceType() !== null) {
try {
$result = bin2hex(random_bytes(22));
} catch (\Exception $e) {
// That's okay
}
}
return $result;
}
/**
* @param $string
*
* @return null|array
*/
private static function jsonFileDecode($string)
{
$json = JsonHelper::decodeIfJson($string);
if (is_string($json)) {
Craft::error('Error decoding JSON file: ' . $json, __METHOD__);
$json = null;
}
return $json;
}
}