typst-rails 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +88 -0
- data/README.md +323 -1
- data/lib/typst-rails.rb +7 -0
- data/lib/typst_rails/backends/base.rb +24 -1
- data/lib/typst_rails/backends/cli.rb +24 -10
- data/lib/typst_rails/backends/gem.rb +19 -2
- data/lib/typst_rails/data_serializer.rb +294 -0
- data/lib/typst_rails/diagnostics.rb +284 -0
- data/lib/typst_rails/errors.rb +139 -0
- data/lib/typst_rails/handler.rb +51 -9
- data/lib/typst_rails/rage_integration.rb +7 -7
- data/lib/typst_rails/rails_rendering.rb +58 -0
- data/lib/typst_rails/renderer.rb +171 -85
- data/lib/typst_rails/sinatra_integration.rb +6 -12
- data/lib/typst_rails/template_rendering.rb +252 -0
- data/lib/typst_rails/version.rb +1 -1
- data/lib/typst_rails.rb +131 -0
- metadata +9 -6
data/lib/typst_rails/renderer.rb
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
require "tmpdir"
|
|
4
4
|
require "fileutils"
|
|
5
5
|
require "json"
|
|
6
|
+
require "typst_rails/errors"
|
|
6
7
|
require "typst_rails/helpers"
|
|
7
8
|
require "typst_rails/backends"
|
|
9
|
+
require "typst_rails/data_serializer"
|
|
8
10
|
|
|
9
11
|
# Only require ActiveSupport extensions if available
|
|
10
12
|
begin
|
|
@@ -59,6 +61,10 @@ module TypstRails
|
|
|
59
61
|
# source mentions it.
|
|
60
62
|
DATA_FILE_NAME = "typst_data.json"
|
|
61
63
|
|
|
64
|
+
# Root of the key paths that serialization errors give for locals, as in
|
|
65
|
+
# "locals.items[0].amount". Instance variables are named "@name" instead.
|
|
66
|
+
LOCALS_PATH = "locals"
|
|
67
|
+
|
|
62
68
|
# Holds the filesystem paths used during a single compilation run. Each
|
|
63
69
|
# run gets its own directory so concurrent renders never share a
|
|
64
70
|
# typst_data.json.
|
|
@@ -72,21 +78,33 @@ module TypstRails
|
|
|
72
78
|
# @return [Object, nil] The view context providing access to helpers and instance variables
|
|
73
79
|
attr_reader :view_context
|
|
74
80
|
|
|
81
|
+
# @return [String, nil] Display name of the template, used in error
|
|
82
|
+
# messages and passed to {TypstRails::Configuration#on_warning}
|
|
83
|
+
attr_reader :template
|
|
84
|
+
|
|
75
85
|
# MARK: - Initialization
|
|
76
86
|
|
|
77
87
|
# Initializes the renderer with the Typst template source.
|
|
78
88
|
#
|
|
79
89
|
# @param source [String] The Typst template source code
|
|
90
|
+
# @param template [String, Pathname, nil] A name for the template, such as
|
|
91
|
+
# "app/views/reports/show.pdf.typ". Error messages and warnings use it
|
|
92
|
+
# in place of the temporary file Typst actually compiles. The Rails
|
|
93
|
+
# handler and the Sinatra and Rage helpers pass it for you.
|
|
80
94
|
# @return [Renderer] A new renderer instance
|
|
81
95
|
# @raise [ArgumentError] if source is nil
|
|
82
96
|
# @raise [ArgumentError] if source is too large (exceeds MAX_SOURCE_SIZE)
|
|
83
97
|
#
|
|
84
98
|
# @example
|
|
85
99
|
# renderer = Renderer.new("= Hello, Typst!")
|
|
86
|
-
|
|
100
|
+
#
|
|
101
|
+
# @example Naming the template for error messages
|
|
102
|
+
# renderer = Renderer.new(File.read(path), template: path)
|
|
103
|
+
def initialize(source, template: nil)
|
|
87
104
|
raise ArgumentError, "Source cannot be nil" if source.nil?
|
|
88
105
|
|
|
89
106
|
@source = source.to_s
|
|
107
|
+
@template = template&.to_s
|
|
90
108
|
|
|
91
109
|
return unless @source.bytesize > MAX_SOURCE_SIZE
|
|
92
110
|
|
|
@@ -106,7 +124,8 @@ module TypstRails
|
|
|
106
124
|
# @return [String] Binary string containing the PDF data
|
|
107
125
|
# @raise [ArgumentError] if local_assigns is not a Hash
|
|
108
126
|
# @raise [ArgumentError] if source is empty
|
|
109
|
-
# @raise [TypstRails::
|
|
127
|
+
# @raise [TypstRails::CompileError] if Typst rejects the template
|
|
128
|
+
# @raise [TypstRails::Error] if compilation fails for another reason
|
|
110
129
|
#
|
|
111
130
|
# @example Render with plain data
|
|
112
131
|
# renderer = Renderer.new("= #data.title")
|
|
@@ -127,7 +146,10 @@ module TypstRails
|
|
|
127
146
|
local_assigns
|
|
128
147
|
end
|
|
129
148
|
|
|
130
|
-
|
|
149
|
+
warnings = []
|
|
150
|
+
pdf = compile_typst_source(@source, data_for_typst, warnings)
|
|
151
|
+
report_warnings(warnings)
|
|
152
|
+
pdf
|
|
131
153
|
end
|
|
132
154
|
|
|
133
155
|
# MARK: - Private Methods
|
|
@@ -145,12 +167,14 @@ module TypstRails
|
|
|
145
167
|
#
|
|
146
168
|
# @param typst_source [String] The Typst template source
|
|
147
169
|
# @param data [Hash] Data to be made available to the Typst template via JSON
|
|
170
|
+
# @param warnings [Array<Diagnostics::Diagnostic>] receives warnings
|
|
171
|
+
# reported by a successful compile
|
|
148
172
|
# @return [String] Binary PDF data
|
|
149
173
|
# @raise [ArgumentError] if typst_source is empty or data is not a Hash
|
|
150
174
|
# @raise [TypstRails::Error] if compilation fails or produces no output
|
|
151
175
|
#
|
|
152
176
|
# @note This method ensures all temporary files are cleaned up even if errors occur
|
|
153
|
-
def compile_typst_source(typst_source, data = {})
|
|
177
|
+
def compile_typst_source(typst_source, data = {}, warnings = [])
|
|
154
178
|
raise ArgumentError, "typst_source cannot be empty" if typst_source.nil? || typst_source.empty?
|
|
155
179
|
raise ArgumentError, "data must be a Hash" unless data.is_a?(Hash)
|
|
156
180
|
|
|
@@ -158,7 +182,7 @@ module TypstRails
|
|
|
158
182
|
begin
|
|
159
183
|
write_typst_source_file(paths, typst_source)
|
|
160
184
|
write_typst_data_file(paths, data) if reads_data_file?(typst_source)
|
|
161
|
-
run_typst_compiler(paths)
|
|
185
|
+
run_typst_compiler(paths, warnings)
|
|
162
186
|
rescue Error
|
|
163
187
|
raise
|
|
164
188
|
rescue StandardError => e
|
|
@@ -198,27 +222,79 @@ module TypstRails
|
|
|
198
222
|
typst_source.include?(DATA_FILE_NAME)
|
|
199
223
|
end
|
|
200
224
|
|
|
225
|
+
# Writes +data+ to typst_data.json next to the Typst source, where the
|
|
226
|
+
# template loads it with `json("typst_data.json")`.
|
|
227
|
+
#
|
|
228
|
+
# The data is converted with {DataSerializer} first, and every value is
|
|
229
|
+
# treated as a local: anything without a faithful JSON form raises. Data
|
|
230
|
+
# from {#collect_data_for_typst} is already plain, so this pass is cheap
|
|
231
|
+
# there; it does the real work for renders without a view context.
|
|
232
|
+
#
|
|
233
|
+
# @raise [SerializationError] if a value has no faithful JSON form
|
|
234
|
+
# @raise [TypstRails::Error] if the file cannot be written
|
|
201
235
|
def write_typst_data_file(paths, data)
|
|
202
236
|
return if data.nil? || data.empty?
|
|
203
237
|
|
|
204
|
-
|
|
205
|
-
# The Typst template would then use `json("typst_data.json")` to load this data.
|
|
238
|
+
json = JSON.generate(DataSerializer.normalize(data, path: LOCALS_PATH))
|
|
206
239
|
paths.data_file_path = File.join(paths.dir, DATA_FILE_NAME)
|
|
207
|
-
File.write(paths.data_file_path,
|
|
240
|
+
File.write(paths.data_file_path, json)
|
|
208
241
|
rescue JSON::GeneratorError => e
|
|
209
242
|
raise Error, "Failed to serialize data to JSON: #{e.message}"
|
|
243
|
+
rescue Error
|
|
244
|
+
raise
|
|
210
245
|
rescue StandardError => e
|
|
211
246
|
raise Error, "Failed to write data file: #{e.message}"
|
|
212
247
|
end
|
|
213
248
|
|
|
214
|
-
|
|
249
|
+
# Backends may yield diagnostic output from a successful compile; the
|
|
250
|
+
# warnings in it are collected here and reported once rendering is done,
|
|
251
|
+
# so an on_warning handler that raises is not mistaken for a compile
|
|
252
|
+
# failure.
|
|
253
|
+
def run_typst_compiler(paths, warnings)
|
|
215
254
|
backend = Backends::Registry.resolve(configured_backend)
|
|
216
|
-
backend.compile(paths.typ_path, paths.root)
|
|
255
|
+
backend.compile(paths.typ_path, paths.root) do |diagnostic_text|
|
|
256
|
+
warnings.concat(Diagnostics.parse(path_rewriter(paths).rewrite(diagnostic_text)).select(&:warning?))
|
|
257
|
+
end
|
|
258
|
+
rescue CompileError => e
|
|
259
|
+
error = contextualize(e, paths)
|
|
260
|
+
log_error(error.message)
|
|
261
|
+
raise error
|
|
217
262
|
rescue Error => e
|
|
218
263
|
log_error(e.message)
|
|
219
264
|
raise
|
|
220
265
|
end
|
|
221
266
|
|
|
267
|
+
# Rebuilds a backend's CompileError with the template's name in place of
|
|
268
|
+
# the temporary paths. The original stays available as #cause.
|
|
269
|
+
def contextualize(error, paths)
|
|
270
|
+
CompileError.new(
|
|
271
|
+
path_rewriter(paths).rewrite(error.typst_message),
|
|
272
|
+
template: @template, command: error.command, source: @source
|
|
273
|
+
)
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
def path_rewriter(paths)
|
|
277
|
+
Diagnostics::PathRewriter.new(
|
|
278
|
+
typ_path: paths.typ_path, run_dir: paths.dir, root: paths.root, template: @template
|
|
279
|
+
)
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
def report_warnings(warnings)
|
|
283
|
+
return if warnings.empty?
|
|
284
|
+
|
|
285
|
+
handler = configured_warning_handler
|
|
286
|
+
handler&.call(warnings, @template)
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
# @return [#call, nil] TypstRails.configuration.on_warning, or the default
|
|
290
|
+
# logger when TypstRails has not been configured
|
|
291
|
+
def configured_warning_handler
|
|
292
|
+
config = TypstRails.respond_to?(:configuration) ? TypstRails.configuration : nil
|
|
293
|
+
return Diagnostics.method(:log_warnings) unless config
|
|
294
|
+
|
|
295
|
+
config.on_warning
|
|
296
|
+
end
|
|
297
|
+
|
|
222
298
|
# @return [Symbol, Backends::Base, nil] the backend preference from
|
|
223
299
|
# TypstRails.configuration, or nil if the top-level TypstRails module
|
|
224
300
|
# (and its Configuration) hasn't been loaded (e.g. when only
|
|
@@ -249,90 +325,114 @@ module TypstRails
|
|
|
249
325
|
warn "Failed to clean up #{description}: #{e.message}"
|
|
250
326
|
end
|
|
251
327
|
|
|
252
|
-
# Collects data from
|
|
328
|
+
# Collects the data for typst_data.json from the view context's instance
|
|
329
|
+
# variables (its `assigns`) and +local_assigns+, which win on a name clash.
|
|
330
|
+
#
|
|
331
|
+
# Values are converted with {DataSerializer}, under two policies:
|
|
332
|
+
#
|
|
333
|
+
# - A local was passed on purpose, so one without a faithful JSON form
|
|
334
|
+
# raises {SerializationError}, naming its key path.
|
|
335
|
+
# - Instance variables include incidental ones (a form object, a service,
|
|
336
|
+
# a Proc), so one without a faithful JSON form is left out, and a single
|
|
337
|
+
# warning per render lists what was left out and why.
|
|
338
|
+
#
|
|
339
|
+
# Assigns whose names begin with an underscore are skipped silently. Rails
|
|
340
|
+
# keeps its own controller state in such variables and filters them from
|
|
341
|
+
# `assigns` itself; gems that add their own (such as `@_current_ability`)
|
|
342
|
+
# are skipped the same way.
|
|
253
343
|
#
|
|
254
|
-
#
|
|
255
|
-
#
|
|
256
|
-
#
|
|
344
|
+
# Conversion happens only when the template reads typst_data.json. For
|
|
345
|
+
# other templates the merged values are returned as they are, since they
|
|
346
|
+
# are never written.
|
|
257
347
|
#
|
|
258
348
|
# @param view_context [Object] The view context (typically from Rails/Sinatra)
|
|
259
349
|
# @param local_assigns [Hash] Local variables passed to the template
|
|
260
|
-
# @return [Hash
|
|
350
|
+
# @return [Hash{Symbol => Object}] The data, keyed by symbolized name
|
|
261
351
|
# @raise [ArgumentError] if local_assigns is not a Hash
|
|
352
|
+
# @raise [SerializationError] if a local has no faithful JSON form
|
|
262
353
|
# @raise [TypstRails::Error] if data collection fails
|
|
263
|
-
#
|
|
264
|
-
# @note Instance variables from view_context take precedence over local_assigns
|
|
265
|
-
# @note All values are transformed for JSON serialization (dates to ISO8601, etc.)
|
|
266
354
|
def collect_data_for_typst(view_context, local_assigns)
|
|
267
355
|
raise ArgumentError, "local_assigns must be a Hash" unless local_assigns.is_a?(Hash)
|
|
268
356
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
if view_context.respond_to?(:assigns)
|
|
273
|
-
assigns = view_context.assigns
|
|
274
|
-
if assigns.is_a?(Hash)
|
|
275
|
-
assigns.each do |key, value|
|
|
276
|
-
data[key.to_sym] = value # Convert keys to symbols for consistency.
|
|
277
|
-
end
|
|
278
|
-
end
|
|
279
|
-
end
|
|
280
|
-
|
|
281
|
-
# Local assigns (e.g., from `render locals: {...}`) merge in, taking precedence.
|
|
282
|
-
data.merge!(local_assigns.symbolize_keys)
|
|
357
|
+
locals = local_assigns.symbolize_keys
|
|
358
|
+
assigns = data_assigns(view_context).reject { |name, _| locals.key?(name) }
|
|
359
|
+
return assigns.merge(locals) unless reads_data_file?(@source)
|
|
283
360
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
361
|
+
data = normalize_assigns(assigns)
|
|
362
|
+
locals.each do |name, value|
|
|
363
|
+
data[name] = DataSerializer.normalize(value, path: DataSerializer.child_path(LOCALS_PATH, name))
|
|
287
364
|
end
|
|
288
|
-
|
|
365
|
+
data
|
|
366
|
+
rescue ArgumentError, Error
|
|
289
367
|
raise
|
|
290
368
|
rescue StandardError => e
|
|
291
369
|
raise Error, "Failed to collect data for Typst template: #{e.message}"
|
|
292
370
|
end
|
|
293
371
|
|
|
294
|
-
#
|
|
372
|
+
# @return [Hash{Symbol => Object}] the view context's assigns, minus
|
|
373
|
+
# underscore-prefixed internals
|
|
374
|
+
def data_assigns(view_context)
|
|
375
|
+
return {} unless view_context.respond_to?(:assigns)
|
|
376
|
+
|
|
377
|
+
assigns = view_context.assigns
|
|
378
|
+
return {} unless assigns.is_a?(Hash)
|
|
379
|
+
|
|
380
|
+
assigns.each_with_object({}) do |(key, value), result|
|
|
381
|
+
result[key.to_sym] = value unless key.to_s.start_with?("_")
|
|
382
|
+
end
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# Converts each assign, leaving out and warning about those that have no
|
|
386
|
+
# faithful JSON form.
|
|
295
387
|
#
|
|
296
|
-
#
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
388
|
+
# @return [Hash{Symbol => Object}]
|
|
389
|
+
def normalize_assigns(assigns)
|
|
390
|
+
omitted = []
|
|
391
|
+
data = assigns.each_with_object({}) do |(name, value), result|
|
|
392
|
+
result[name] = DataSerializer.normalize(value, path: "@#{name}")
|
|
393
|
+
rescue SerializationError => e
|
|
394
|
+
omitted << "@#{name} (#{e.path} #{e.reason})"
|
|
395
|
+
end
|
|
396
|
+
warn_about_omitted_assigns(omitted) unless omitted.empty?
|
|
397
|
+
data
|
|
398
|
+
end
|
|
399
|
+
|
|
400
|
+
def warn_about_omitted_assigns(omitted)
|
|
401
|
+
log_warning("Left #{omitted.size} instance variable(s) out of #{DATA_FILE_NAME} because they are not " \
|
|
402
|
+
"JSON-serializable: #{omitted.join("; ")}. If the template needs one, pass it as a local " \
|
|
403
|
+
"in a serializable form.")
|
|
404
|
+
end
|
|
405
|
+
|
|
406
|
+
# Transforms a value into plain JSON data.
|
|
302
407
|
#
|
|
303
|
-
#
|
|
304
|
-
#
|
|
408
|
+
# Kept for compatibility; it delegates to {DataSerializer.normalize}. Hash
|
|
409
|
+
# keys and Symbols come back as Strings, and values with no faithful JSON
|
|
410
|
+
# form raise {SerializationError} rather than passing through unchanged.
|
|
305
411
|
#
|
|
306
|
-
# @
|
|
307
|
-
#
|
|
308
|
-
#
|
|
412
|
+
# @param value [Object] The value to transform
|
|
413
|
+
# @return [Object] Plain JSON data
|
|
414
|
+
# @raise [SerializationError] if the value has no faithful JSON form
|
|
309
415
|
#
|
|
310
|
-
# @example
|
|
311
|
-
# transform_value_for_json_serialization([Date.
|
|
312
|
-
# # => ["2024-01-15", "
|
|
416
|
+
# @example
|
|
417
|
+
# transform_value_for_json_serialization([Date.new(2024, 1, 15), :draft])
|
|
418
|
+
# # => ["2024-01-15", "draft"]
|
|
313
419
|
def transform_value_for_json_serialization(value)
|
|
314
|
-
|
|
315
|
-
value.as_json # Use Rails' built-in JSON serialization for ActiveRecord objects.
|
|
316
|
-
elsif value.is_a?(Date) || value.is_a?(Time) || value.is_a?(DateTime)
|
|
317
|
-
value.iso8601 # Convert date/time objects to ISO8601 strings.
|
|
318
|
-
elsif value.is_a?(Array)
|
|
319
|
-
value.map { |v| transform_value_for_json_serialization(v) } # Recursively transform array elements.
|
|
320
|
-
elsif value.is_a?(Hash)
|
|
321
|
-
# Recursively transform hash values.
|
|
322
|
-
value.transform_values do |v_hash|
|
|
323
|
-
transform_value_for_json_serialization(v_hash)
|
|
324
|
-
end
|
|
325
|
-
else
|
|
326
|
-
value # Return other types as-is, assuming they are JSON-serializable.
|
|
327
|
-
end
|
|
420
|
+
DataSerializer.normalize(value, path: "value")
|
|
328
421
|
end
|
|
329
422
|
|
|
330
|
-
#
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
423
|
+
# Logs a warning to Rails.logger when available, otherwise with warn.
|
|
424
|
+
#
|
|
425
|
+
# @param message [String] The warning, without the "TypstRails:" prefix
|
|
426
|
+
# @return [void]
|
|
427
|
+
def log_warning(message)
|
|
428
|
+
formatted_message = "TypstRails: #{message}"
|
|
429
|
+
if defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
|
|
430
|
+
::Rails.logger.warn formatted_message
|
|
431
|
+
else
|
|
432
|
+
warn formatted_message
|
|
433
|
+
end
|
|
434
|
+
rescue StandardError
|
|
435
|
+
warn formatted_message
|
|
336
436
|
end
|
|
337
437
|
|
|
338
438
|
# Logs an error message to the appropriate logger.
|
|
@@ -399,18 +499,4 @@ module TypstRails
|
|
|
399
499
|
@view_context.respond_to?(method_name, include_private) || super
|
|
400
500
|
end
|
|
401
501
|
end
|
|
402
|
-
|
|
403
|
-
# Error class for Typst-related errors.
|
|
404
|
-
#
|
|
405
|
-
# Raised when Typst compilation fails, when files cannot be created,
|
|
406
|
-
# or when other Typst-specific errors occur during rendering.
|
|
407
|
-
#
|
|
408
|
-
# @example Handling Typst errors
|
|
409
|
-
# begin
|
|
410
|
-
# renderer.render(nil, data)
|
|
411
|
-
# rescue TypstRails::Error => e
|
|
412
|
-
# Rails.logger.error "Typst compilation failed: #{e.message}"
|
|
413
|
-
# render plain: "PDF generation failed", status: 500
|
|
414
|
-
# end
|
|
415
|
-
class Error < StandardError; end
|
|
416
502
|
end
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "typst_rails/template_rendering"
|
|
4
|
+
|
|
3
5
|
module TypstRails
|
|
4
6
|
# Integration for Sinatra framework
|
|
5
7
|
module SinatraIntegration
|
|
6
8
|
# Simple view context wrapper providing the `assigns` reader that
|
|
7
|
-
# Renderer expects, mirroring Rails' view context interface.
|
|
8
|
-
|
|
9
|
+
# Renderer expects, mirroring Rails' view context interface. Kept for
|
|
10
|
+
# compatibility; the helper now goes through {TemplateRendering}.
|
|
11
|
+
ViewContext = ::TypstRails::TemplateRendering::ViewContext
|
|
9
12
|
|
|
10
13
|
def self.setup
|
|
11
14
|
return unless defined?(::Sinatra)
|
|
12
15
|
|
|
13
|
-
require "typst_rails/renderer"
|
|
14
|
-
require "typst_rails/erb_source"
|
|
15
|
-
|
|
16
16
|
# Extend Sinatra with Typst rendering capabilities
|
|
17
17
|
::Sinatra::Base.class_eval do
|
|
18
18
|
include ::TypstRails::Helpers
|
|
@@ -21,13 +21,7 @@ module TypstRails
|
|
|
21
21
|
# first, in the route's scope, with +locals+ as local variables;
|
|
22
22
|
# +locals+ are also written to typst_data.json.
|
|
23
23
|
def typst(template, locals = {}, _options = {})
|
|
24
|
-
|
|
25
|
-
renderer = ::TypstRails::Renderer.new(typst_source)
|
|
26
|
-
|
|
27
|
-
# Sinatra doesn't have the same view context as Rails,
|
|
28
|
-
# so we create a simple wrapper
|
|
29
|
-
view_context = ::TypstRails::SinatraIntegration::ViewContext.new(locals)
|
|
30
|
-
pdf_data = renderer.render(view_context, locals)
|
|
24
|
+
pdf_data = ::TypstRails::TemplateRendering.render_file(template, self, locals, locals)
|
|
31
25
|
|
|
32
26
|
content_type "application/pdf"
|
|
33
27
|
pdf_data
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "pathname"
|
|
4
|
+
require "stringio"
|
|
5
|
+
require "typst_rails/erb_source"
|
|
6
|
+
require "typst_rails/framework_detection"
|
|
7
|
+
require "typst_rails/helpers"
|
|
8
|
+
require "typst_rails/rails_rendering"
|
|
9
|
+
require "typst_rails/renderer"
|
|
10
|
+
|
|
11
|
+
module TypstRails
|
|
12
|
+
# Renders a `.typ` template file to PDF outside a request: in a background
|
|
13
|
+
# job, a mailer, a rake task, or a script.
|
|
14
|
+
#
|
|
15
|
+
# The template runs through ERB first, with +locals+ as local variables,
|
|
16
|
+
# +assigns+ as instance variables, and the {Helpers} methods such as
|
|
17
|
+
# `escape_typst`. Both hashes are also written to typst_data.json, as in
|
|
18
|
+
# the Rails, Sinatra, and Rage integrations.
|
|
19
|
+
#
|
|
20
|
+
# Relative names resolve against +root+, which defaults to `app/views`
|
|
21
|
+
# under Rails.root in a Rails app and to the current directory elsewhere.
|
|
22
|
+
# The `.typ` extension is optional, and `name.pdf.typ` is tried after
|
|
23
|
+
# `name.typ`. A relative name that resolves outside the root, such as
|
|
24
|
+
# `"../secrets"`, raises ArgumentError. Absolute paths are used as given.
|
|
25
|
+
#
|
|
26
|
+
# Rails view helpers, such as route helpers and `render` for partials, are
|
|
27
|
+
# not available. Use {TypstRails.render_with_rails} for templates that
|
|
28
|
+
# need them.
|
|
29
|
+
#
|
|
30
|
+
# @param template [String, Pathname] template name or path, such as
|
|
31
|
+
# `"reports/monthly"`
|
|
32
|
+
# @param locals [Hash] ERB local variables and typst_data.json entries
|
|
33
|
+
# @param assigns [Hash] ERB instance variables and typst_data.json
|
|
34
|
+
# entries; locals win on a name clash
|
|
35
|
+
# @param root [String, Pathname, nil] directory relative names resolve against
|
|
36
|
+
# @return [String] binary PDF data
|
|
37
|
+
# @raise [ArgumentError] if the name is blank or resolves outside the root
|
|
38
|
+
# @raise [TypstRails::Error] if the template is missing or compilation fails
|
|
39
|
+
#
|
|
40
|
+
# @example In a background job
|
|
41
|
+
# pdf = TypstRails.render("reports/monthly", locals: { month: "October" })
|
|
42
|
+
# File.binwrite("monthly.pdf", pdf)
|
|
43
|
+
#
|
|
44
|
+
# @example In a mailer
|
|
45
|
+
# attachments["invoice.pdf"] = TypstRails.render("invoices/show", assigns: { invoice: invoice })
|
|
46
|
+
def self.render(template, locals: {}, assigns: {}, root: nil)
|
|
47
|
+
TemplateRendering.render(template, locals: locals, assigns: assigns, root: root)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Renders a `.typ` view through a Rails controller and returns the PDF.
|
|
51
|
+
#
|
|
52
|
+
# Unlike {TypstRails.render}, the template goes through ActionView, the
|
|
53
|
+
# same as a `render template:` in a controller action. Rails resolves the
|
|
54
|
+
# name with its own view lookup, and app helpers, route helpers, and
|
|
55
|
+
# partials work. This method calls
|
|
56
|
+
# `controller.render(template:, formats: [:pdf], locals:, assigns:)`.
|
|
57
|
+
#
|
|
58
|
+
# The default controller is ApplicationController when it is defined and
|
|
59
|
+
# inherits from ActionController::Base, otherwise ActionController::Base.
|
|
60
|
+
#
|
|
61
|
+
# Route helpers that build full URLs need a host, from
|
|
62
|
+
# `config.action_controller.default_url_options` or the controller's
|
|
63
|
+
# renderer defaults, because there is no request to take one from.
|
|
64
|
+
#
|
|
65
|
+
# @param template [String, Symbol, Pathname] Rails template name, such as
|
|
66
|
+
# `"reports/monthly"`
|
|
67
|
+
# @param locals [Hash] view locals
|
|
68
|
+
# @param assigns [Hash] view instance variables
|
|
69
|
+
# @param controller [Class, nil] controller class to render with, such as
|
|
70
|
+
# `AdminController`
|
|
71
|
+
# @return [String] binary PDF data
|
|
72
|
+
# @raise [TypstRails::Error] if ActionController is not loaded
|
|
73
|
+
# @raise [ActionView::MissingTemplate] if Rails cannot find the template
|
|
74
|
+
#
|
|
75
|
+
# @example In a job
|
|
76
|
+
# pdf = TypstRails.render_with_rails("invoices/show", assigns: { invoice: invoice })
|
|
77
|
+
def self.render_with_rails(template, locals: {}, assigns: {}, controller: nil)
|
|
78
|
+
RailsRendering.render(template, locals: locals, assigns: assigns, controller: controller)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Renders a template and attaches the PDF to +attachable+ by calling
|
|
82
|
+
# `attachable.attach(io:, filename:, content_type:)`.
|
|
83
|
+
#
|
|
84
|
+
# Any object with that method works. An ActiveStorage attachment, such as
|
|
85
|
+
# `report.file` for `has_one_attached :file`, is the usual one.
|
|
86
|
+
#
|
|
87
|
+
# The template renders with {TypstRails.render}, or with
|
|
88
|
+
# {TypstRails.render_with_rails} when +via+ is `:rails`. Other options go
|
|
89
|
+
# to whichever one renders.
|
|
90
|
+
#
|
|
91
|
+
# @param attachable [#attach] receives the PDF
|
|
92
|
+
# @param template [String, Pathname] template name or path
|
|
93
|
+
# @param filename [String] filename to attach the PDF under
|
|
94
|
+
# @param locals [Hash] template locals
|
|
95
|
+
# @param content_type [String] content type to attach the PDF with
|
|
96
|
+
# @param via [Symbol] `:typst_rails` (the default) or `:rails`
|
|
97
|
+
# @param options [Hash] other options for the render method
|
|
98
|
+
# (`assigns:` and `root:`, or `assigns:` and `controller:`)
|
|
99
|
+
# @return [Object] whatever +attachable.attach+ returns
|
|
100
|
+
# @raise [ArgumentError] if +attachable+ does not respond to `attach`, or
|
|
101
|
+
# +via+ is unknown
|
|
102
|
+
# @raise [TypstRails::Error] if rendering fails
|
|
103
|
+
#
|
|
104
|
+
# @example
|
|
105
|
+
# TypstRails.render_and_attach(report.file, "reports/monthly",
|
|
106
|
+
# filename: "monthly.pdf", locals: { report: report })
|
|
107
|
+
#
|
|
108
|
+
# @example Through ActionView
|
|
109
|
+
# TypstRails.render_and_attach(report.file, "reports/monthly",
|
|
110
|
+
# filename: "monthly.pdf", via: :rails)
|
|
111
|
+
# rubocop:disable Metrics/ParameterLists -- render options plus the attach options
|
|
112
|
+
def self.render_and_attach(attachable, template, filename:, locals: {}, content_type: "application/pdf",
|
|
113
|
+
via: :typst_rails, **options)
|
|
114
|
+
raise ArgumentError, "#{attachable.class} does not respond to attach" unless attachable.respond_to?(:attach)
|
|
115
|
+
|
|
116
|
+
pdf = case via
|
|
117
|
+
when :typst_rails then render(template, locals: locals, **options)
|
|
118
|
+
when :rails then render_with_rails(template, locals: locals, **options)
|
|
119
|
+
else raise ArgumentError, "via must be :typst_rails or :rails, got #{via.inspect}"
|
|
120
|
+
end
|
|
121
|
+
attachable.attach(io: StringIO.new(pdf), filename: filename, content_type: content_type)
|
|
122
|
+
end
|
|
123
|
+
# rubocop:enable Metrics/ParameterLists
|
|
124
|
+
|
|
125
|
+
# Renders `.typ` template files to PDF without a controller or request:
|
|
126
|
+
# from background jobs, mailers, rake tasks, and scripts. Backs
|
|
127
|
+
# {TypstRails.render} and {TypstRails.render_and_attach}, and the Sinatra
|
|
128
|
+
# and Rage helpers.
|
|
129
|
+
#
|
|
130
|
+
# A template file runs through ERB first, then compiles with Typst. Locals
|
|
131
|
+
# are ERB local variables and assigns are instance variables; both are also
|
|
132
|
+
# written to typst_data.json for templates that read it.
|
|
133
|
+
#
|
|
134
|
+
# @api private
|
|
135
|
+
module TemplateRendering
|
|
136
|
+
# File extension of Typst templates.
|
|
137
|
+
EXTENSION = ".typ"
|
|
138
|
+
|
|
139
|
+
# Mirrors the `assigns` reader Renderer expects from a view context, so
|
|
140
|
+
# data gets the same JSON conversion (models, dates) as in Rails.
|
|
141
|
+
ViewContext = Struct.new(:assigns)
|
|
142
|
+
|
|
143
|
+
# The `self` of a template rendered outside a request: it has the
|
|
144
|
+
# {Helpers} methods and whatever instance variables the assigns set.
|
|
145
|
+
class Scope
|
|
146
|
+
include Helpers
|
|
147
|
+
|
|
148
|
+
# @param assigns [Hash] instance variables to set, keyed by name
|
|
149
|
+
# without the leading `@`
|
|
150
|
+
def initialize(assigns = {})
|
|
151
|
+
assigns.each do |name, value|
|
|
152
|
+
instance_variable_set(:"@#{name}", value) if ErbSource::LOCAL_NAME.match?(name.to_s)
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
module_function
|
|
158
|
+
|
|
159
|
+
# Resolves a template name, runs it through ERB, and compiles it.
|
|
160
|
+
#
|
|
161
|
+
# @param template [String, Pathname] template path; see {.resolve}
|
|
162
|
+
# @param locals [Hash] ERB local variables, also written to typst_data.json
|
|
163
|
+
# @param assigns [Hash] ERB instance variables, also written to
|
|
164
|
+
# typst_data.json; locals win on a name clash
|
|
165
|
+
# @param root [String, Pathname, nil] template root; see {.default_root}
|
|
166
|
+
# @return [String] binary PDF data
|
|
167
|
+
# @raise [ArgumentError] if the template resolves outside the root
|
|
168
|
+
# @raise [TypstRails::Error] if the template is missing or compilation fails
|
|
169
|
+
def render(template, locals: {}, assigns: {}, root: nil)
|
|
170
|
+
raise ArgumentError, "locals must be a Hash" unless locals.is_a?(Hash)
|
|
171
|
+
raise ArgumentError, "assigns must be a Hash" unless assigns.is_a?(Hash)
|
|
172
|
+
|
|
173
|
+
path = resolve(template, root || default_root)
|
|
174
|
+
render_file(path, Scope.new(assigns), locals, assigns)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# Renders a template file in a given ERB scope. Shared by the Sinatra and
|
|
178
|
+
# Rage helpers, which pass their route or controller as the scope.
|
|
179
|
+
#
|
|
180
|
+
# @param path [String] path to the template file
|
|
181
|
+
# @param scope [Object] `self` for ERB
|
|
182
|
+
# @param locals [Hash] ERB local variables, also written to typst_data.json
|
|
183
|
+
# @param assigns [Hash] extra data for typst_data.json; locals win on a
|
|
184
|
+
# name clash
|
|
185
|
+
# @return [String] binary PDF data
|
|
186
|
+
# @raise [TypstRails::Error] if compilation fails
|
|
187
|
+
def render_file(path, scope, locals = {}, assigns = {})
|
|
188
|
+
source = ErbSource.render(File.read(path), scope, locals)
|
|
189
|
+
Renderer.new(source, template: path.to_s).render(ViewContext.new(assigns), locals)
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Turns a template name into the path of an existing file.
|
|
193
|
+
#
|
|
194
|
+
# Relative names resolve against +root+ and must stay inside it.
|
|
195
|
+
# Absolute paths are used as given. A name without the `.typ` extension
|
|
196
|
+
# matches `name.typ`, or failing that the Rails-style `name.pdf.typ`.
|
|
197
|
+
#
|
|
198
|
+
# @param template [String, Pathname] template name or path
|
|
199
|
+
# @param root [String, Pathname] directory relative names resolve against
|
|
200
|
+
# @return [String] absolute path of the template file
|
|
201
|
+
# @raise [ArgumentError] if the template is blank or resolves outside +root+
|
|
202
|
+
# @raise [TypstRails::Error] if no matching file exists
|
|
203
|
+
#
|
|
204
|
+
# @example
|
|
205
|
+
# TemplateRendering.resolve("reports/monthly", "app/views")
|
|
206
|
+
# #=> "/app/app/views/reports/monthly.typ"
|
|
207
|
+
def resolve(template, root)
|
|
208
|
+
name = template.to_s
|
|
209
|
+
raise ArgumentError, "template cannot be empty" if name.strip.empty?
|
|
210
|
+
|
|
211
|
+
base = File.expand_path(name, root.to_s)
|
|
212
|
+
check_inside_root!(base, root) unless absolute?(name)
|
|
213
|
+
|
|
214
|
+
found = candidates(base).find { |candidate| File.file?(candidate) }
|
|
215
|
+
raise Error, "Typst template not found: #{name} (looked for #{candidates(base).join(", ")})" unless found
|
|
216
|
+
|
|
217
|
+
found
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
# The root relative template names resolve against: `app/views` under
|
|
221
|
+
# Rails.root when Rails is loaded, otherwise the current directory.
|
|
222
|
+
#
|
|
223
|
+
# @return [String]
|
|
224
|
+
def default_root
|
|
225
|
+
if FrameworkDetection.rails? && ::Rails.respond_to?(:root) && ::Rails.root
|
|
226
|
+
File.join(::Rails.root.to_s, "app", "views")
|
|
227
|
+
else
|
|
228
|
+
Dir.pwd
|
|
229
|
+
end
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# @api private
|
|
233
|
+
def candidates(base)
|
|
234
|
+
return [base] if File.extname(base) == EXTENSION
|
|
235
|
+
|
|
236
|
+
["#{base}#{EXTENSION}", "#{base}.pdf#{EXTENSION}"]
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# @api private
|
|
240
|
+
def absolute?(name)
|
|
241
|
+
Pathname.new(name).absolute?
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# @api private
|
|
245
|
+
def check_inside_root!(path, root)
|
|
246
|
+
root_path = File.expand_path(root.to_s)
|
|
247
|
+
return if path.start_with?(File.join(root_path, ""))
|
|
248
|
+
|
|
249
|
+
raise ArgumentError, "Typst template #{path} is outside the template root #{root_path}"
|
|
250
|
+
end
|
|
251
|
+
end
|
|
252
|
+
end
|
data/lib/typst_rails/version.rb
CHANGED