4
4
5
5
namespace Rawilk \FormComponents ;
6
6
7
+ use Illuminate \Support \Facades \Vite ;
8
+
7
9
final class FormComponents
8
10
{
9
11
/**
@@ -22,14 +24,38 @@ public function javaScript(array $options = []): string
22
24
private function javaScriptAssets (array $ options = []): string
23
25
{
24
26
$ assetsUrl = config ('form-components.asset_url ' ) ?: rtrim ($ options ['asset_url ' ] ?? '' , '/ ' );
27
+ $ nonce = $ this ->getNonce ($ options );
25
28
26
29
$ manifest = json_decode (file_get_contents (__DIR__ . '/../dist/manifest.json ' ), true );
27
30
$ versionedFileName = $ manifest ['/form-components.js ' ];
28
31
29
32
$ fullAssetPath = "{$ assetsUrl }/form-components {$ versionedFileName }" ;
30
33
31
34
return <<<HTML
32
- <script src=" {$ fullAssetPath }" data-turbo-eval="false" data-turbolinks-eval="false"></script>
35
+ <script src=" {$ fullAssetPath }" data-turbo-eval="false" data-turbolinks-eval="false" { $ nonce } ></script>
33
36
HTML ;
34
37
}
38
+
39
+ private function getNonce (array $ options ): string
40
+ {
41
+ if (isset ($ options ['nonce ' ])) {
42
+ return "nonce= \"{$ options ['nonce ' ]}\"" ;
43
+ }
44
+
45
+ // If there is a csp package installed, i.e. spatie/laravel-csp, we'll check for the existence of the helper function.
46
+ if (function_exists ('csp_nonce ' ) && $ nonce = csp_nonce ()) {
47
+ return "nonce= \"{$ nonce }\"" ;
48
+ }
49
+
50
+ if (function_exists ('cspNonce ' ) && $ nonce = cspNonce ()) {
51
+ return "nonce= \"{$ nonce }\"" ;
52
+ }
53
+
54
+ // Lastly, we'll check for the existence of a csp nonce from Vite.
55
+ if (class_exists (Vite::class) && $ nonce = Vite::cspNonce ()) {
56
+ return "nonce= \"{$ nonce }\"" ;
57
+ }
58
+
59
+ return '' ;
60
+ }
35
61
}
0 commit comments