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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fc059a87f8ebdb16113e053ae6bdad1c32638cc1137e77424430504ab08d9635
4
- data.tar.gz: b39bda7395a15634391fd0b1d8a8923377387580f21797b367383ab01cc01a53
3
+ metadata.gz: 799ef6d2c13a142d9aff9884073aabc53230ea685ec6a27c9295b80b2f259ff9
4
+ data.tar.gz: ce7de50ed456972f529e5b2b7920c86a791a1eab5130d2e69a0f388f42b78044
5
5
  SHA512:
6
- metadata.gz: 6e792083bd8593a5eea48147de44270444b9d83ade7de8074c4c177633681af8629dea85a56880b30a58384a8af8646a02e03a0bb2b282ba5deb356b9ee5a415
7
- data.tar.gz: ee5c42c4d491ce960b774829e9201ace7b3716f2cabc3f902affb734c54fd2a142bf9834c608ffa67f033d947415607f238173d9814bf2af125843e844777511
6
+ metadata.gz: f3fd3d9e3584ad621410d63685f519104a4cd418b88a187af2a0a3d1b1a0ca779d9cff6cfaa4be10fcfe84f4acb84366d360b26b8436c3ede081111d31e84394
7
+ data.tar.gz: a89f2235008b19da770761bc9abf19e5adb9368dc2961b52c99822c8af9f6a5958d60d289dee65596fd7429221b437d62c97b2e3696cd7e0482391473efaff1a
data/CHANGELOG.md CHANGED
@@ -7,6 +7,94 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.2] - 2026-11-20
11
+
12
+ ### Added
13
+ - `config.pdf_standard` to have Typst enforce PDF standards such as PDF/UA-1
14
+ (`:ua_1`) and PDF/A (`:a_2b` and others). Accepts a symbol or an array of
15
+ symbols, and works with both the CLI and gem backends. PDF/UA-1 requires the
16
+ template to set a document title.
17
+ - `config.font_paths` to add directories that Typst searches for fonts, and
18
+ `config.ignore_system_fonts` to skip the system's fonts. Both backends pass
19
+ them to Typst: the CLI as `--font-path` and `--ignore-system-fonts`, the
20
+ `typst` gem as its `font_paths:` and `ignore_system_fonts:` options.
21
+ - `TypstRails::Configuration#compile_options`, the compiler options that
22
+ backends pass through to Typst.
23
+ - `TypstRails::CompileError`, a subclass of `TypstRails::Error`, raised when
24
+ Typst rejects a template. It carries the parsed diagnostics (severity,
25
+ message, path, line, column, hints), the line and column of the first
26
+ error, the template's name, the offending source line, Typst's output, and,
27
+ for the CLI backend, the command that was run.
28
+ - `TypstRails::Renderer.new` accepts an optional `template:` name. The Rails
29
+ handler passes the view's path, and the Sinatra and Rage helpers pass the
30
+ template path, so errors name the template instead of a temporary file.
31
+ - `config.on_warning`, called with the warnings from a successful CLI
32
+ compile and the template's name. By default it logs them. The `typst` gem
33
+ does not expose warnings on success, so it is not called for the `:gem`
34
+ backend.
35
+ - `TypstRails.render(template, locals:, assigns:, root:)` renders a `.typ`
36
+ template file to PDF outside a request, for background jobs, mailers, and
37
+ scripts. The template runs through ERB, then compiles, with locals and
38
+ assigns also written to `typst_data.json`. Relative paths resolve against
39
+ `app/views` in Rails and the current directory elsewhere, the `.typ`
40
+ extension is optional, and paths that lead outside the root raise
41
+ `ArgumentError`.
42
+ - `TypstRails.render_with_rails(template, locals:, assigns:, controller:)`
43
+ renders a `.typ` view through a Rails controller, so app helpers, route
44
+ helpers, and partials work outside a request. It raises
45
+ `TypstRails::Error` when ActionController is not loaded.
46
+ - `TypstRails.render_and_attach(attachable, template, filename:, ...)`
47
+ renders a template and passes the PDF to `attachable.attach`, such as an
48
+ ActiveStorage attachment. Pass `via: :rails` to render through
49
+ `render_with_rails`.
50
+
51
+ ### Changed
52
+ - Compile error messages name the template and the location of the first
53
+ error, and replace paths into the render's temporary directory with the
54
+ template's name or root-relative paths. The full command line is no longer
55
+ part of the message; it is available as `CompileError#command`.
56
+ - Warnings printed by a successful CLI compile are no longer discarded.
57
+ - **Behavior change:** a local whose value has no faithful JSON form now
58
+ raises `TypstRails::SerializationError` (a subclass of `TypstRails::Error`)
59
+ when the template reads `typst_data.json`. The message names the key path,
60
+ such as `locals.line_items[0].amount is a Money, which is not
61
+ JSON-serializable`, and says how to fix it. Such values used to reach the
62
+ template as `{}`, a dump of the object's instance variables, or its `#to_s`,
63
+ depending on whether ActiveSupport was loaded. Rejected values include plain
64
+ objects without their own `as_json` or `to_h`, Procs, IO objects,
65
+ Rationals, NaN and Infinity, strings with no valid UTF-8 form, and Hashes
66
+ with keys other than Strings, Symbols or numbers.
67
+ - An instance variable with no faithful JSON form is left out of
68
+ `typst_data.json`, with one warning per render (to `Rails.logger` when
69
+ present) naming each variable and the path of the offending value. Instance
70
+ variables whose names begin with an underscore are no longer written at all.
71
+ - Values in `typst_data.json` are converted by the new
72
+ `TypstRails::DataSerializer`: Symbols and Hash keys become strings, Sets
73
+ become arrays, BigDecimals become decimal strings, Structs and `Data`
74
+ objects become objects via `to_h`, and other objects are used only when
75
+ their class defines `as_json` or `to_h` itself. The private
76
+ `Renderer#transform_value_for_json_serialization` now delegates to it, and
77
+ the private `active_record_value?` check is gone: models and relations are
78
+ handled through their own `as_json`.
79
+ - Data for templates that do not mention `typst_data.json` is no longer
80
+ converted at all, so it cannot raise.
81
+ - The Sinatra `typst` and Rage `render_typst` helpers now share the template
82
+ rendering code behind `TypstRails.render`. Their behavior is unchanged.
83
+
84
+ ### Fixed
85
+ - `gem "typst-rails"` in a Gemfile now loads the library. Bundler.require
86
+ requires "typst-rails", but the entry point was only `typst_rails.rb`, so
87
+ Rails apps loaded `version.rb` and nothing else: the Railtie never ran and
88
+ `.typ` views failed with `ActionView::MissingTemplate`. The workaround,
89
+ `require: "typst_rails"`, is no longer needed.
90
+ - `.typ` partials rendered from a `.typ` view no longer compile to a PDF of
91
+ their own. Only the outermost `.typ` template compiles; nested ones return
92
+ their ERB-processed Typst source to be spliced into the parent.
93
+ - Times passed as locals to a render without a view context (as with
94
+ `Renderer.new(source).render(nil, locals)`) are now ISO 8601 strings, as they
95
+ already were with a view context. They were written with `Time#to_s` when
96
+ ActiveSupport was not loaded.
97
+
10
98
  ## [0.2.1] - 2026-11-14
