Skip to content

Commit 8e42bbb

Browse files
committed
bump request.js to v0.0.11
1 parent 739a5ca commit 8e42bbb

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

Gemfile.lock

+1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ GEM
6868

6969
PLATFORMS
7070
arm64-darwin-21
71+
arm64-darwin-22
7172
x86_64-darwin-18
7273
x86_64-linux
7374

app/assets/javascripts/requestjs.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ class FetchResponse {
4545
get isTurboStream() {
4646
return this.contentType.match(/^text\/vnd\.turbo-stream\.html/);
4747
}
48+
get isScript() {
49+
return this.contentType.match(/\b(?:java|ecma)script\b/);
50+
}
4851
async renderTurboStream() {
4952
if (this.isTurboStream) {
5053
if (window.Turbo) {
@@ -56,6 +59,20 @@ class FetchResponse {
5659
return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`));
5760
}
5861
}
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+
}
5976
}
6077

6178
class RequestInterceptor {
@@ -129,10 +146,14 @@ class FetchRequest {
129146
} catch (error) {
130147
console.error(error);
131148
}
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));
133151
if (response.unauthenticated && response.authenticationURL) {
134152
return Promise.reject(window.location.href = response.authenticationURL);
135153
}
154+
if (response.isScript) {
155+
await response.activeScript();
156+
}
136157
const responseStatusIsTurboStreamable = response.ok || response.unprocessableEntity;
137158
if (responseStatusIsTurboStreamable && response.isTurboStream) {
138159
await response.renderTurboStream();
@@ -199,6 +220,9 @@ class FetchRequest {
199220
case "json":
200221
return "application/json, application/vnd.api+json";
201222

223+
case "script":
224+
return "text/javascript, application/javascript";
225+
202226
default:
203227
return "*/*";
204228
}

0 commit comments

Comments
 (0)