Skip to content

A platform for community discussion. Free, open, simple.

2.1 KB
Raw Blame
# frozen_string_literal: true

# The extractor requires a markdown engine context, and building one means a
# V8 isolate evaluating the whole engine bundle (~70ms warm) — too much to pay
# per example. Contexts are stateless across scans, so they are memoized per
# configuration for the whole spec run (one isolate is ~33 MiB RSS, so specs
# should reuse the canonical configurations here rather than inventing
# near-duplicates) and disposed together after the suite.
module MarkdownEngineHelper
  def self.bundle
    @bundle ||= Migrations::Converters::MarkdownEngine::Bundle.load_or_build
  end

  def self.close_all
    @contexts&.each_value(&:close)
    @contexts = nil
  end

  def self.context_for(category_slugs: [], tag_names: [], custom_emoji_names: [], settings: {})
    key = [category_slugs.sort, tag_names.sort, custom_emoji_names.sort, settings.sort]
    @contexts ||= {}
    @contexts[key] ||= Migrations::Converters::MarkdownEngine::Context.new(
      bundle:,
      config:
        Migrations::Converters::MarkdownEngine::Config.new(
          source_settings: settings,
          category_slugs:,
          tag_names:,
          custom_emoji_names:,
        ),
    )
  end

  # Runs `js` inside a memoized context's isolate, for a spec that needs the
  # engine's JavaScript surface itself rather than a scan of a body.
  def self.eval_js(js, **config)
    context_for(**config).instance_variable_get(:@context).eval(js)
  end

  # An engine configuration matching a raw-extractor spec's Ruby-side name
  # sets. Whether a slug resolves as a category or a tag does not reach the
  # extracted rows (the forced type comes from the source's `::type` suffix),
  # so every name goes into both name sets — `Config` derives what the
  # engine's lookup needs from them.
  def self.context_for_names(hashtag_names:, custom_emoji_names: [], settings: {})
    context_for(
      category_slugs: hashtag_names,
      tag_names: hashtag_names,
      custom_emoji_names:,
      settings: { "unicode_usernames" => true }.merge(settings),
    )
  end
end

RSpec.configure { |config| config.after(:suite) { MarkdownEngineHelper.close_all } }