11
99
 
12
100
  ### Added
data/README.md CHANGED
@@ -62,6 +62,36 @@ is not escaped. The controller's instance variables and locals are also
62
62
  serialized to `typst_data.json`, which Typst reads with `json()`. That file is
63
63
  written only when the template source mentions `typst_data.json`.
64
64
 
65
+ Only values with a faithful JSON form are written. Strings, numbers, booleans,
66
+ nil, Hashes, Arrays and Sets pass through, converted recursively; Symbols
67
+ become strings; Dates and Times (including `ActiveSupport::TimeWithZone`)
68
+ become ISO 8601 strings without fractional seconds; and BigDecimals become
69
+ decimal strings such as `"19.99"`, so no precision is lost (use
70
+ `decimal(data.total)` in Typst to do arithmetic with them). Hash keys must be
71
+ Strings, Symbols or numbers. Other objects are converted with `as_json` when
72
+ their class defines one, as ActiveRecord models and relations do, or with
73
+ `to_h`, as Structs and `Data` classes do. The generic `as_json` ActiveSupport
74
+ adds to every object does not count, since it writes the object's instance
75
+ variables. NaN, Infinity, and anything else, such as a Proc or a `Money`
76
+ object, are rejected.
77
+
78
+ A rejected local raises `TypstRails::SerializationError`, a
79
+ `TypstRails::Error`, naming where the value sits:
80
+
81
+ ```text
82
+ locals.line_items[0].amount is a Money, which is not JSON-serializable. Convert it ...
83
+ ```
84
+
85
+ Controllers often hold instance variables the template never uses, so a
86
+ rejected instance variable is left out of `typst_data.json` instead, with one
87
+ warning per render in the Rails log listing each one and why. Instance
88
+ variables whose names begin with an underscore are skipped silently. To give
89
+ the template such a value, convert it and pass it as a local:
90
+
91
+ ```ruby
92
+ render template: "invoices/show", locals: { total: @invoice.total.to_s }
93
+ ```
94
+
65
95
  The `TypstRails::Helpers` methods, such as `escape_typst` and
