@@ -45,6 +45,9 @@ class FetchResponse {
45
45
get isTurboStream ( ) {
46
46
return this . contentType . match ( / ^ t e x t \/ v n d \. t u r b o - s t r e a m \. h t m l / ) ;
47
47
}
48
+ get isScript ( ) {
49
+ return this . contentType . match ( / \b (?: j a v a | e c m a ) s c r i p t \b / ) ;
50
+ }
48
51
async renderTurboStream ( ) {
49
52
if ( this . isTurboStream ) {
50
53
if ( window . Turbo ) {
@@ -56,6 +59,20 @@ class FetchResponse {
56
59
return Promise . reject ( new Error ( `Expected a Turbo Stream response but got "${ this . contentType } " instead` ) ) ;
57
60
}
58
61
}
62
+ async activeScript ( ) {
63
+ if ( this . isScript ) {
64
+ const script = document . createElement ( "script" ) ;
65
+ const metaTag = document . querySelector ( "meta[name=csp-nonce]" ) ;
66
+ const nonce = metaTag && metaTag . content ;
67
+ if ( nonce ) {
68
+ script . setAttribute ( "nonce" , nonce ) ;
69
+ }
70
+ script . innerHTML = await this . text ;
71
+ document . body . appendChild ( script ) ;
72
+ } else {
73
+ return Promise . reject ( new Error ( `Expected a Script response but got "${ this . contentType } " instead` ) ) ;
74
+ }
75
+ }
59
76
}
60
77
61
78
class RequestInterceptor {
@@ -129,10 +146,14 @@ class FetchRequest {
129
146
} catch ( error ) {
130
147
console . error ( error ) ;
131
148
}
132
- const response = new FetchResponse ( await window . fetch ( this . url , this . fetchOptions ) ) ;
149
+ const fetch = this . responseKind === "turbo-stream" && window . Turbo ? window . Turbo . fetch : window . fetch ;
150
+ const response = new FetchResponse ( await fetch ( this . url , this . fetchOptions ) ) ;
133
151
if ( response . unauthenticated && response . authenticationURL ) {
134
152
return Promise . reject ( window . location . href = response . authenticationURL ) ;
135
153
}
154
+ if ( response . isScript ) {
155
+ await response . activeScript ( ) ;
156
+ }
136
157
const responseStatusIsTurboStreamable = response . ok || response . unprocessableEntity ;
137
158
if ( responseStatusIsTurboStreamable && response . isTurboStream ) {
138
159
await response . renderTurboStream ( ) ;
@@ -199,6 +220,9 @@ class FetchRequest {
199
220
case "json" :
200
221
return "application/json, application/vnd.api+json" ;
201
222
223
+ case "script" :
224
+ return "text/javascript, application/javascript" ;
225
+
202
226
default :
203
227
return "*/*" ;
204
228
}
0 commit comments