diff --git a/Gemfile b/Gemfile index 52d5e083ca..28b6044b19 100644 --- a/Gemfile +++ b/Gemfile @@ -74,6 +74,7 @@ gem 'public_suffix', '~> 7.0' gem 'pundit', '~> 2.3' gem 'rack-attack', '~> 6.6' gem 'rack-cors', require: 'rack/cors' +gem 'rack-proxy', require: 'rack/proxy' gem 'rails-i18n', '~> 8.0' gem 'redcarpet', '~> 3.6' gem 'redis', '~> 5' @@ -231,6 +232,4 @@ gem 'hcaptcha', '~> 7.1' gem 'mail', '~> 2.8' -gem 'vite_rails' - gem 'base58', '~> 0.2.3' diff --git a/Gemfile.lock b/Gemfile.lock index b0d2f3b30b..9105076482 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -214,7 +214,6 @@ GEM railties (>= 5) dotenv (3.2.0) drb (2.2.3) - dry-cli (1.4.1) elastic-transport (8.5.3) faraday (< 3) multi_json @@ -642,8 +641,8 @@ GEM base64 (>= 0.1.0) logger (>= 1.6.0) rack (>= 3.0.0, < 4) - rack-proxy (0.8.3) - rack + rack-proxy (1.0.1) + rack (>= 2.0, < 4) rack-session (2.1.2) base64 (>= 0.1.0) rack (>= 3.0.0) @@ -901,15 +900,6 @@ GEM validate_url (1.0.15) activemodel (>= 3.0.0) public_suffix - vite_rails (3.11.1) - railties (>= 5.1, < 9) - vite_ruby (~> 3.0, >= 3.2.2) - vite_ruby (3.10.2) - dry-cli (>= 0.7, < 2) - logger (~> 1.6) - mutex_m - rack-proxy (~> 0.6, >= 0.6.1) - zeitwerk (~> 2.2) warden (1.2.9) rack (>= 2.0.9) webauthn (3.4.3) @@ -1051,6 +1041,7 @@ DEPENDENCIES pundit (~> 2.3) rack-attack (~> 6.6) rack-cors + rack-proxy rack-test (~> 2.1) rails (~> 8.1.0) rails-i18n (~> 8.0) @@ -1091,7 +1082,6 @@ DEPENDENCIES tty-prompt (~> 0.23) twitter-text (~> 3.1.0) tzinfo-data (~> 1.2023) - vite_rails webauthn (~> 3.0) webmock (~> 3.18) webpush! diff --git a/app/helpers/routing_helper.rb b/app/helpers/routing_helper.rb index b5d090db49..8c69430eeb 100644 --- a/app/helpers/routing_helper.rb +++ b/app/helpers/routing_helper.rb @@ -4,7 +4,7 @@ module RoutingHelper extend ActiveSupport::Concern include ActionView::Helpers::AssetTagHelper - include ViteRails::TagHelpers + include Vite::TagsHelper included do include Rails.application.routes.url_helpers diff --git a/bin/vite b/bin/vite deleted file mode 100755 index 9664d0d987..0000000000 --- a/bin/vite +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# -# This file was generated by Bundler. -# -# The application 'vite' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) - -require "rubygems" -require "bundler/setup" - -load Gem.bin_path("vite_ruby", "vite") diff --git a/config/application.rb b/config/application.rb index 181924da64..6f502295e0 100644 --- a/config/application.rb +++ b/config/application.rb @@ -50,7 +50,6 @@ require_relative '../lib/action_dispatch/remote_ip_extensions' require_relative '../lib/active_record/database_tasks_extensions' require_relative '../lib/active_record/batches' require_relative '../lib/simple_navigation/item_extensions' -require_relative '../lib/vite_ruby/sri_extensions' require_relative '../lib/json-canonicalization/floats_fix' Bundler.require(:pam_authentication) if ENV['PAM_ENABLED'] == 'true' diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb index 33894db93f..b343c372dd 100644 --- a/config/initializers/content_security_policy.rb +++ b/config/initializers/content_security_policy.rb @@ -30,19 +30,21 @@ Rails.application.config.content_security_policy do |p| p.child_src :self, :blob, assets_host p.worker_src :self, :blob, assets_host - if Rails.env.development? - vite_public_host = ENV.fetch('VITE_DEV_SERVER_PUBLIC', "localhost:#{ViteRuby.config.port}") - front_end_build_urls = %w(ws http).map { |protocol| "#{protocol}#{'s' if ViteRuby.config.https}://#{vite_public_host}" } + p.connect_src :self, :data, :blob, *media_hosts, Rails.configuration.x.streaming_api_base_url + p.script_src :self, assets_host, "'wasm-unsafe-eval'" + p.frame_src :self, :https + p.style_src :self, assets_host + + next unless Rails.env.development? + + Rails.application.config.to_prepare do + vite_public_host = "#{Vite.config.host}:#{Vite.config.port}" + front_end_build_urls = %w(ws http).map { |protocol| "#{protocol}#{'s' if Vite.config.https?}://#{vite_public_host}" } p.connect_src :self, :data, :blob, *media_hosts, Rails.configuration.x.streaming_api_base_url, *front_end_build_urls p.script_src :self, :unsafe_inline, :unsafe_eval, assets_host p.frame_src :self, :https, :http p.style_src :self, assets_host, :unsafe_inline - else - p.connect_src :self, :data, :blob, *media_hosts, Rails.configuration.x.streaming_api_base_url - p.script_src :self, assets_host, "'wasm-unsafe-eval'" - p.frame_src :self, :https - p.style_src :self, assets_host end end diff --git a/config/initializers/vite.rb b/config/initializers/vite.rb new file mode 100644 index 0000000000..4294afc40d --- /dev/null +++ b/config/initializers/vite.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +require 'vite' + +Vite.setup do |config| + config.copy_from Rails.application.config_for(:vite) + config.logger = Rails.logger.tagged('vite') + + if Rails.env.development? + Rails.application.config.middleware.insert_before(0, Vite::Proxy, config:, dev_server: Vite.dev_server) + else + Rails.application.config.to_prepare do + Vite.preload if defined?(Rails::Server) || defined?(Rails::Console) + end + end +end diff --git a/config/vite.json b/config/vite.json deleted file mode 100644 index 254dc3365a..0000000000 --- a/config/vite.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "all": { - "sourceCodeDir": "app/javascript", - "additionalEntrypoints": [ - "~/{fonts,icons,images}/**/*", - "~/styles/entrypoints/*.scss" - ], - "watchAdditionalPaths": [] - }, - "production": { - "publicOutputDir": "packs" - }, - "development": { - "autoBuild": true, - "publicOutputDir": "packs-dev", - "port": 3036 - }, - "test": { - "autoBuild": true, - "publicOutputDir": "packs", - "port": 3037 - } -} diff --git a/config/vite.yml b/config/vite.yml new file mode 100644 index 0000000000..95d701c2ac --- /dev/null +++ b/config/vite.yml @@ -0,0 +1,36 @@ +# Main configuration for Vite integration inside Rails +# see lib/vite/config.rb for more info +# +# All values need to match Vite's configuration in vite.config.mts +shared: + cache_dir: 'node_modules/.vite' + +development: + host: 'localhost' + port: 3036 + https: false + base_path: '/packs-dev/' + manifest_path: 'public/packs-dev/.vite/manifest.json' + manifest_assets_path: 'public/packs-dev/.vite/manifest-assets.json' + auto_build: true + build_command: 'yarn build:development' + tag_strategies: ['dev_server', 'manifest'] + out_dir: 'public/packs-dev' + +test: + base_path: '/packs/' + manifest_path: 'public/packs/.vite/manifest.json' + manifest_assets_path: 'public/packs/.vite/manifest-assets.json' + auto_build: true + build_command: 'yarn build:production' + tag_strategies: ['manifest'] + out_dir: 'public/packs' + +production: + base_path: '/packs/' + manifest_path: 'public/packs/.vite/manifest.json' + manifest_assets_path: 'public/packs/.vite/manifest-assets.json' + auto_build: false + build_command: 'yarn build:production' + tag_strategies: ['manifest'] + out_dir: 'public/packs' diff --git a/config/vite/plugin-name-lookup.ts b/config/vite/plugin-name-lookup.ts deleted file mode 100644 index 82dbf712e2..0000000000 --- a/config/vite/plugin-name-lookup.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { relative, extname } from 'node:path'; - -import type { Plugin } from 'vite'; - -export function MastodonNameLookup(): Plugin { - const nameMap: Record = {}; - - let root = ''; - - return { - name: 'mastodon-name-lookup', - applyToEnvironment(environment) { - return !!environment.config.build.manifest; - }, - configResolved(userConfig) { - root = userConfig.root; - }, - generateBundle(options, bundle) { - if (!root) { - throw new Error( - 'MastodonNameLookup plugin requires the root to be set in the config.', - ); - } - - // Iterate over all chunks in the bundle and create a lookup map - for (const file in bundle) { - const chunk = bundle[file]; - if ( - chunk?.type !== 'chunk' || - !chunk.isEntry || - !chunk.facadeModuleId - ) { - continue; - } - - const relativePath = relative( - root, - sanitizeFileName(chunk.facadeModuleId), - ); - const ext = extname(relativePath); - const name = chunk.name.replace(ext, ''); - - if (nameMap[name]) { - throw new Error( - `Entrypoint ${relativePath} conflicts with ${nameMap[name]}`, - ); - } - - nameMap[name] = relativePath; - } - - this.emitFile({ - type: 'asset', - fileName: '.vite/manifest-lookup.json', - source: JSON.stringify(nameMap, null, 2), - }); - }, - }; -} - -// Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts -// https://datatracker.ietf.org/doc/html/rfc2396 -// eslint-disable-next-line no-control-regex -const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g; - -function sanitizeFileName(name: string): string { - return name.replace(INVALID_CHAR_REGEX, ''); -} diff --git a/lib/premailer_bundled_asset_strategy.rb b/lib/premailer_bundled_asset_strategy.rb index f02f49e6f9..1c31bd2b68 100644 --- a/lib/premailer_bundled_asset_strategy.rb +++ b/lib/premailer_bundled_asset_strategy.rb @@ -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 diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake index de722f6bc1..0b0f114ec6 100644 --- a/lib/tasks/assets.rake +++ b/lib/tasks/assets.rake @@ -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 diff --git a/lib/vite.rb b/lib/vite.rb new file mode 100644 index 0000000000..98944cda9c --- /dev/null +++ b/lib/vite.rb @@ -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 diff --git a/lib/vite/builder.rb b/lib/vite/builder.rb new file mode 100644 index 0000000000..5e97b43232 --- /dev/null +++ b/lib/vite/builder.rb @@ -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 diff --git a/lib/vite/config.rb b/lib/vite/config.rb new file mode 100644 index 0000000000..cc974d788a --- /dev/null +++ b/lib/vite/config.rb @@ -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 diff --git a/lib/vite/dev_server.rb b/lib/vite/dev_server.rb new file mode 100644 index 0000000000..0e463c2ac7 --- /dev/null +++ b/lib/vite/dev_server.rb @@ -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 diff --git a/lib/vite/manifest.rb b/lib/vite/manifest.rb new file mode 100644 index 0000000000..9812c39637 --- /dev/null +++ b/lib/vite/manifest.rb @@ -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 diff --git a/lib/vite/name_resolver.rb b/lib/vite/name_resolver.rb new file mode 100644 index 0000000000..03eb2f2acd --- /dev/null +++ b/lib/vite/name_resolver.rb @@ -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 diff --git a/lib/vite/proxy.rb b/lib/vite/proxy.rb new file mode 100644 index 0000000000..e63e75f253 --- /dev/null +++ b/lib/vite/proxy.rb @@ -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 diff --git a/lib/vite/tagger.rb b/lib/vite/tagger.rb new file mode 100644 index 0000000000..febed5ddf5 --- /dev/null +++ b/lib/vite/tagger.rb @@ -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 diff --git a/lib/vite/tags_helper.rb b/lib/vite/tags_helper.rb new file mode 100644 index 0000000000..5d434c4a66 --- /dev/null +++ b/lib/vite/tags_helper.rb @@ -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 diff --git a/lib/vite/tasks.rb b/lib/vite/tasks.rb new file mode 100644 index 0000000000..0c81150ce5 --- /dev/null +++ b/lib/vite/tasks.rb @@ -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 diff --git a/lib/vite_ruby/sri_extensions.rb b/lib/vite_ruby/sri_extensions.rb deleted file mode 100644 index 139483d057..0000000000 --- a/lib/vite_ruby/sri_extensions.rb +++ /dev/null @@ -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 diff --git a/package.json b/package.json index 3cbca6116f..6b4a5fb7ac 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ ], "scripts": { "dev": "vite dev", - "build:development": "cross-env RAILS_ENV=development NODE_ENV=development vite build", - "build:production": "cross-env RAILS_ENV=production NODE_ENV=production vite build", + "build:development": "cross-env RAILS_ENV=development NODE_ENV=development vite build --mode development", + "build:production": "cross-env RAILS_ENV=production NODE_ENV=production vite build --mode production", "fix:js": "eslint . --cache --fix", "fix:css": "stylelint --fix \"**/*.{css,scss}\"", "fix": "yarn fix:js && yarn fix:css", diff --git a/spec/fixtures/files/vite-manifest-assets.json b/spec/fixtures/files/vite-manifest-assets.json new file mode 100644 index 0000000000..c27c53fb8a --- /dev/null +++ b/spec/fixtures/files/vite-manifest-assets.json @@ -0,0 +1,6 @@ +{ + "icons/main.png": { + "file": "assets/main-abc.png", + "integrity": "abc-9" + } +} diff --git a/spec/fixtures/files/vite-manifest.json b/spec/fixtures/files/vite-manifest.json new file mode 100644 index 0000000000..76d42fe7b7 --- /dev/null +++ b/spec/fixtures/files/vite-manifest.json @@ -0,0 +1,101 @@ +{ + "mastodon/locales/en-GB.json": { + "file": "intl/en-GB.js", + "name": "en-GB", + "src": "mastodon/locales/en-GB.json", + "isDynamicEntry": true, + "integrity": "abc-1" + }, + "entrypoints/application.ts": { + "file": "application.js", + "name": "application", + "src": "entrypoints/application.ts", + "isEntry": true, + "imports": ["_no-deps.js", "_dep-1.js", "_dep-2.js"], + "css": ["assets/main.css", "assets/unlisted.css"], + "integrity": "abc-2" + }, + "entrypoints/admin.ts": { + "file": "admin.js", + "name": "admin", + "src": "entrypoints/admin.ts", + "isEntry": true, + "imports": ["_no-deps.js", "_dep-1.js", "_dep-2.js", "_dep-3.js"], + "css": ["assets/main.css", "assets/unlisted.css"], + "integrity": "cba-2" + }, + "_no-deps.js": { + "file": "no-deps.js", + "name": "no-deps", + "integrity": "abc-3" + }, + "_dep-1.js": { + "file": "dep-1.js", + "name": "dep-1", + "imports": ["_dep-1-1.js", "_dep-1-2.js"], + "css": ["assets/dep-1.css", "assets/dep-2.css"], + "integrity": "abc-4" + }, + "_dep-2.js": { + "file": "dep-2.js", + "name": "dep-2", + "imports": ["_dep-1-1.js"], + "css": ["assets/dep-2.css"], + "integrity": "abc-5" + }, + "_dep-3.js": { + "file": "dep-3.js", + "name": "dep-3", + "integrity": "cba-5" + }, + "_dep-1-1.js": { + "file": "dep-1-1.js", + "name": "dep-1-1", + "css": ["assets/dep-1-1.css"], + "integrity": "abc-6" + }, + "_dep-1-2.js": { + "file": "dep-1-2.js", + "name": "dep-1-2", + "integrity": "abc-7" + }, + "../legacy/polyfills.js": { + "file": "polyfills.js", + "name": "polyfills", + "isEntry": true, + "integrity": "abc-8" + }, + "styles/entrypoints/inert.scss": { + "file": "assets/inert-xyz.css", + "name": "inert", + "names": ["inert.css"], + "src": "styles/entrypoints/inert.scss", + "isEntry": true, + "integrity": "abc-10" + }, + "_main.css": { + "file": "assets/main.css", + "src": "_main.css", + "integrity": "abc-11" + }, + "_dep-1.css": { + "file": "assets/dep-1.css", + "src": "_dep-1.css", + "integrity": "abc-12" + }, + "_dep-2.css": { + "file": "assets/dep-2.css", + "src": "_dep-2.css", + "integrity": "abc-13" + }, + "_dep-1-1.css": { + "file": "assets/dep-1-1.css", + "src": "_dep-1-1.css", + "integrity": "abc-14" + }, + "node_modules/somepackage.js": { + "file": "package.js", + "src": "node_modules/somepackage.js", + "integrity": "noop" + } +} diff --git a/spec/lib/vite/builder_spec.rb b/spec/lib/vite/builder_spec.rb new file mode 100644 index 0000000000..eb14f7b6a3 --- /dev/null +++ b/spec/lib/vite/builder_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::Builder do + subject { described_class.new(config:, logger:) } + + let(:config) { Struct.new(:build_command).new('echo "spec builder"') } + let(:buffer) { StringIO.new } + let(:logger) { Logger.new(buffer) } + + describe '#build' do + it 'executes the configured build_command and logs the output' do + subject.build + + buffer.rewind + + expect(buffer.read).to include('spec builder') + end + end + + describe '#build!' do + context 'when the command fails' do + let(:config) { Struct.new(:build_command).new('false') } + + it 'raises an error' do + expect { subject.build! }.to raise_error(Vite::Builder::BuildError) + end + end + end +end diff --git a/spec/lib/vite/config_spec.rb b/spec/lib/vite/config_spec.rb new file mode 100644 index 0000000000..200bda7251 --- /dev/null +++ b/spec/lib/vite/config_spec.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::Config do + subject { described_class.new } + + describe '#backend' do + it 'returns the full dev server URL' do + expect(subject.backend).to eq('http://localhost:5173') + end + end + + describe '#copy_from' do + let(:other) do + { + host: '127.0.0.1', + port: 3036, + https: true, + base_path: '/specs/', + tag_strategies: ['dev_server'], + manifest_path: 'public/specs/.vite/manifest.json', + manifest_assets_path: 'public/specs/.vite/manifest-assets.json', + auto_build: true, + build_command: 'echo "spec config"', + out_dir: 'public/specs', + cache_dir: 'tmp/.vite', + } + end + + before do + subject.copy_from(other) + end + + it 'copies server data from a hash' do + expect(subject.host).to eq(other[:host]) + expect(subject.port).to eq(other[:port]) + expect(subject.https?).to eq(other[:https]) + expect(subject.base_path).to eq(other[:base_path]) + end + + it 'copies manifest data from a hash' do + expect(subject.tag_strategies).to eq([:dev_server]) + expect(subject.manifest_path).to eq(other[:manifest_path]) + expect(subject.manifest_assets_path).to eq(other[:manifest_assets_path]) + end + + it 'copies build data from a hash' do + expect(subject.auto_build?).to eq(other[:auto_build]) + expect(subject.build_command).to eq(other[:build_command]) + end + + it 'copies asset management data from a hash' do + expect(subject.out_dir).to eq(other[:out_dir]) + expect(subject.cache_dir).to eq(other[:cache_dir]) + end + end +end diff --git a/spec/lib/vite/dev_server_spec.rb b/spec/lib/vite/dev_server_spec.rb new file mode 100644 index 0000000000..0e9ca111e9 --- /dev/null +++ b/spec/lib/vite/dev_server_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::DevServer do + subject { described_class.new(config:) } + + # port == 0 means that it will pick up any available port provided by the OS + let(:server) { TCPServer.new('localhost', 0) } + let!(:config) { Struct.new(:host, :port).new('localhost', server.addr[1]) } + + after { server.close } + + describe '#running?' do + context 'when the server is running' do + it 'returns true' do + expect(subject.running?).to be(true) + end + end + + context 'when the server is not running' do + it 'returns false' do + server.close + + expect(subject.running?).to be(false) + end + end + end +end diff --git a/spec/lib/vite/manifest_spec.rb b/spec/lib/vite/manifest_spec.rb new file mode 100644 index 0000000000..cc0636ea0f --- /dev/null +++ b/spec/lib/vite/manifest_spec.rb @@ -0,0 +1,142 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::Manifest do + subject { described_class.new(config:, logger:) } + + let(:config) do + Vite::Config.new({ + auto_build: false, + manifest_path: manifest_path, + manifest_assets_path: manifest_assets_path, + }) + end + + let(:logger) { Logger.new(StringIO.new) } + + let(:manifest_path) { manifest_file.to_path } + let(:manifest_assets_path) { manifest_assets_file.to_path } + + let(:manifest_file) { file_fixture('vite-manifest.json') } + let(:manifest_assets_file) { file_fixture('vite-manifest-assets.json') } + + describe '#fetch' do + it 'gets assets from manifest_assets' do + entry = subject.fetch('icons/main.png') + expect(entry[:file]).to eq('assets/main-abc.png') + expect(entry[:integrity]).to eq('abc-9') + end + + it 'gets locales' do + entry = subject.fetch('mastodon/locales/en-GB.json') + expect(entry[:file]).to eq('intl/en-GB.js') + expect(entry[:integrity]).to eq('abc-1') + end + + it 'gets virtual assets' do + entry = subject.fetch('polyfills', type: :virtual) + expect(entry[:file]).to eq('polyfills.js') + expect(entry[:integrity]).to eq('abc-8') + end + + it 'gets stylesheets' do + entry = subject.fetch('styles/entrypoints/inert.scss') + expect(entry[:file]).to eq('assets/inert-xyz.css') + expect(entry[:integrity]).to eq('abc-10') + end + + context 'when assets have dependencies' do + let(:entry) { subject.fetch('entrypoints/application.ts') } + + it 'gets the entrypoint' do + expect(entry[:file]).to eq('application.js') + expect(entry[:integrity]).to eq('abc-2') + end + + it 'resolves all the imports from bottom to top without duplicates' do + imports = subject.imports_for(entry).pluck(:file) + expect(imports).to eq(%w(no-deps.js dep-1-1.js dep-1-2.js dep-1.js dep-2.js)) + end + + it 'resolves all the stylesheets from bottom to top without duplicates' do + stylesheets = subject.stylesheets_for(entry).pluck(:file) + expect(stylesheets).to eq(%w(assets/dep-1-1.css assets/dep-1.css assets/dep-2.css assets/main.css assets/unlisted.css)) + end + + context 'when another entrypoint has the same dependencies' do + let(:entry) { subject.fetch('entrypoints/admin.ts') } + + it 'resolves all the imports from bottom to top without duplicates' do + imports = subject.imports_for(entry).pluck(:file) + expect(imports).to eq(%w(no-deps.js dep-1-1.js dep-1-2.js dep-1.js dep-2.js dep-3.js)) + end + + it 'resolves all the stylesheets from bottom to top without duplicates' do + stylesheets = subject.stylesheets_for(entry).pluck(:file) + expect(stylesheets).to eq(%w(assets/dep-1-1.css assets/dep-1.css assets/dep-2.css assets/main.css assets/unlisted.css)) + end + end + end + end + + describe 'fetch!' do + it 'raises an error on missing entries' do + expect { subject.fetch!('missing.ts') }.to raise_error(Vite::Manifest::MissingEntryError) + end + end + + describe '#load' do + it 'has one reference per entrypoint' do + subject.load + + entries = subject.entries + expect(entries.keys.count).to eq(6) + end + + it 'only keeps track of dependencies' do + subject.load + + pool = subject.pool + expect(pool.count).to eq(11) + # This file is present in the manifest but not referenced by any entrypoint + expect(pool.find { |entry| entry[:file] == 'package.js' }).to be_nil + end + + context 'when the manifest is missing' do + let(:manifest_path) { 'tmp/missing.json' } + + it 'raises an error' do + expect { subject.load }.to raise_error(Vite::Manifest::MissingManifestError) + end + + context 'when auto_build is enabled' do + let(:config) do + Vite::Config.new({ + auto_build: true, + manifest_path: manifest_path, + manifest_assets_path: manifest_assets_path, + }) + end + + let(:manifest_path) { Rails.root.join('tmp', 'vite-manifest.json') } + + let(:builder) { instance_double(Vite::Builder) } + + after do + FileUtils.rm_f(manifest_path) + end + + it 'builds on missing file' do + allow(Vite::Builder).to receive(:new).and_return(builder) + allow(builder).to receive(:build) do + # Create an empty file + File.write(manifest_path, '{}') + end + + expect { subject.load }.to_not raise_error + end + end + end + end +end diff --git a/spec/lib/vite/name_resolver_spec.rb b/spec/lib/vite/name_resolver_spec.rb new file mode 100644 index 0000000000..7407995921 --- /dev/null +++ b/spec/lib/vite/name_resolver_spec.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::NameResolver do + subject { described_class.new(config:) } + + let(:config) { Struct.new(:base_path).new('/specs/') } + + describe '#full_path' do + context 'with an entrypoint' do + it 'returns full path' do + expect(subject.full_path('common.ts')).to eq('/specs/entrypoints/common.ts') + end + end + + context 'with a nested path' do + it 'returns full path' do + expect(subject.full_path('styles/application.scss')).to eq('/specs/styles/application.scss') + end + end + end + + describe '#entrypoint_path' do + context 'with an entrypoint' do + it 'returns entrypoint path' do + expect(subject.entrypoint_path('common.ts')).to eq('entrypoints/common.ts') + end + end + + context 'with a nested path' do + it 'returns entrypoint path' do + expect(subject.entrypoint_path('styles/application.scss')).to eq('styles/application.scss') + end + end + end + + describe '#bundle_path' do + context 'with an entrypoint' do + it 'returns bundle path' do + expect(subject.bundle_path('entrypoints/common.ts')).to eq('/specs/entrypoints/common.ts') + end + end + + context 'with a nested path' do + it 'returns bundle path' do + expect(subject.bundle_path('styles/application.scss')).to eq('/specs/styles/application.scss') + end + end + end +end diff --git a/spec/lib/vite/proxy_spec.rb b/spec/lib/vite/proxy_spec.rb new file mode 100644 index 0000000000..399f9bb241 --- /dev/null +++ b/spec/lib/vite/proxy_spec.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::Proxy do + include Rack::Test::Methods + + subject { described_class.new(stack, config:, dev_server:) } + + let(:app) { subject } + + let(:stack) { ->(_env) { [404, { 'content-type' => 'text/plain' }, ['Not Found']] } } + + let(:config) do + Vite::Config.new({ https: false, base_path: '/specs/' }) + end + + describe '#call' do + context 'when the dev server is running' do + let(:dev_server) do + Class.new do + def self.running? + true + end + end + end + + before do + # This represent Vite's dev server + stub_request(:get, "#{config.backend}/specs/app.js").to_return(status: 200, body: 'script') + end + + it 'proxies asset requests' do + get '/specs/app.js' + expect(last_response.ok?).to be(true) + expect(last_response.body).to eq('script') + end + + it 'does not proxy other requests' do + get '/accounts' + expect(last_response).to have_http_status(404) + end + end + + context 'when the dev server is not running' do + let(:dev_server) do + Class.new do + def self.running? + false + end + end + end + + it 'does not proxy asset requests' do + get '/specs/app.js' + expect(last_response).to have_http_status(404) + end + + it 'does not proxy other requests' do + get '/accounts' + expect(last_response).to have_http_status(404) + end + end + end +end diff --git a/spec/lib/vite/tagger_spec.rb b/spec/lib/vite/tagger_spec.rb new file mode 100644 index 0000000000..2b88af0912 --- /dev/null +++ b/spec/lib/vite/tagger_spec.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Vite::Tagger do + include RSpec::Rails::HelperExampleGroup + + subject { described_class.new(config:, manifest:, dev_server:) } + + let(:manifest) { Vite::Manifest.new(config:, logger:) } + + let(:logger) { Logger.new(StringIO.new) } + + let(:manifest_path) { manifest_file.to_path } + let(:manifest_assets_path) { manifest_assets_file.to_path } + + let(:manifest_file) { file_fixture('vite-manifest.json') } + let(:manifest_assets_file) { file_fixture('vite-manifest-assets.json') } + + let(:nonce) { 'hoGYqEChtkb4m4rpaLV1ng==' } + + context 'with :dev_server strategy' do + let(:config) do + Vite::Config.new({ + auto_build: false, + manifest_path: manifest_path, + manifest_assets_path: manifest_assets_path, + base_path: '/packs-dev/', + tag_strategies: [:dev_server], + }) + end + + let(:dev_server) do + Class.new do + def self.running? + true + end + end + end + + describe '#vite_client_tag' do + it 'returns @vite/client tag' do + tag = subject.vite_client_tag(helper) + expect(tag.to_s).to eq('') + end + end + + describe '#vite_react_refresh_tag' do + let(:react_refresh) do + <<~JAVASCRIPT.html_safe + import RefreshRuntime from '/packs-dev/@react-refresh' + RefreshRuntime.injectIntoGlobalHook(window) + window.$RefreshReg$ = () => {} + window.$RefreshSig$ = () => (type) => type + window.__vite_plugin_react_preamble_installed__ = true + JAVASCRIPT + end + + it 'returns react-refresh tag' do + tag = subject.vite_react_refresh_tag(helper, nonce:) + expect(tag.to_s).to eq(helper.javascript_tag(react_refresh, type: :module, nonce:)) + end + end + + describe '#vite_javascript_tag' do + it 'generates a simple include tag' do + tag = subject.vite_javascript_tag(helper, 'application.ts') + expect(tag.to_s).to eq('') + end + end + + describe '#vite_stylesheet_tag' do + it 'generates a simple link tag' do + tag = subject.vite_stylesheet_tag(helper, 'styles/application.scss') + expect(tag.to_s).to eq('') + end + end + + describe '#vite_asset_path' do + it 'returns full path to asset' do + expect(subject.vite_asset_path(helper, 'icons/main.png')).to eq('/packs-dev/icons/main.png') + end + end + + describe '#vite_polyfills_tag' do + it 'returns an empty string' do + expect(subject.vite_polyfills_tag(helper)).to eq('') + end + end + + describe '#vite_preload_file_tag' do + it 'returns a preload link tag' do + tag = subject.vite_preload_file_tag(helper, 'mastodon/locales/en-GB.json') + expect(tag.to_s).to eq('') + end + end + end + + context 'with :manifest strategy' do + let(:config) do + Vite::Config.new({ + auto_build: false, + manifest_path: manifest_path, + manifest_assets_path: manifest_assets_path, + base_path: '/packs-dev/', + tag_strategies: [:manifest], + }) + end + + let(:dev_server) do + Class.new do + def self.running? + false + end + end + end + + describe '#vite_client_tag' do + it 'returns an empty string' do + expect(subject.vite_client_tag(helper)).to eq('') + end + end + + describe '#vite_react_refresh_tag' do + it 'returns an empty string' do + expect(subject.vite_react_refresh_tag(helper)).to eq('') + end + end + + describe '#vite_javascript_tag' do + let(:expected) do + '' \ + '' \ + '' \ + '' \ + '' \ + '' \ + '' \ + '' \ + '' \ + '' \ + '' + end + + it 'returns tags for the main javascript module and its dependencies' do + tag = subject.vite_javascript_tag(helper, 'application.ts') + expect(tag.to_s).to eq(expected) + end + end + + describe '#vite_stylesheet_tag' do + it 'returns stylesheet link tag to the bundled asset' do + tag = subject.vite_stylesheet_tag(helper, 'styles/entrypoints/inert.scss') + expect(tag.to_s).to eq('') + end + end + + describe '#vite_asset_path' do + it 'returns path to the bundled asset' do + expect(subject.vite_asset_path(helper, 'icons/main.png')).to eq('/packs-dev/assets/main-abc.png') + end + end + + describe '#vite_polyfills_tag' do + it 'returns include tag to polyfill module' do + tag = subject.vite_polyfills_tag(helper) + expect(tag.to_s).to eq('') + end + end + + describe '#vite_preload_file_tag' do + it 'returns a preload link tag to bundled asset' do + tag = subject.vite_preload_file_tag(helper, 'mastodon/locales/en-GB.json') + expect(tag.to_s).to eq('') + end + end + end + + context 'with both strategies' do + let(:config) do + Vite::Config.new({ + auto_build: false, + manifest_path: manifest_path, + manifest_assets_path: manifest_assets_path, + base_path: '/packs-dev/', + tag_strategies: [:dev_server, :manifest], + }) + end + + context 'when the dev server is running' do + let(:dev_server) do + Class.new do + def self.running? + true + end + end + end + + it 'uses :dev_server strategy' do + expect(subject.vite_client_tag(helper)).to_not be_empty + end + end + + context 'when the dev server is not running' do + let(:dev_server) do + Class.new do + def self.running? + false + end + end + end + + it 'uses :manifest strategy' do + expect(subject.vite_client_tag(helper)).to be_empty + end + end + end +end diff --git a/vite.config.mts b/vite.config.mts index 8b2cefb8f5..8bc4882894 100644 --- a/vite.config.mts +++ b/vite.config.mts @@ -21,7 +21,6 @@ import svgr from 'vite-plugin-svgr'; import { MastodonAssetsManifest } from './config/vite/plugin-assets-manifest'; import { MastodonThemes } from './config/vite/plugin-mastodon-themes'; -import { MastodonNameLookup } from './config/vite/plugin-name-lookup'; import { MastodonServiceWorkerChunkPaths } from './config/vite/plugin-sw-chunk-paths'; import { MastodonServiceWorkerLocales } from './config/vite/plugin-sw-locales'; @@ -105,10 +104,14 @@ export const config: UserConfigFnPromise = async ({ mode, command }) => { // but it needs to be scoped to the whole domain 'Service-Worker-Allowed': '/', }, - hmr: { + hmr: true, + ws: { // 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', + // The client can't connect through the main Rails app proxy since it doesn't support + // WebSockets. It needs to connect directly to Vite's server, that's why we set the port again + clientPort: 3036, }, port: 3036, }, @@ -202,7 +205,6 @@ export const config: UserConfigFnPromise = async ({ mode, command }) => { (visualizer({ template: process.env.CI ? 'raw-data' : 'treemap', }) as PluginOption), - MastodonNameLookup(), ], } satisfies UserConfig; };