66
96
  `markdown_to_typst`, are available in views:
67
97
 
@@ -71,6 +101,17 @@ The `TypstRails::Helpers` methods, such as `escape_typst` and
71
101
 
72
102
  In views, `url_encode` remains ActionView's own, which encodes spaces as `%20`.
73
103
 
104
+ `.typ` partials work like any other partial. Only the outermost `.typ`
105
+ template is compiled; a partial returns its Typst source, which is spliced
106
+ into the parent before the whole document compiles once:
107
+
108
+ ```typst
109
+ <%# app/views/reports/monthly.pdf.typ %>
110
+ = Monthly Report
111
+
112
+ <%= render partial: "shared/footer" %> <%# app/views/shared/_footer.pdf.typ %>
113
+ ```
114
+
74
115
  ### Rage Integration
75
116
 
76
117
  Rage controllers have no template handlers, so when Rage is detected,
@@ -113,6 +154,128 @@ variables, helpers such as `escape_typst`, and the locals hash are all
113
154
  available. The locals are also written to `typst_data.json` for templates
114
155
  that read it.
115
156
 
157
+ ### Rendering outside a request
158
+
159
+ Background jobs, mailers, rake tasks, and scripts have no controller to
160
+ render with. `TypstRails.render` takes a template path and returns the PDF
161
+ as a binary string:
162
+
163
+ ```ruby
164
+ pdf = TypstRails.render("reports/monthly",
165
+ locals: { month: "October" },
166
+ assigns: { title: "Monthly Report" })
167
+ File.binwrite("monthly.pdf", pdf)
168
+ ```
169
+
170
+ The template runs through ERB first. `locals` become local variables,
171
+ `assigns` become instance variables, and the `TypstRails::Helpers` methods,
172
+ such as `escape_typst`, are available. Both hashes are also written to
173
+ `typst_data.json`, as in a controller render, with locals winning on a name
174
+ clash:
175
+
176
+ ```typst
177
+ <%# app/views/reports/monthly.typ %>
178
+ #let data = json("typst_data.json")
179
+
180
+ = <%= @title %>
181
+
182
+ Figures for <%= escape_typst(month) %>, also readable as #data.month.
183
+ ```
184
+
185
+ Relative paths resolve against `app/views` in a Rails app and against the
186
+ current directory elsewhere; pass `root:` to use another directory. The
187
+ `.typ` extension is optional, and `reports/monthly.pdf.typ` is found if
188
+ `reports/monthly.typ` does not exist. A relative path that leads outside the
189
+ root, such as `"../../config/master"`, raises `ArgumentError`. Absolute paths
190
+ are used as given, so do not pass user input as one.
191
+
192
+ These templates are not rendered by ActionView, so your app's helpers,
193
+ route helpers, and `render` for partials are not available.
194
+
195
+ #### Rendering through Rails
196
+
197
+ `TypstRails.render_with_rails` renders the template the way a controller
198
+ action does, so those helpers work. It takes a Rails template name, found
199
+ by Rails' own view lookup, and returns the PDF as a binary string:
200
+
201
+ ```ruby
202
+ pdf = TypstRails.render_with_rails("reports/monthly",
203
+ locals: { month: "October" },
204
+ assigns: { title: "Monthly Report" })
205
+ ```
206
+
207
+ It calls `ApplicationController.render(template:, formats: [:pdf], locals:,
208
+ assigns:)`. If your `ApplicationController` inherits from
209
+ `ActionController::API`, which cannot render views, it uses
210
+ `ActionController::Base` instead. Pass `controller:` to pick another one,
211
+ for example one that adds the helpers the template needs. Calling
212
+ `ApplicationController.render` yourself with the same arguments gives the
213
+ same result.
214
+
215
+ Which one to use:
216
+
217
+ - `TypstRails.render` works in any Ruby program, takes a file path, and
218
+ checks that relative paths stay inside the root. Templates get
219
+ `TypstRails::Helpers` and nothing else.
220
+ - `TypstRails.render_with_rails` needs ActionController. Use it when the
221
+ template calls your helpers, builds URLs, or renders partials. It raises
222
+ `TypstRails::Error` if ActionController is not loaded.
223
+
224
+ There is no request, so helpers that build full URLs, such as
225
+ `report_url`, need a host from `Rails.application.routes.default_url_options`.
226
+
227
+ Write partials as `.typ` files, such as `_footer.pdf.typ`; see the Rails
228
+ usage section above. An `.erb` partial also works, but Rails escapes `<%= %>`
229
+ output in `.erb` files as HTML, turning `&` into `&amp;`, so use `<%== %>`
230
+ there, together with `escape_typst` for untrusted values.
231
+
232
+ In a job:
233
+
234
+ ```ruby
235
+ class MonthlyReportJob < ApplicationJob
236
+ def perform(account)
237
+ pdf = TypstRails.render("reports/monthly", assigns: { account: account })
238
+ File.binwrite(Rails.root.join("tmp", "report-#{account.id}.pdf"), pdf)
239
+ end
240
+ end
241
+ ```
242
+
243
+ Pass the PDF to `deliver_now` rather than `deliver_later` if you hand it to
244
+ a mailer: job arguments are serialized, and binary strings do not survive
245
+ that. Better still, render inside the mailer, as below.
246
+
247
+ In a mailer, assign the PDF to `attachments`:
248
+
249
+ ```ruby
250
+ class InvoiceMailer < ApplicationMailer
251
+ def receipt(invoice)
252
+ attachments["invoice-#{invoice.number}.pdf"] =
253
+ TypstRails.render("invoices/show", locals: { invoice: invoice })
254
+ mail(to: invoice.customer.email, subject: "Your invoice")
255
+ end
256
+ end
257
+ ```
258
+
259
+ To store the PDF with ActiveStorage, `TypstRails.render_and_attach` renders
260
+ the template and calls `attach` on what you pass it:
261
+
262
+ ```ruby
263
+ class Report < ApplicationRecord
264
+ has_one_attached :pdf
265
+ end
266
+
267
+ TypstRails.render_and_attach(report.pdf, "reports/monthly",
268
+ filename: "monthly.pdf",
269
+ locals: { report: report })
270
+ ```
271
+
272
+ It accepts any object with an `attach(io:, filename:, content_type:)`
273
+ method; ActiveStorage itself is not required. `content_type:` defaults to
274
+ `"application/pdf"`, and `assigns:` and `root:` work as in
275
+ `TypstRails.render`. Pass `via: :rails` to render with
276
+ `TypstRails.render_with_rails` instead; `controller:` then works as it does
277
+ there.
278
+
116
279
  ### Configuration
