Enables cross-origin Web Workers (#35483)

This commit is contained in:
Echo 2025-07-24 09:14:27 +02:00 committed by GitHub
parent a6794c066d
commit 7f9ad7eabf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 44 additions and 6 deletions

View File

@ -1,4 +1,5 @@
import initialState from '@/mastodon/initial_state';
import { loadWorker } from '@/mastodon/utils/workers';
import { toSupportedLocale } from './locale';
@ -9,9 +10,8 @@ let worker: Worker | null = null;
export async function initializeEmoji() {
if (!worker && 'Worker' in window) {
try {
worker = new Worker(new URL('./worker', import.meta.url), {
worker = loadWorker(new URL('./worker', import.meta.url), {
type: 'module',
credentials: 'omit',
});
} catch (err) {
console.warn('Error creating web worker:', err);

View File

@ -36,15 +36,16 @@ async function fetchAndCheckEtag<ResultType extends object[]>(
): Promise<ResultType | null> {
const locale = toSupportedLocaleOrCustom(localeOrCustom);
let uri: string;
// Use location.origin as this script may be loaded from a CDN domain.
const url = new URL(location.origin);
if (locale === 'custom') {
uri = '/api/v1/custom_emojis';
url.pathname = '/api/v1/custom_emojis';
} else {
uri = `/packs${isDevelopment() ? '-dev' : ''}/emoji/${locale}.json`;
url.pathname = `/packs${isDevelopment() ? '-dev' : ''}/emoji/${locale}.json`;
}
const oldEtag = await loadLatestEtag(locale);
const response = await fetch(uri, {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
'If-None-Match': oldEtag ?? '', // Send the old ETag to check for modifications

View File

@ -0,0 +1,29 @@
/**
* Loads Web Worker that is compatible with cross-origin scripts for CDNs.
*
* Returns null if the environment doesn't support web workers.
*/
export function loadWorker(url: string | URL, options: WorkerOptions = {}) {
if (!('Worker' in window)) {
return null;
}
try {
// Check if the script origin and the window origin are the same.
const scriptUrl = new URL(import.meta.url);
if (location.origin === scriptUrl.origin) {
// Not cross-origin, can just load normally.
return new Worker(url, options);
}
} catch (err) {
// In case the URL parsing fails.
console.warn('Error instantiating Worker:', err);
}
// Import the worker script from a same-origin Blob.
const contents = `import ${JSON.stringify(url)};`;
const blob = URL.createObjectURL(
new Blob([contents], { type: 'text/javascript' }),
);
return new Worker(blob, options);
}

View File

@ -19,6 +19,9 @@ Rails.application.configure do
# Enable server timing.
config.server_timing = true
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
config.asset_host = ENV['CDN_HOST'] if ENV['CDN_HOST'].present?
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?

View File

@ -65,6 +65,11 @@ export const config: UserConfigFnPromise = async ({ mode, command }) => {
// but it needs to be scoped to the whole domain
'Service-Worker-Allowed': '/',
},
hmr: {
// Forcing the protocol to be insecure helps if you are proxying your dev server with SSL,
// because Vite still tries to connect to localhost.
protocol: 'ws',
},
port: 3036,
},
build: {