44
55namespace Rawilk \FormComponents ;
66
7+ use Illuminate \Support \Facades \Vite ;
8+
79final class FormComponents
810{
911 /**
@@ -22,14 +24,38 @@ public function javaScript(array $options = []): string
2224 private function javaScriptAssets (array $ options = []): string
2325 {
2426 $ assetsUrl = config ('form-components.asset_url ' ) ?: rtrim ($ options ['asset_url ' ] ?? '' , '/ ' );
27+ $ nonce = $ this ->getNonce ($ options );
2528
2629 $ manifest = json_decode (file_get_contents (__DIR__ . '/../dist/manifest.json ' ), true );
2730 $ versionedFileName = $ manifest ['/form-components.js ' ];
2831
2932 $ fullAssetPath = "{$ assetsUrl }/form-components {$ versionedFileName }" ;
3033
3134 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>
3336 HTML ;
3437 }
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+ }
3561}
0 commit comments