117
280
 
118
281
  ```ruby
@@ -128,6 +291,79 @@ creates a short-lived working directory inside the root, so it must be
128
291
  writable. Without it, each render compiles in a private temporary directory
129
292
  and cannot read your application's files.
130
293
 
294
+ #### Fonts
295
+
296
+ Typst finds fonts in three places: the fonts installed on the system, the
297
+ fonts embedded in Typst itself (Libertinus Serif, New Computer Modern and
298
+ DejaVu Sans Mono), and any extra directories you name.
299
+
300
+ ```ruby
301
+ TypstRails.configure do |config|
302
+ config.font_paths = [Rails.root.join("app", "assets", "fonts")]
303
+ config.ignore_system_fonts = true
304
+ end
305
+ ```
306
+
307
+ - `font_paths` lists directories that Typst searches, recursively, for font
308
+ files. It defaults to `[]`. A single path is accepted and wrapped in an
309
+ Array. Relative paths are expanded against the process working directory.
310
+ - `ignore_system_fonts` stops Typst from searching the system's fonts, so
311
+ only `font_paths` and Typst's embedded fonts are used. It defaults to
312
+ `false`.
313
+
314
+ Both settings apply to the `:cli` backend (as `--font-path` and
315
+ `--ignore-system-fonts`) and the `:gem` backend (as the `font_paths:` and
316
+ `ignore_system_fonts:` options of `Typst::Pdf.new`).
317
+
318
+ #### Fonts in production and Docker
319
+
320
+ A slim production image usually has few fonts installed, and often not the
321
+ ones a template was designed with. Typst does not fail when a font is
322
+ missing: it warns and falls back to another font, so the PDF renders but
323
+ looks different from the one you saw in development.
324
+
325
+ To get the same output everywhere, keep the font files with the
326
+ application and point `font_paths` at them:
327
+
328
+ 1. Copy the `.ttf` or `.otf` files your templates use into the app, for
329
+ example `app/assets/fonts/`, and commit them. Check that each font's
330
+ license allows you to redistribute it.
331
+ 2. Set `config.font_paths` to that directory.
332
+ 3. Optionally set `config.ignore_system_fonts = true`. Typst then skips
333
+ scanning the system's font directories on each compile, and a document
334
+ can no longer pick up a font that happens to be installed on one machine
335
+ but not another. A font your templates name that is missing from
336
+ `font_paths` then falls back in development too, so you see the problem
337
+ before you deploy.
338
+
339
+ Nothing extra needs to be installed in the Docker image for this, since the
340
+ fonts ship inside the application directory.
341
+
342
+ #### Accessible and archival PDFs
343
+
344
+ Set `pdf_standard` to have Typst enforce a PDF standard. Use `:ua_1` for
345
+ PDF/UA-1, the accessibility standard:
346
+
347
+ ```ruby
348
+ TypstRails.configure do |config|
349
+ config.pdf_standard = :ua_1
350
+ end
351
+ ```
352
+
353
+ PDF/UA-1 requires a document title. Set it in each template, or the render
354
+ raises `TypstRails::Error`:
355
+
356
+ ```typst
357
+ #set document(title: "Quarterly Report")
358
+ ```
359
+
360
+ Pass an array to combine standards, such as `[:a_2b, :ua_1]` for a document
361
+ that is both archival and accessible. The accepted keys are `:pdf_1_4`,
362
+ `:pdf_1_5`, `:pdf_1_6`, `:pdf_1_7`, `:pdf_2_0`, `:a_1a`, `:a_1b`, `:a_2a`,
363
+ `:a_2b`, `:a_2u`, `:a_3a`, `:a_3b`, `:a_3u`, `:a_4`, `:a_4e`, `:a_4f` and
364
+ `:ua_1`, matching the values listed by `typst compile --help`. The default,
365
+ `nil`, produces a plain PDF. Both the CLI and gem backends honor this setting.
366
+
131
367
  ### Compilation Backends
132
368
 
133
369
  `TypstRails` compiles documents through a pluggable backend. Two backends ship
@@ -164,7 +400,10 @@ class MyRemoteBackend < TypstRails::Backends::Base
164
400
  end
165
401
 
166
402
  def compile(typ_path, root_dir)
167
- # ... return PDF bytes, or raise TypstRails::Error on failure
403
+ # ... return PDF bytes. If Typst rejects the source, raise
404
+ # TypstRails::CompileError with Typst's diagnostic output as the message;
405
+ # raise TypstRails::Error for other failures. To report warnings from a
406
+ # successful compile, yield Typst's diagnostic output to the block.
168
407
  end
169
408
  end
170
409
 
@@ -172,6 +411,89 @@ TypstRails::Backends::Registry.register(:my_remote, MyRemoteBackend.new)
172
411
  TypstRails.configure { |config| config.backend = :my_remote }
173
412
  ```
