Merge commit 'f8cb997b98ba219d110839b4178ee9b469ff944b' into glitch-soc/merge-upstream

Conflicts:
- `config/vite.json`:
  Upstream removed this file, while we had modified it.
  But it had become irrelevant, so removed it as upstream did.
- `vite.config.mts`:
  Upstream removed a plugin that became irrelevant, and the
  import was right besides a glitch-specific import.
  Removed the same import as upstream, kept the glitch-specific one.
This commit is contained in:
Claire committed 2026-08-03 20:59:59 +02:00
commit c40f67e36d
77 files changed
+2092 -345

No files matched your search

+4 -4
View File
@@ -2,16 +2,16 @@
module PremailerBundledAssetStrategy
def load(url)
if ViteRuby.instance.dev_server_running?
if Rails.env.development? && Vite.dev_server.running?
# Request from the dev server
return unless url.start_with?("/#{ViteRuby.config.public_output_dir}/")
return unless url.start_with?(Vite.config.base_path)
headers = {}
# Vite dev server wants this header for CSS files, otherwise it will respond with a JS file that inserts the CSS (to support hot reloading)
headers['Accept'] = 'text/css' if url.end_with?('.scss', '.css')
Net::HTTP.get(
URI("#{ViteRuby.config.origin}#{url}"),
URI("#{Vite.config.backend}#{url}"),
headers
).presence
else
@@ -22,7 +22,7 @@ module PremailerBundledAssetStrategy
path.read
end
rescue ViteRuby::MissingEntrypointError
rescue Vite::Manifest::MissingEntryError
# If the path is not in the manifest, ignore it
end
+9 -2
View File
@@ -14,9 +14,16 @@ end
if Rake::Task.task_defined?('assets:precompile')
Rake::Task['assets:precompile'].enhance do
# Vite integration
Vite.tasks.precompile
Rake::Task['assets:generate_static_pages'].invoke
end
end
# We don't want vite_ruby to run yarn, we do that in a separate step
Rake::Task['vite:install_dependencies'].clear
if Rake::Task.task_defined?('assets:clobber')
Rake::Task['assets:clobber'].enhance do
# Vite integration
Vite.tasks.clobber
end
end
+48
View File
@@ -0,0 +1,48 @@
# frozen_string_literal: true
# Integration library between Mastodon backend and Vite
module Vite
autoload :Builder, 'vite/builder'
autoload :Config, 'vite/config'
autoload :DevServer, 'vite/dev_server'
autoload :Manifest, 'vite/manifest'
autoload :NameResolver, 'vite/name_resolver'
autoload :Proxy, 'vite/proxy'
autoload :Tagger, 'vite/tagger'
autoload :TagsHelper, 'vite/tags_helper'
autoload :Tasks, 'vite/tasks'
def self.setup
yield config if block_given?
end
def self.config
@config ||= Config.new
end
def self.logger
@logger ||= config.logger
end
def self.dev_server
@dev_server ||= DevServer.new(config:)
end
def self.tagger
@tagger ||= Tagger.new(config:, manifest:, dev_server:)
end
def self.manifest
@manifest ||= Manifest.new(config:, logger:)
end
def self.tasks
@tasks ||= Vite::Tasks.new(config:)
end
def self.preload
manifest.load
rescue Vite::Manifest::MissingManifestError => e
logger.error { e.message }
end
end
+50
View File
@@ -0,0 +1,50 @@
# frozen_string_literal: true
module Vite
# Execute the configured build command and log its output
# @see Vite::Config#build_command
class Builder
class BuildError < StandardError
def initialize(command, exit_status)
super("Vite build command '#{command}' failed with status: #{exit_status}")
end
end
attr_reader :config, :logger
def initialize(config:, logger:)
@config = config
@logger = logger
end
def build
logger.info { "Build: Building assets with vite with command: '#{config.build_command}'" }
Open3.popen3(config.build_command) do |_stdin, stdout, stderr, wait_thread|
read_pipe(stdout) do |line|
logger.info { line.strip }
end
read_pipe(stderr) do |line|
logger.error { line.strip }
end
wait_thread.value
end
end
def build!
status = build
raise(BuildError.new(config.build_command, status.exitstatus)) unless status.success?
end
private
def read_pipe(io)
while (line = io.gets)
next if line.blank?
yield line
end
end
end
end
+88
View File
@@ -0,0 +1,88 @@
# frozen_string_literal: true
module Vite
# Main configuration options to integrate with Vite:
# - host: Main host for Vite's dev server. Default: localhost
# - port: Main port for Vite's dev server. Default: 5173
# - https: Whether to use HTTPS to connect to the dev server or not. Default: false
# - base_path: The prefix path added to the assets. Default: /packs-dev/
# - tag_strategies: How to generate javascript and stylesheet tags in views. Possible values are:
# * dev_server: Generate tags linking directly to the dev server through an internal proxy
# * manifest: Generate tags using assets listed in Vite's manifest files
# Default: [:dev_server, :manifest]
# - manifest_path: Where the manifest file is located. Default: public/packs-dev/.vite/manifest.json
# - manifest_assets_path: Where the manifest-assets file is located. Default: public/packs-dev/.vite/manifest-assets.json
# - auto_build: Whether to automatically build assets or not. This is useful for tess. Default: false
# - build_command: How to build assets when auto_build is enabled. Default: 'yarn build:development'
# - out_dir: Output dir for built assets. Default: 'public/packs-dev'
# - cache_dir: Vite's build cache path. Default: 'node_modules/.vite'
# - logger: Main logger instance for other Vite classes. Default: Logger.new($stdout)
class Config
attr_accessor :host,
:port,
:https,
:base_path,
:tag_strategies,
:manifest_path,
:manifest_assets_path,
:auto_build,
:build_command,
:out_dir,
:cache_dir,
:logger
def initialize(cnf = nil)
@host = 'localhost'
@port = 5173
@https = false
@base_path = '/packs-dev/'
@tag_strategies = [:dev_server, :manifest]
@manifest_path = 'public/packs-dev/.vite/manifest.json'
@manifest_assets_path = 'public/packs-dev/.vite/manifest-assets.json'
@auto_build = false
@build_command = 'yarn build:development'
@out_dir = 'public/packs-dev'
@cache_dir = 'node_modules/.vite'
@logger = Logger.new($stdout)
copy_from(cnf) unless cnf.nil?
end
def https?
https
end
def protocol
https? ? 'https' : 'http'
end
def backend
"#{protocol}://#{host}:#{port}"
end
def auto_build?
auto_build
end
def copy_from(other)
self.host = other[:host] unless other[:host].nil?
self.port = other[:port] unless other[:port].nil?
self.https = other[:https] unless other[:https].nil?
self.base_path = other[:base_path] unless other[:base_path].nil?
self.tag_strategies = other[:tag_strategies].map(&:to_sym) unless other[:tag_strategies].nil?
self.manifest_path = other[:manifest_path] unless other[:manifest_path].nil?
self.manifest_assets_path = other[:manifest_assets_path] unless other[:manifest_assets_path].nil?
self.out_dir = other[:out_dir] unless other[:out_dir].nil?
self.cache_dir = other[:cache_dir] unless other[:cache_dir].nil?
self.auto_build = other[:auto_build] unless other[:auto_build].nil?
self.build_command = other[:build_command] unless other[:build_command].nil?
end
end
end
+25
View File
@@ -0,0 +1,25 @@
# frozen_string_literal: true
module Vite
# Check the status of Vite's dev server
class DevServer
WAIT_TIME = 5 # seconds
attr_reader :config
def initialize(config:)
@config = config
end
# Original idea from vite_ruby gem
def running?
return @running if defined?(@running) && Time.now.to_i - @running_checked_at < WAIT_TIME
Socket.tcp(config.host, config.port).close
@running = true
rescue
@running = false
ensure
@running_checked_at = Time.now.to_i
end
end
end
+189
View File
@@ -0,0 +1,189 @@
# frozen_string_literal: true
module Vite
# We use two manifest files to list the assets loaded in our backend:
# - manifest.json: This is the main file that lists all the javascript and stylesheets our frontend app uses
# - manifest-assets.json: This only lists media assets linked directly from our backend, mainly images
#
# Not all the assets listed in the manifest.json file are linked or used by the app view, so we don't need to
# keep track of those. The idea behind this class is to keep track only of the main entrypoints and all their
# subsequent imports. Imports in this case include other javascript modules and stylesheets generated by Vite.
#
# This class focuses on reducing the amount of data we keep per entrypoint and making fast lookups. To do so
# it keeps two main datastructures:
# - entries: A Hash with references to each main entrypoint (including media assets)
# - pool: An Array with all the referenced imports and stylesheets
#
# Each entrypoint has a list of IDs for each import and stylesheet that it needs to load, this ID is
# an index to the main pool. With this the referenced asset is stored only once and referenced across
# entries with a unique ID. In the original manifest files references are also nested, if an entrypoint
# imports a javascript module, this first module can import other modules and stylesheet and so on. To keep
# fetching entrypoints fast, the final list of modules and stylesheets to load per entrypoint
# is expanded when loading the manifest data and not when rendering views. Each entrypoint has the final
# list of IDs of imports and stylesheets it will need to link in the backend, without further recursive
# checks.
class Manifest
class MissingManifestError < StandardError; end
class MissingEntryError < StandardError
def initialize(entry)
super("Failed to find entry '#{entry}' in manifest files")
end
end
attr_reader :config, :entries, :pool, :logger
def initialize(config:, logger:)
@config = config
@virtual = {}
@entries = {}
@pool = []
@loaded = false
@logger = logger
end
def reload
@loaded = false
load
end
def load
return if @loaded
retries = 0
begin
build if retries.positive?
load_manifest
@loaded = true
rescue Errno::ENOENT => e
if retries.zero? && config.auto_build?
retries = 1
retry
else
raise MissingManifestError, e.message
end
end
end
def fetch(name, type: nil)
load
key = type == :virtual ? @virtual[name] : name
entries[key]
end
def fetch!(name, type: nil)
fetch(name, type:) || raise(MissingEntryError, name)
end
def imports_for(entry)
find_entries(entry[:import_ids] || [])
end
def stylesheets_for(entry)
find_entries(entry[:stylesheet_ids] || [])
end
private
def load_manifest
@virtual = {}
@entries = {}
@pool = []
# intermediate Hash for fast lookups while parsing the manifest
@lookup = {}
logger.debug { "loading manifest file: #{config.manifest_path}" }
json = JSON.load_file(config.manifest_path)
json.each do |key, raw|
# Only select main entrypoints and locales
next unless raw['isEntry'] || key.start_with?('mastodon/locales/')
import_ids, stylesheet_ids = resolve_relations(json, raw)
@virtual[raw['name']] = key
@entries[key] = {
file: raw['file'],
integrity: raw['integrity'],
import_ids: import_ids,
stylesheet_ids: stylesheet_ids,
}
end
logger.debug { "loading manifest file: #{config.manifest_assets_path}" }
assets = JSON.load_file(config.manifest_assets_path)
assets.each do |key, raw|
@entries[key] = {
file: raw['file'],
integrity: raw['integrity'],
}
end
ensure
@lookup = {}
end
def build
logger.debug { 'AutoBuild enabled' }
builder.build
end
def builder
@builder ||= Vite::Builder.new(config:, logger:)
end
def resolve_relations(manifest, raw)
# NOTE: By using Set we make sure we add each asset only once
imports = Set.new
stylesheets = Set.new
raw['imports']&.each do |import|
raw_import = manifest[import]
next unless raw_import
id, deps = lookup(file: raw_import['file'], integrity: raw_import['integrity']) do
resolve_relations(manifest, raw_import)
end
imports.merge(deps[0])
stylesheets.merge(deps[1])
imports.add id
end
raw['css']&.each do |stylesheet|
# the css field includes the file names of the stylesheets and not
# the src names which are the ones used as keys in the manifest
raw_style = manifest.values.find { |value| value['file'] == stylesheet }
# some listed CSS files are not included as a entry in the manifest,
# but they are among the generated assets. We can still link to them
# but without the integrity field
raw_style = { 'file' => stylesheet } if raw_style.nil?
id, = lookup(file: raw_style['file'], integrity: raw_style['integrity'])
stylesheets.add id
end
[imports, stylesheets]
end
# Lookup in the internal cache if an entry has been processed
# If not, yield and save the result of the block as the entry deps
def lookup(file:, integrity:)
id, deps = @lookup[file] || []
if id.nil?
@pool << { file:, integrity: }
id = @pool.size - 1 # last ID
deps = yield if block_given?
@lookup[file] = [id, deps]
end
[id, deps]
end
def find_entries(ids)
ids.filter_map { |id| pool[id] }
end
end
end
+49
View File
@@ -0,0 +1,49 @@
# frozen_string_literal: true
module Vite
# When using assets in frontend views, we need to have an actual path that serves the asset.
# This path needs to include:
# - Vite's base_path, this is where the bundle is generated
# - If the asset needs to be included inside the main entrypoints path or not
#
# For convenience assets that are single file names (i.e: application.ts) are considered to
# be entrypoints. To make them work with Vite the `entrypoints/` prefix needs to be added.
# If an asset is referenced with a relative path like `styles/application.scss`, that path
# is used as is given.
#
# Examples:
# resolver = Vite::NameResolver.new(config: Vite.config)
# resolver.full_path('application.ts')
# # => '/packs-dev/entrypoints/application.ts'
# resolver.full_path('styles/application.scss')
# # => '/packs-dev/styles/application.scss'
#
# The #full_path is useful when working with Vite's dev server.
# When serving asssets from a manifest, it is necessary to resolve first the #entrypoint_path
# to have a proper reference of the asset inside the manifest file and then generate the
# #bundle_path of the asset's real file name defined in the manifest
class NameResolver
attr_reader :config
def initialize(config:)
@config = config
end
# Full path to the given asset
def full_path(name)
bundle_path(entrypoint_path(name))
end
# Determines if an asset name should be considered an entrypoint and builds
# the path accordingly
def entrypoint_path(name)
# If the name is a single file we assume it is inside app/javascripts/entrypoints
name.include?('/') ? name : "entrypoints/#{name}"
end
# Asset's bundle path that includes Vite's base_path as a prefix
def bundle_path(name)
"#{config.base_path}#{name}"
end
end
end
+25
View File
@@ -0,0 +1,25 @@
# frozen_string_literal: true
require 'rack/proxy'
module Vite
# Simple proxy that redirects asset requests to the running Vite dev server
class Proxy < Rack::Proxy
attr_reader :config, :dev_server
def initialize(app, config:, dev_server:, **)
@config = config
@dev_server = dev_server
super(app, backend: config.backend, ssl_verify_none: !config.https?, **)
end
def perform_request(env)
if dev_server.running? && env['PATH_INFO'].start_with?(config.base_path)
super
else
@app.call(env)
end
end
end
end
+241
View File
@@ -0,0 +1,241 @@
# frozen_string_literal: true
module Vite
# This class generates the HTML tags needed to load assets in the app views
#
# It does it by following different strategies:
# - dev_server: If Vite's dev server is running, it generates a simple tag
# for an asset that the server will know how to handle
# - manifest: When using a manifest, each asset is expanded in a collection
# of tags that include the main asset and all of their dependencies.
# For example a javascript asset includes an include tag for the main
# javascript file, preload tags for each of their dependencies and
# stylesheet links for each css module file generated by Vite
#
# When both :dev_server and :manifest strategies are defined, it will first
# try to use the :dev_server and if it's not running it will fallback to :manifest
class Tagger
SKIP = Object.new
module Common
def vite_preload_tag(helper, *sources, crossorigin:, **options)
url_options = options.extract!(:host, :protocol)
asset_paths = sources.map { |source| helper.path_to_asset(source, **url_options) }
helper.try(:request).try(
:send_early_hints,
'Link' => asset_paths.map do |href|
%(<#{href}>; rel=modulepreload; as=script; crossorigin=#{crossorigin})
end.join(',')
)
tags = asset_paths.map do |href|
helper.tag.link(rel: 'modulepreload', href:, as: 'script', crossorigin:, **options)
end
helper.safe_join(tags)
end
end
# When Vite's dev server is running we just need to generate tags
# linking to the main assets (javascript, stylesheets, etc) and the
# dev server will do the rest
class DevServerStrategy
include Common
attr_reader :config, :resolver, :dev_server
def initialize(config:, dev_server:)
@config = config
@dev_server = dev_server || DevServer.new(config:)
@resolver = NameResolver.new(config:)
end
def vite_client_tag(helper, crossorigin: 'anonymous', **)
return SKIP unless dev_server.running?
src = resolver.bundle_path('@vite/client')
helper.javascript_include_tag(src, type: 'module', extname: false, crossorigin:, **)
end
def vite_react_refresh_tag(helper, **options)
return SKIP unless dev_server.running?
options[:nonce] = true unless options.key?(:nonce)
react_refresh = resolver.bundle_path('@react-refresh')
preamble = <<~REACT_PREAMBLE_CODE.html_safe # rubocop:disable Rails/OutputSafety
import RefreshRuntime from '#{react_refresh}'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
REACT_PREAMBLE_CODE
helper.javascript_tag(preamble, type: :module, **options)
end
def vite_javascript_tag(helper, *names, type: 'module', crossorigin: '', asset_type: '', **) # rubocop:disable Lint/UnusedMethodArgument
return SKIP unless dev_server.running?
scripts = names.map { |name| resolver.full_path(name) }
helper.javascript_include_tag(*scripts, crossorigin:, type:, extname: false, **)
end
def vite_stylesheet_tag(helper, *names, type: :stylesheet, **options) # rubocop:disable Lint/UnusedMethodArgument
return SKIP unless dev_server.running?
style_paths = names.map { |name| resolver.full_path(name) }
options[:extname] = false
helper.stylesheet_link_tag(*style_paths, **options)
end
def vite_asset_path(helper, name, **_options)
return SKIP unless dev_server.running?
helper.path_to_asset resolver.full_path(name)
end
def vite_polyfills_tag(*)
return SKIP unless dev_server.running?
''
end
def vite_preload_file_tag(helper, name, crossorigin: 'anonymous', **)
return SKIP unless dev_server.running?
vite_preload_tag(helper, resolver.full_path(name), crossorigin:, **)
end
end
class ManifestStrategy
include Common
attr_reader :config, :manifest, :resolver
def initialize(config:, manifest: nil)
@config = config
@manifest = manifest || Manifest.new(config:, logger: config.logger)
@resolver = NameResolver.new(config:)
end
def vite_client_tag(*)
''
end
def vite_react_refresh_tag(*)
''
end
def vite_javascript_tag(helper, *names, type: 'module', crossorigin: '', asset_type: '', media: nil, **)
names = names.map { |name| resolver.entrypoint_path(name) }
scripts = []
preloads = []
stylesheets = []
entries = names.map { |name| manifest.fetch!(name, type: asset_type) }
entries.each do |entry|
scripts << helper.javascript_include_tag(
resolver.bundle_path(entry[:file]),
integrity: entry[:integrity],
crossorigin:,
type:,
extname: false,
**
)
preloads = manifest.imports_for(entry).map do |import|
vite_preload_tag(
helper,
resolver.bundle_path(import[:file]),
integrity: import[:integrity],
crossorigin:,
**
)
end
stylesheets = manifest.stylesheets_for(entry).map do |stylesheet|
helper.stylesheet_link_tag(
resolver.bundle_path(stylesheet[:file]),
integrity: stylesheet[:integrity],
crossorigin:,
media:,
**
)
end
end
helper.safe_join(scripts + preloads + stylesheets)
end
def vite_stylesheet_tag(helper, *names, type: :stylesheet, **options)
options[:extname] = false
stylesheets = names.map do |name|
entry = manifest.fetch!(resolver.entrypoint_path(name), type:)
helper.stylesheet_link_tag(
resolver.bundle_path(entry[:file]),
integrity: entry[:integrity],
**options
)
end
helper.safe_join(stylesheets)
end
def vite_asset_path(helper, name, type: nil, **)
entry = manifest.fetch!(resolver.entrypoint_path(name), type:)
helper.path_to_asset resolver.bundle_path(entry[:file])
end
def vite_polyfills_tag(helper, crossorigin: 'anonymous', **)
entry = manifest.fetch!('polyfills', type: :virtual)
helper.javascript_include_tag(
resolver.bundle_path(entry[:file]),
type: 'module',
integrity: entry[:integrity],
crossorigin:,
**
)
end
def vite_preload_file_tag(helper, name, crossorigin: 'anonymous', **)
entry = manifest.fetch(resolver.entrypoint_path(name))
return SKIP unless entry
vite_preload_tag(helper, resolver.bundle_path(entry[:file]), integrity: entry[:integrity], crossorigin:, **)
end
end
attr_reader :strategies
def initialize(config:, manifest: nil, dev_server: nil)
@strategies = config.tag_strategies.filter_map do |name|
case name
when :dev_server
DevServerStrategy.new(config:, dev_server:)
when :manifest
ManifestStrategy.new(config:, manifest:)
end
end
end
def method_missing(method, ...)
return super unless method.to_s.start_with?('vite_')
strategies.lazy.map { |s| s.__send__(method, ...) }.find { |result| result != SKIP } || ''
end
def respond_to_missing?(method, include_private = false)
return super unless method.to_s.start_with?('vite_')
strategies.all? { |s| s.respond_to?(method, include_private) }
end
end
end
+41
View File
@@ -0,0 +1,41 @@
# frozen_string_literal: true
module Vite
module TagsHelper
def vite_javascript_tag(*names, type: 'module', crossorigin: '', **)
Vite.tagger.vite_javascript_tag(self, *names, type:, crossorigin:, **)
end
def vite_typescript_tag(*names, **)
vite_javascript_tag(*names, asset_type: :typescript, **)
end
def vite_stylesheet_tag(*names, type: :stylesheet, **)
Vite.tagger.vite_stylesheet_tag(self, *names, type:, **)
end
def vite_client_tag(crossorigin: 'anonymous', **)
Vite.tagger.vite_client_tag(self, crossorigin:, **)
end
def vite_react_refresh_tag(**)
Vite.tagger.vite_react_refresh_tag(self, **)
end
def vite_asset_path(name, **)
Vite.tagger.vite_asset_path(self, name, **)
end
def vite_polyfills_tag(crossorigin: 'anonymous', **)
Vite.tagger.vite_polyfills_tag(self, crossorigin:, **)
end
def vite_preload_file_tag(name, crossorigin: 'anonymous', **)
Vite.tagger.vite_preload_file_tag(self, name, crossorigin:, **)
end
def vite_preload_tag(*sources, crossorigin:, **)
Vite.tagger.vite_preload_tag(self, *sources, crossorigin:, **)
end
end
end
+33
View File
@@ -0,0 +1,33 @@
# frozen_string_literal: true
module Vite
class Tasks
attr_reader :config, :logger
def initialize(config:)
@config = config
# We want tasks to always log out to STDOUT
@logger = ActiveSupport::TaggedLogging.new(
ActiveSupport::Logger.new($stdout)
).tagged('vite')
end
# Intended to run within assets:precompile task
def precompile
Vite::Builder.new(config:, logger:).build!
end
# Intended to run within assets:clobber task
def clobber
[config.out_dir, config.cache_dir].each do |path|
dir = Rails.root.join(path)
if dir.exist?
logger.info { "Deleting directory '#{dir}'" }
dir.rmtree
else
logger.info { "Directory '#{dir}' doesn't exist, nothing to delete" }
end
end
end
end
end
-153
View File
@@ -1,153 +0,0 @@
# frozen_string_literal: true
module ViteRuby::ManifestIntegrityExtension
def path_and_integrity_for(name, **)
entry = lookup!(name, **)
{ path: entry.fetch('file'), integrity: entry.fetch('integrity', nil) }
end
def load_manifest
# Invalidate the name lookup cache when reloading manifest
@name_lookup_cache = nil unless dev_server_running?
super
end
def load_name_lookup_cache
JSON.load_file(config.build_output_dir.join('.vite/manifest-lookup.json'))
end
# Upstream's `virtual` type is a hack, re-implement it with efficient exact name lookup
def resolve_virtual_entry(name)
return name if dev_server_running?
@name_lookup_cache ||= load_name_lookup_cache
@name_lookup_cache.fetch(name)
end
# Find a manifest entry by the *final* file name
def integrity_hash_for_file(file_name)
@integrity_cache ||= {}
@integrity_cache[file_name] ||= begin
entry = manifest.find { |_key, entry| entry['file'] == file_name }
entry[1].fetch('integrity', nil) if entry
end
end
def resolve_entries_with_integrity(*names, **options)
entries = names.map { |name| lookup!(name, **options) }
script_paths = entries.map do |entry|
{
file: entry.fetch('file'),
# TODO: Secure this so we require the integrity hash outside of dev
integrity: entry['integrity'],
}
end
imports = dev_server_running? ? [] : entries.flat_map { |entry| import_chunks_for(entry) }
{
scripts: script_paths,
imports: imports.filter_map { |entry| { file: entry.fetch('file'), integrity: entry.fetch('integrity') } }.uniq,
stylesheets: dev_server_running? ? [] : (entries + imports).flat_map { |entry| entry['css'] }.compact.uniq,
}
end
# We need to override this method to not include the manifest, as in our case it is too large and will cause a JSON max nesting error rather than raising the expected exception
def missing_entry_error(name, **)
raise ViteRuby::MissingEntrypointError.new(
file_name: resolve_entry_name(name, **),
last_build: builder.last_build_metadata,
manifest: '',
config: config
)
end
end
ViteRuby::Manifest.prepend ViteRuby::ManifestIntegrityExtension
module ViteRails::TagHelpers::IntegrityExtension
def vite_javascript_tag(*names,
type: 'module',
asset_type: :javascript,
skip_preload_tags: false,
skip_style_tags: false,
crossorigin: '',
media: nil,
**options)
entries = vite_manifest.resolve_entries_with_integrity(*names, type: asset_type)
''.html_safe.tap do |tags|
entries.fetch(:scripts).each do |script|
tags << javascript_include_tag(
script[:file],
integrity: script[:integrity],
crossorigin: crossorigin,
type: type,
extname: false,
**options
)
end
unless skip_preload_tags
entries.fetch(:imports).each do |import|
tags << vite_preload_tag(import[:file], integrity: import[:integrity], crossorigin: crossorigin, **options)
end
end
options[:extname] = false if Rails::VERSION::MAJOR >= 7
unless skip_style_tags
entries.fetch(:stylesheets).each do |stylesheet|
# This is for stylesheets imported from Javascript. The entry for the JS entrypoint only contains the final CSS file name, so we need to look it up in the manifest
tags << stylesheet_link_tag(
stylesheet,
integrity: vite_manifest.integrity_hash_for_file(stylesheet),
media: media,
crossorigin: crossorigin,
**options
)
end
end
end
end
def vite_stylesheet_tag(*names, type: :stylesheet, **options)
''.html_safe.tap do |tags|
names.each do |name|
entry = vite_manifest.path_and_integrity_for(name, type:)
options[:extname] = false if Rails::VERSION::MAJOR >= 7
tags << stylesheet_link_tag(entry[:path], integrity: entry[:integrity], **options)
end
end
end
def vite_preload_file_tag(name,
asset_type: :javascript,
crossorigin: 'anonymous', **options)
''.html_safe.tap do |tags|
entries = vite_manifest.resolve_entries_with_integrity(name, type: asset_type)
entries.fetch(:scripts).each do |script|
tags << vite_preload_tag(script[:file], integrity: script[:integrity], crossorigin: crossorigin, **options)
end
end
rescue ViteRuby::MissingEntrypointError
# Ignore this error, it is not critical if the file is not preloaded
end
def vite_polyfills_tag(crossorigin: 'anonymous', **)
return if ViteRuby.instance.dev_server_running?
entry = vite_manifest.path_and_integrity_for('polyfills', type: :virtual)
javascript_include_tag(entry[:path], type: 'module', integrity: entry[:integrity], crossorigin: crossorigin, **)
end
end
ViteRails::TagHelpers.prepend ViteRails::TagHelpers::IntegrityExtension