| 1 |
# frozen_string_literal: true |
| 2 |
|
| 3 |
require 'cgi' |
| 4 |
require 'asciidoctor/extensions' unless RUBY_ENGINE == 'opal' |
| 5 |
|
| 6 |
# Asciidoctor extensions |
| 7 |
# |
| 8 |
module AsciidoctorExtensions |
| 9 |
include Asciidoctor |
| 10 |
|
| 11 |
# A block extension that converts a diagram into an image. |
| 12 |
# |
| 13 |
class KrokiBlockProcessor < Extensions::BlockProcessor |
| 14 |
use_dsl |
| 15 |
|
| 16 |
on_context :listing, :literal |
| 17 |
name_positional_attributes 'target', 'format' |
| 18 |
|
| 19 |
# @param name [String] name of the block macro (optional) |
| 20 |
# @param config [Hash] a config hash (optional) |
| 21 |
# - :logger a logger used to log warning and errors (optional) |
| 22 |
# |
| 23 |
def initialize(name = nil, config = {}) |
| 24 |
@logger = (config || {}).delete(:logger) { ::Asciidoctor::LoggerManager.logger } |
| 25 |
super |
| 26 |
end |
| 27 |
|
| 28 |
def process(parent, reader, attrs) |
| 29 |
diagram_type = @name |
| 30 |
diagram_text = reader.string |
| 31 |
KrokiProcessor.process(self, parent, attrs, diagram_type, diagram_text, @logger) |
| 32 |
end |
| 33 |
|
| 34 |
protected |
| 35 |
|
| 36 |
attr_reader :logger |
| 37 |
end |
| 38 |
|
| 39 |
# A block macro extension that converts a diagram into an image. |
| 40 |
# |
| 41 |
class KrokiBlockMacroProcessor < Asciidoctor::Extensions::BlockMacroProcessor |
| 42 |
include Asciidoctor::Logging |
| 43 |
use_dsl |
| 44 |
|
| 45 |
name_positional_attributes 'format' |
| 46 |
|
| 47 |
# @param name [String] name of the block macro (optional) |
| 48 |
# @param config [Hash] a config hash (optional) |
| 49 |
# - :logger a logger used to log warning and errors (optional) |
| 50 |
# |
| 51 |
def initialize(name = nil, config = {}) |
| 52 |
@logger = (config || {}).delete(:logger) { ::Asciidoctor::LoggerManager.logger } |
| 53 |
super |
| 54 |
end |
| 55 |
|
| 56 |
# Processes the diagram block or block macro by converting it into an image or literal block. |
| 57 |
# |
| 58 |
# @param parent [Asciidoctor::AbstractBlock] the parent asciidoc block of the block or block macro being processed |
| 59 |
# @param target [String] the target value of a block macro |
| 60 |
# @param attrs [Hash] the attributes of the block or block macro |
| 61 |
# @return [Asciidoctor::AbstractBlock] a new block that replaces the original block or block macro |
| 62 |
def process(parent, target, attrs) |
| 63 |
diagram_type = @name |
| 64 |
target = parent.apply_subs(target, [:attributes]) |
| 65 |
|
| 66 |
unless read_allowed?(target) |
| 67 |
link = create_inline(parent, :anchor, target, type: :link, target: target) |
| 68 |
return create_block(parent, :paragraph, link.convert, {}, content_model: :raw) |
| 69 |
end |
| 70 |
|
| 71 |
unless (path = resolve_target_path(parent, target)) |
| 72 |
logger.error message_with_context "#{diagram_type} block macro not found: #{target}.", source_location: parent.document.reader.cursor_at_mark |
| 73 |
return create_block(parent, 'paragraph', unresolved_block_macro_message(diagram_type, target), {}) |
| 74 |
end |
| 75 |
|
| 76 |
begin |
| 77 |
diagram_text = read(path) |
| 78 |
rescue => e # rubocop:disable Style/RescueStandardError |
| 79 |
logger.error message_with_context "Failed to read #{diagram_type} file: #{path}. #{e}.", source_location: parent.document.reader.cursor_at_mark |
| 80 |
return create_block(parent, 'paragraph', unresolved_block_macro_message(diagram_type, path), {}) |
| 81 |
end |
| 82 |
KrokiProcessor.process(self, parent, attrs, diagram_type, diagram_text, @logger) |
| 83 |
end |
| 84 |
|
| 85 |
protected |
| 86 |
|
| 87 |
attr_reader :logger |
| 88 |
|
| 89 |
# @param parent [Asciidoctor::AbstractBlock] the parent asciidoc block of the block or block macro being processed |
| 90 |
# @param target [String] the target value of a block macro |
| 91 |
def resolve_target_path(parent, target) |
| 92 |
parent.normalize_system_path(target) |
| 93 |
end |
| 94 |
|
| 95 |
def read_allowed?(_target) |
| 96 |
true |
| 97 |
end |
| 98 |
|
| 99 |
def read(target) |
| 100 |
if target.start_with?('http://') || target.start_with?('https://') |
| 101 |
require 'open-uri' |
| 102 |
::OpenURI.open_uri(target, &:read) |
| 103 |
else |
| 104 |
File.read(target, mode: 'rb:utf-8:utf-8') |
| 105 |
end |
| 106 |
end |
| 107 |
|
| 108 |
def unresolved_block_macro_message(name, target) |
| 109 |
"Unresolved block macro - #{name}::#{target}[]" |
| 110 |
end |
| 111 |
end |
| 112 |
|
| 113 |
# Kroki API |
| 114 |
# |
| 115 |
module Kroki |
| 116 |
SUPPORTED_DIAGRAM_NAMES = %w[ |
| 117 |
actdiag |
| 118 |
blockdiag |
| 119 |
bpmn |
| 120 |
bytefield |
| 121 |
c4plantuml |
| 122 |
d2 |
| 123 |
dbml |
| 124 |
ditaa |
| 125 |
erd |
| 126 |
excalidraw |
| 127 |
goat |
| 128 |
graphviz |
| 129 |
mermaid |
| 130 |
nomnoml |
| 131 |
nwdiag |
| 132 |
packetdiag |
| 133 |
pikchr |
| 134 |
plantuml |
| 135 |
rackdiag |
| 136 |
seqdiag |
| 137 |
svgbob |
| 138 |
symbolator |
| 139 |
tikz |
| 140 |
umlet |
| 141 |
vega |
| 142 |
vegalite |
| 143 |
wavedrom |
| 144 |
structurizr |
| 145 |
diagramsnet |
| 146 |
wireviz |
| 147 |
].freeze |
| 148 |
end |
| 149 |
|
| 150 |
# Internal processor |
| 151 |
# |
| 152 |
class KrokiProcessor |
| 153 |
include Asciidoctor::Logging |
| 154 |
|
| 155 |
TEXT_FORMATS = %w[txt atxt utxt].freeze |
| 156 |
BUILTIN_ATTRIBUTES = %w[target width height format fallback link float align role caption title cloaked-context subs].freeze |
| 157 |
|
| 158 |
class << self |
| 159 |
# rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity |
| 160 |
def process(processor, parent, attrs, diagram_type, diagram_text, logger) |
| 161 |
doc = parent.document |
| 162 |
diagram_text = prepend_plantuml_config(diagram_text, diagram_type, doc, logger) |
| 163 |
# If "subs" attribute is specified, substitute accordingly. |
| 164 |
# Be careful not to specify "specialcharacters" or your diagram code won't be valid anymore! |
| 165 |
if (subs = attrs['subs']) |
| 166 |
diagram_text = parent.apply_subs(diagram_text, parent.resolve_subs(subs)) |
| 167 |
end |
| 168 |
attrs.delete('opts') |
| 169 |
# Apply the option defined on the block/macro or, as a fallback, the document-wide kroki-default-options. |
| 170 |
if (option = get_option(attrs, doc)) && option != 'none' |
| 171 |
attrs["#{option}-option"] = '' |
| 172 |
end |
| 173 |
format = get_format(doc, attrs, diagram_type) |
| 174 |
attrs['role'] = get_role(format, attrs['role']) |
| 175 |
attrs['format'] = format |
| 176 |
opts = attrs.filter { |key, _| key.is_a?(String) && BUILTIN_ATTRIBUTES.none? { |k| key == k } && !key.end_with?('-option') } |
| 177 |
kroki_diagram = KrokiDiagram.new(diagram_type, format, diagram_text, attrs['target'], opts) |
| 178 |
kroki_client = KrokiClient.new({ |
| 179 |
server_url: server_url(doc), |
| 180 |
http_method: http_method(doc), |
| 181 |
max_uri_length: max_uri_length(doc), |
| 182 |
source_location: doc.reader.cursor_at_mark, |
| 183 |
http_client: KrokiHttpClient |
| 184 |
}, logger) |
| 185 |
alt = get_alt(attrs) |
| 186 |
title = attrs.delete('title') |
| 187 |
caption = attrs.delete('caption') |
| 188 |
if TEXT_FORMATS.include?(format) |
| 189 |
text_content = kroki_client.text_content(kroki_diagram) |
| 190 |
block = processor.create_block(parent, 'literal', text_content, attrs) |
| 191 |
else |
| 192 |
attrs['alt'] = alt |
| 193 |
attrs['target'] = create_image_src(doc, kroki_diagram, kroki_client, logger) |
| 194 |
block = processor.create_image_block(parent, attrs) |
| 195 |
end |
| 196 |
block.title = title if title |
| 197 |
block.assign_caption(caption, 'figure') |
| 198 |
block |
| 199 |
end |
| 200 |
# rubocop:enable Metrics/AbcSize, Metrics/PerceivedComplexity |
| 201 |
|
| 202 |
private |
| 203 |
|
| 204 |
def prepend_plantuml_config(diagram_text, diagram_type, doc, logger) |
| 205 |
if diagram_type == :plantuml && doc.safe < ::Asciidoctor::SafeMode::SECURE && doc.attr?('kroki-plantuml-include') |
| 206 |
# REMIND: this behaves different than the JS version |
| 207 |
# Once we have a preprocessor for Ruby, the value should be added in the diagram source as "!include #{plantuml_include}" |
| 208 |
plantuml_include_path = doc.normalize_system_path(doc.attr('kroki-plantuml-include')) |
| 209 |
if ::File.readable? plantuml_include_path |
| 210 |
config = File.read(plantuml_include_path) |
| 211 |
diagram_text = "#{config}\n#{diagram_text}" |
| 212 |
else |
| 213 |
logger.warn message_with_context "Unable to read plantuml-include. File not found or not readable: #{plantuml_include_path}.", |
| 214 |
source_location: doc.reader.cursor_at_mark |
| 215 |
end |
| 216 |
end |
| 217 |
diagram_text |
| 218 |
end |
| 219 |
|
| 220 |
def get_alt(attrs) |
| 221 |
if (title = attrs['title']) |
| 222 |
title |
| 223 |
elsif (target = attrs['target']) |
| 224 |
target |
| 225 |
else |
| 226 |
'Diagram' |
| 227 |
end |
| 228 |
end |
| 229 |
|
| 230 |
def get_role(format, role) |
| 231 |
if role |
| 232 |
if format |
| 233 |
"#{role} kroki-format-#{format} kroki" |
| 234 |
else |
| 235 |
"#{role} kroki" |
| 236 |
end |
| 237 |
else |
| 238 |
'kroki' |
| 239 |
end |
| 240 |
end |
| 241 |
|
| 242 |
# Get the option defined on the block or macro. |
| 243 |
# |
| 244 |
# First, check if an option is defined as an attribute (e.g. opts=inline). |
| 245 |
# If there is no match, fall back to the document-wide kroki-default-options attribute. |
| 246 |
# |
| 247 |
# @param attrs [Hash] the block or macro attributes |
| 248 |
# @param doc [Asciidoctor::Document] the Asciidoctor document |
| 249 |
# @return [String, nil] the option name (inline, interactive or none) or nil |
| 250 |
def get_option(attrs, doc) |
| 251 |
available_options = %w[inline interactive none] |
| 252 |
available_options.find { |option| attrs["#{option}-option"] == '' } || |
| 253 |
available_options.find { |option| doc.attr('kroki-default-options') == option } |
| 254 |
end |
| 255 |
|
| 256 |
def get_format(doc, attrs, diagram_type) |
| 257 |
format = attrs['format'] || doc.attr('kroki-default-format') || 'svg' |
| 258 |
if format == 'png' |
| 259 |
# redirect PNG format to SVG if the diagram library only supports SVG as output format. |
| 260 |
# this is useful when the default format has been set to PNG |
| 261 |
# Currently, goat, nomnoml, svgbob, wavedrom only support SVG as output format. |
| 262 |
svg_only_diagram_types = %i[goat nomnoml svgbob wavedrom] |
| 263 |
format = 'svg' if svg_only_diagram_types.include?(diagram_type) |
| 264 |
end |
| 265 |
format |
| 266 |
end |
| 267 |
|
| 268 |
def create_image_src(doc, kroki_diagram, kroki_client, logger) |
| 269 |
if doc.attr('kroki-fetch-diagram') && doc.safe < ::Asciidoctor::SafeMode::SECURE |
| 270 |
kroki_diagram.save(output_dir_path(doc), kroki_client, generated_files(doc), logger) |
| 271 |
else |
| 272 |
kroki_diagram.get_diagram_uri(server_url(doc)) |
| 273 |
end |
| 274 |
end |
| 275 |
|
| 276 |
# Returns the per-document registry of generated file names, mapping each name |
| 277 |
# to the diagram URI it was generated from. Used to detect name clashes within |
| 278 |
# a single conversion. |
| 279 |
def generated_files(doc) |
| 280 |
doc.instance_variable_get(:@kroki_generated_files) || |
| 281 |
doc.instance_variable_set(:@kroki_generated_files, {}) |
| 282 |
end |
| 283 |
|
| 284 |
def server_url(doc) |
| 285 |
doc.attr('kroki-server-url', 'https://kroki.io') |
| 286 |
end |
| 287 |
|
| 288 |
def http_method(doc) |
| 289 |
doc.attr('kroki-http-method', 'adaptive').downcase |
| 290 |
end |
| 291 |
|
| 292 |
def max_uri_length(doc) |
| 293 |
doc.attr('kroki-max-uri-length', '4000').to_i |
| 294 |
end |
| 295 |
|
| 296 |
def output_dir_path(doc) |
| 297 |
images_dir = doc.attr('imagesdir', '') |
| 298 |
if (images_output_dir = doc.attr('imagesoutdir')) |
| 299 |
images_output_dir |
| 300 |
# the nested document logic will become obsolete once https://github.com/asciidoctor/asciidoctor/commit/7edc9da023522be67b17e2a085d72e056703a438 is released |
| 301 |
elsif (out_dir = doc.attr('outdir') || (doc.nested? ? doc.parent_document : doc).options[:to_dir]) |
| 302 |
File.join(out_dir, images_dir) |
| 303 |
else |
| 304 |
File.join(doc.base_dir, images_dir) |
| 305 |
end |
| 306 |
end |
| 307 |
end |
| 308 |
end |
| 309 |
|
| 310 |
# Kroki diagram |
| 311 |
# |
| 312 |
class KrokiDiagram |
| 313 |
require 'fileutils' |
| 314 |
require 'zlib' |
| 315 |
require 'digest' |
| 316 |
|
| 317 |
attr_reader :type, :text, :format, :target, :opts |
| 318 |
|
| 319 |
def initialize(type, format, text, target = nil, opts = {}) |
| 320 |
@text = text |
| 321 |
@type = type |
| 322 |
@format = format |
| 323 |
@target = target |
| 324 |
@opts = opts |
| 325 |
end |
| 326 |
|
| 327 |
def get_diagram_uri(server_url) |
| 328 |
query_params = opts.map { |k, v| "#{k}=#{_url_encode(v.to_s)}" }.join('&') unless opts.empty? |
| 329 |
_join_uri_segments(server_url, @type, @format, encode) + (query_params ? "?#{query_params}" : '') |
| 330 |
end |
| 331 |
|
| 332 |
def encode |
| 333 |
([Zlib::Deflate.deflate(@text, 9)].pack 'm0').tr '+/', '-_' |
| 334 |
end |
| 335 |
|
| 336 |
def save(output_dir_path, kroki_client, generated_files = nil, logger = nil) |
| 337 |
diagram_url = get_diagram_uri(kroki_client.server_url) |
| 338 |
# An explicit name is used verbatim so links stay stable across content changes; |
| 339 |
# otherwise the name is content-addressed so anonymous diagrams don't collide (see #451). |
| 340 |
named = @target.is_a?(::String) && [email protected]? |
| 341 |
diagram_name = named ? "#{@target}.#{@format}" : "diag-#{Digest::SHA256.hexdigest diagram_url}.#{@format}" |
| 342 |
file_path = File.join(output_dir_path, diagram_name) |
| 343 |
if named |
| 344 |
# A stable file may exist from a previous build with stale content, so always |
| 345 |
# re-fetch and overwrite. Warn when the same name is reused for a different diagram. |
| 346 |
warn_on_name_clash(generated_files, diagram_name, diagram_url, logger) |
| 347 |
generated_files[diagram_name] = diagram_url if generated_files |
| 348 |
fetch_and_write(output_dir_path, file_path, kroki_client) |
| 349 |
elsif !File.exist?(file_path) |
| 350 |
# Content-addressed name: an existing file necessarily has identical content. |
| 351 |
fetch_and_write(output_dir_path, file_path, kroki_client) |
| 352 |
end |
| 353 |
diagram_name |
| 354 |
end |
| 355 |
|
| 356 |
private |
| 357 |
|
| 358 |
def fetch_and_write(output_dir_path, file_path, kroki_client) |
| 359 |
contents = kroki_client.get_image(self, image_encoding) |
| 360 |
FileUtils.mkdir_p(output_dir_path) |
| 361 |
File.write(file_path, contents, mode: 'wb') |
| 362 |
end |
| 363 |
|
| 364 |
def warn_on_name_clash(generated_files, diagram_name, diagram_url, logger) |
| 365 |
return unless generated_files && logger |
| 366 |
|
| 367 |
previous_url = generated_files[diagram_name] |
| 368 |
return if previous_url.nil? || previous_url == diagram_url |
| 369 |
|
| 370 |
logger.warn "kroki: the diagram file name '#{diagram_name}' is generated by more than one diagram with different content; " \ |
| 371 |
'the file will be overwritten. Use unique names to keep stable links.' |
| 372 |
end |
| 373 |
|
| 374 |
def image_encoding |
| 375 |
case @format |
| 376 |
when 'txt', 'atxt', 'utxt', 'svg' |
| 377 |
'utf8' |
| 378 |
else |
| 379 |
'binary' |
| 380 |
end |
| 381 |
end |
| 382 |
|
| 383 |
def _url_encode(text) |
| 384 |
CGI.escape(text).gsub('+', '%20') |
| 385 |
end |
| 386 |
|
| 387 |
def _join_uri_segments(base, *uris) |
| 388 |
segments = [] |
| 389 |
# remove trailing slashes |
| 390 |
segments.push(base.gsub(%r{/+$}, '')) |
| 391 |
segments.concat(uris.map do |uri| |
| 392 |
# remove leading and trailing slashes |
| 393 |
uri.to_s |
| 394 |
.gsub(%r{^/+}, '') |
| 395 |
.gsub(%r{/+$}, '') |
| 396 |
end) |
| 397 |
segments.join('/') |
| 398 |
end |
| 399 |
end |
| 400 |
|
| 401 |
# Kroki client |
| 402 |
# |
| 403 |
class KrokiClient |
| 404 |
include Asciidoctor::Logging |
| 405 |
|
| 406 |
attr_reader :server_url, :method, :max_uri_length |
| 407 |
|
| 408 |
SUPPORTED_HTTP_METHODS = %w[get post adaptive].freeze |
| 409 |
|
| 410 |
def initialize(opts, logger = ::Asciidoctor::LoggerManager.logger) |
| 411 |
@server_url = opts[:server_url] |
| 412 |
@max_uri_length = opts.fetch(:max_uri_length, 4000) |
| 413 |
@http_client = opts[:http_client] |
| 414 |
method = opts.fetch(:http_method, 'adaptive').downcase |
| 415 |
if SUPPORTED_HTTP_METHODS.include?(method) |
| 416 |
@method = method |
| 417 |
else |
| 418 |
logger.warn message_with_context "Invalid value '#{method}' for kroki-http-method attribute. The value must be either: " \ |
| 419 |
"'get', 'post' or 'adaptive'. Proceeding using: 'adaptive'.", |
| 420 |
source_location: opts[:source_location] |
| 421 |
@method = 'adaptive' |
| 422 |
end |
| 423 |
end |
| 424 |
|
| 425 |
def text_content(kroki_diagram) |
| 426 |
get_image(kroki_diagram, 'utf-8') |
| 427 |
end |
| 428 |
|
| 429 |
def get_image(kroki_diagram, encoding) |
| 430 |
type = kroki_diagram.type |
| 431 |
format = kroki_diagram.format |
| 432 |
text = kroki_diagram.text |
| 433 |
opts = kroki_diagram.opts |
| 434 |
if @method == 'adaptive' || @method == 'get' |
| 435 |
uri = kroki_diagram.get_diagram_uri(server_url) |
| 436 |
if uri.length > @max_uri_length |
| 437 |
# The request URI is longer than the max URI length. |
| 438 |
if @method == 'get' |
| 439 |
# The request might be rejected by the server with a 414 Request-URI Too Large. |
| 440 |
# Consider using the attribute kroki-http-method with the value 'adaptive'. |
| 441 |
@http_client.get(uri, opts, encoding) |
| 442 |
else |
| 443 |
@http_client.post("#{@server_url}/#{type}/#{format}", text, opts, encoding) |
| 444 |
end |
| 445 |
else |
| 446 |
@http_client.get(uri, opts, encoding) |
| 447 |
end |
| 448 |
else |
| 449 |
@http_client.post("#{@server_url}/#{type}/#{format}", text, opts, encoding) |
| 450 |
end |
| 451 |
end |
| 452 |
end |
| 453 |
|
| 454 |
# Kroki HTTP client |
| 455 |
# |
| 456 |
class KrokiHttpClient |
| 457 |
require 'net/http' |
| 458 |
require 'uri' |
| 459 |
require 'json' |
| 460 |
|
| 461 |
class << self |
| 462 |
REFERER = "asciidoctor/kroki.rb/#{Asciidoctor::AsciidoctorKroki::VERSION}" |
| 463 |
|
| 464 |
def get(uri, opts, _) |
| 465 |
uri = URI(uri) |
| 466 |
headers = opts.transform_keys { |key| "Kroki-Diagram-Options-#{key}" } |
| 467 |
.merge({ 'referer' => REFERER }) |
| 468 |
request = ::Net::HTTP::Get.new(uri, headers) |
| 469 |
::Net::HTTP.start( |
| 470 |
uri.hostname, |
| 471 |
uri.port, |
| 472 |
use_ssl: (uri.scheme == 'https') |
| 473 |
) do |http| |
| 474 |
http.request(request).body |
| 475 |
end |
| 476 |
end |
| 477 |
|
| 478 |
def post(uri, data, opts, _) |
| 479 |
headers = opts.transform_keys { |key| "Kroki-Diagram-Options-#{key}" } |
| 480 |
.merge({ |
| 481 |
'Content-Type' => 'text/plain', |
| 482 |
'referer' => REFERER |
| 483 |
}) |
| 484 |
res = ::Net::HTTP.post( |
| 485 |
URI(uri), |
| 486 |
data, |
| 487 |
headers |
| 488 |
) |
| 489 |
res.body |
| 490 |
end |
| 491 |
end |
| 492 |
end |
| 493 |
end |