174
413
 
414
+ ### Errors
415
+
416
+ When Typst rejects a template, rendering raises `TypstRails::CompileError`, a
417
+ subclass of `TypstRails::Error`, so existing `rescue TypstRails::Error` code
418
+ keeps working. The message names the template and the location of the first
419
+ error, followed by Typst's own report:
420
+
421
+ ```
422
+ Typst compilation failed in app/views/reports/show.pdf.typ:4:9: unknown variable: foo
423
+ (Line numbers count lines of the compiled Typst source, after any ERB evaluation.)
424
+
425
+ error: unknown variable: foo
426
+ ┌─ app/views/reports/show.pdf.typ:4:9
427
+ │
428
+ 4 │ #let x = foo(1)
429
+ │ ^^^
430
+ ```
431
+
432
+ Each render compiles a copy of the template in a temporary directory. Paths
433
+ into that directory are replaced in the message: the template becomes its
434
+ name (the view path in Rails, the path you passed to the Sinatra and Rage
435
+ helpers, or `(inline source)` for a `Renderer` built from a string), other
436
+ files under the Typst root become root-relative paths such as `/lib.typ`, and
437
+ files next to the template, such as `typst_data.json`, are shown by name.
438
+ To name a template yourself, pass `template:` to `TypstRails::Renderer.new`:
439
+
440
+ ```ruby
441
+ TypstRails::Renderer.new(File.read(path), template: path).render(nil, data)
442
+ ```
443
+
444
+ The error also carries the details as attributes:
445
+
446
+ ```ruby
447
+ rescue TypstRails::CompileError => e
448
+ e.template # => "app/views/reports/show.pdf.typ", or nil
449
+ e.line # => 4, line of the first error
450
+ e.column # => 9, column of the first error
451
+ e.source_line # => "#let x = foo(1)", when the error is in the template
452
+ e.diagnostics # => every error and warning, with severity, message,
453
+ # path, line, column and hints
454
+ e.errors # => just the errors
455
+ e.warnings # => just the warnings
456
+ e.typst_message # => Typst's output, with paths rewritten
457
+ e.command # => the command line the CLI backend ran, for debugging
458
+ end
459
+ ```
460
+
461
+ Line numbers refer to the source Typst compiled. For `.typ` views and the
462
+ Sinatra and Rage helpers, that is the template after ERB evaluation, so an
463
+ ERB tag that expands to several lines, or a `<% %>` line that is trimmed
464
+ away, shifts them relative to the file on disk; `source_line` shows the line
465
+ Typst actually saw. Columns are counted from 0, as Typst prints them.
466
+
467
+ Parsing is best-effort. If Typst's output is not in a format TypstRails
468
+ recognizes, you still get a `CompileError` with the raw output in the message
469
+ and in `typst_message`, and `diagnostics` is empty.
470
+
471
+ ### Warnings
472
+
473
+ Typst can report warnings, such as an unknown font family, on a compile that
474
+ succeeds. With the CLI backend, TypstRails passes them to `config.on_warning`,
475
+ which is called with an array of diagnostics and the template's name (or
476
+ nil). By default the warnings are logged with `Rails.logger.warn`, or with
477
+ `Kernel#warn` outside Rails:
478
+
479
+ ```ruby
480
+ TypstRails.configure do |config|
481
+ # Fail tests on any Typst warning:
482
+ config.on_warning = ->(warnings, template) do
483
+ raise "Typst warnings in #{template}: #{warnings.map(&:to_s).join(", ")}"
484
+ end
485
+
486
+ # Or ignore them:
487
+ # config.on_warning = nil
488
+ end
489
+ ```
490
+
491
+ An error raised by the handler propagates from the render.
492
+
493
+ The `typst` gem returns only the PDF on a successful compile, so with the
494
+ `:gem` backend `on_warning` is never called. Warnings that accompany a failed
495
+ compile are included in `CompileError#warnings` with either backend.
496
+
175
497
  ## Testing
176
498
 
177
499
  The gem includes comprehensive testing at multiple levels:
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Bundler.require loads a gem by its name, "typst-rails", but the library's
4
+ # entry point is typst_rails.rb. This file bridges the two, so a plain
5
+ # `gem "typst-rails"` line in a Gemfile loads the Railtie and registers the
6
+ # .typ template handler.
7
+ require "typst_rails"
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "typst_rails/errors"
4
+
3
5
  module TypstRails
4
6
  module Backends
5
7
  # Abstract interface for a Typst compilation backend.
@@ -20,11 +22,32 @@ module TypstRails
20
22
  #
21
23
  # @param typ_path [String] path to the .typ source file to compile
22
24
  # @param root_dir [String] root directory for resolving relative imports
25
+ # @yieldparam diagnostics [String] Typst's diagnostic output from a
26
+ # successful compile, such as warnings. Backends that can see it
27
+ # should yield it when a block is given; the Renderer parses it and
28
+ # passes the warnings to {TypstRails::Configuration#on_warning}.
29
+ # Yielding is optional.
23
30
  # @return [String] binary PDF data
24
- # @raise [TypstRails::Error] if compilation fails
31
+ # @raise [TypstRails::CompileError] if Typst rejects the source; pass
32
+ # Typst's diagnostic output as the message so it can be parsed
33
+ # @raise [TypstRails::Error] if compilation fails for another reason
25
34
  def compile(typ_path, root_dir)
26
35
  raise NotImplementedError, "#{self.class} must implement #compile"
27
36
  end
37
+
38
+ private
39
+
40
+ # Options from {TypstRails::Configuration#compile_options}, or an empty
41
+ # Hash when nothing is configured. TypstRails.configuration is checked
42
+ # with respond_to? first because the top-level module is not loaded when
43
+ # "typst_rails/renderer" is required on its own.
44
+ #
45
+ # @return [Hash{Symbol => Object}]
46
+ def configured_compile_options
47
+ return {} unless TypstRails.respond_to?(:configuration)
48
+
49
+ TypstRails.configuration&.compile_options || {}
50
+ end
28
51
  end
29
52
  end
30
53
  end
@@ -35,10 +35,15 @@ module TypstRails
35
35
  executable_on_path?(path)
36
36
  end
37
37
 
38
+ # Passes {TypstRails::Configuration#compile_options} to Typst as
39
+ # command-line flags. Typst's stderr is parsed into the raised
40
+ # {TypstRails::CompileError} on failure, and yielded to the block, if
41
+ # given, on success, since a successful compile can still print warnings.
42
+ #
38
43
  # @see Base#compile
39
44
  def compile(typ_path, root_dir)
40
45
  output_pdf_path = File.join(root_dir, "#{File.basename(typ_path, ".typ")}_output.pdf")
41
- cmd = [executable_path, "compile", "--root", root_dir, typ_path, output_pdf_path]
46
+ cmd = [executable_path, "compile", "--root", root_dir, *compile_option_args, typ_path, output_pdf_path]
42
47
 
43
48
  begin
44
49
  _stdout_str, stderr_str, status = Open3.capture3(*cmd)
@@ -48,8 +53,11 @@ module TypstRails
48
53
  raise Error, "Failed to execute Typst compiler: #{e.message}"
49
54
  end
50
55
 
51
- raise_compilation_failure(cmd, stderr_str) unless status.success?
52
- read_compiled_pdf(output_pdf_path)
56
+ raise CompileError.new(stderr_str, command: cmd) unless status.success?
57
+
58
+ pdf_data = read_compiled_pdf(output_pdf_path)
59
+ yield stderr_str if block_given? && !stderr_str.strip.empty?
60
+ pdf_data
53
61
  ensure
54
62
  safe_unlink(output_pdf_path)
55
63
  end
@@ -69,6 +77,19 @@ module TypstRails
69
77
  TypstRails.configuration&.typst_executable_path
70
78
  end
71
79
 
80
+ # Flags for the configured compile options. Each font directory gets its
81
+ # own --font-path flag rather than one PATH_SEPARATOR-joined value, so a
82
+ # directory whose name contains the separator still reaches Typst
83
+ # intact. Typst takes several PDF standards as one comma-separated value.
84
+ def compile_option_args
85
+ options = configured_compile_options
86
+ flags = Array(options[:font_paths]).flat_map { |path| ["--font-path", path] }
87
+ flags << "--ignore-system-fonts" if options[:ignore_system_fonts]
88
+ standards = Array(options[:pdf_standards])
89
+ flags.push("--pdf-standard", standards.join(",")) unless standards.empty?
90
+ flags
91
+ end
92
+
72
93
  def directory_path?(path)
73
94
  [File::SEPARATOR, File::ALT_SEPARATOR].compact.any? { |separator| path.include?(separator) }
74
95
  end
@@ -94,13 +115,6 @@ module TypstRails
94
115
  pdf_data
95
116
  end
96
117
 
97
- def raise_compilation_failure(cmd, stderr_str)
98
- error_message = "Typst compilation failed.\n"
99
- error_message += "Command: #{cmd.join(" ")}\n"
100
- error_message += "Stderr: #{stderr_str}" unless stderr_str.empty?
101
- raise Error, error_message
102
- end
103
-
104
118
  def safe_unlink(path)
105
119
  File.unlink(path) if path && File.exist?(path)
106
120
  rescue StandardError => e
@@ -32,11 +32,28 @@ module TypstRails
32
32
  end
33
33
  end
34
34
 
35
+ # Passes {TypstRails::Configuration#compile_options} to `Typst::Pdf.new`.
36
+ # The `typst` gem raises with Typst's diagnostics as the message, so
37
+ # failures become a {TypstRails::CompileError} with parsed
38
+ # diagnostics. On success it returns only the PDF, so warnings are not
39
+ # available and nothing is yielded.
40
+ #
35
41
  # @see Base#compile
36
42
  def compile(typ_path, root_dir)
37
- ::Typst::Pdf.new(file: typ_path, root: root_dir).compiled.document
43
+ ::Typst::Pdf.new(file: typ_path, root: root_dir, **gem_options).compiled.document
38
44
  rescue StandardError => e
39
- raise Error, "Typst compilation failed: #{e.message}"
45
+ raise CompileError, e.message
46
+ end
47
+
48
+ private
49
+
50
+ # Options for Typst::Pdf.new, under the keys the `typst` gem expects.
51
+ # PDF standards are left out when none are configured, so a plain
52
+ # compile does not pass an empty list.
53
+ def gem_options
54
+ options = configured_compile_options.slice(:font_paths, :ignore_system_fonts, :pdf_standards)
55
+ options.delete(:pdf_standards) if Array(options[:pdf_standards]).empty?
56
+ options
40
57
  end
41
58
  end
42
59
  end