formfeed 0.3.32

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 86bcde4960bb30db76b1c258052172ac51fd27f97cb91f02b70dbbadd73f79e0
4
+ data.tar.gz: a3cd2bfc2f02552084a59d572c40dc5ca038b774b3b7d97704573109e4d91df6
5
+ SHA512:
6
+ metadata.gz: 4046afca61043e4d5a33f7e8eb2d8b68aedad6a78e0b584641b23a41890516a632af5fe60e303fe543bb25813469751240eb2bdd6297f3e59794f035b69dd97f
7
+ data.tar.gz: 5aa9813de0c12aa994f95effa728075117a617f7c268d547f8dfc23dcdef8e4c2d7d9ab779356ef32bccd9b605739d0fc7bbc034c497bf794cb52bcfee5cee47
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Philipp Staudt IT-Dienstleistungen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # formfeed
2
+
3
+ The Ruby SDK for the [Formfeed](https://formfeed.dev/?utm_source=rubygems) API:
4
+ PDFs and images from templates, HTML, URLs or Markdown, and tools for existing PDFs. Ruby 3.3 or
5
+ newer, and nothing beyond Ruby's standard library.
6
+
7
+ ```bash
8
+ bundle add formfeed
9
+ ```
10
+
11
+ or `gem install formfeed`.
12
+
13
+ ## Render a document
14
+
15
+ ```ruby
16
+ require "formfeed"
17
+
18
+ formfeed = Formfeed::Client.new(api_key: ENV.fetch("FORMFEED_API_KEY"))
19
+
20
+ render = formfeed.renders.create(
21
+ template: "invoice",
22
+ data: { customer: { name: "Olvarest GmbH" }, total: 1428.00 }
23
+ )
24
+ formfeed.renders.download_to(render, "invoice.pdf")
25
+ ```
26
+
27
+ A request takes keywords or one Hash, so `create("template" => "invoice", "data" => data)` sends the
28
+ same. Template data and settings are free hashes; answers are read into `Formfeed::Render`,
29
+ `Formfeed::Job` and the like, whose `raw` keeps the whole answer, fields of later API versions
30
+ included.
31
+
32
+ ## Downloads
33
+
34
+ `download` answers the file as binary bytes, `download_to` streams it to a path or an IO and answers
35
+ the number of bytes written. Both take a render or its id; the signed link they follow needs no key.
36
+
37
+ ```ruby
38
+ pdf = formfeed.renders.download(render)
39
+ send_data pdf, type: "application/pdf", filename: "invoice.pdf" # in a Rails controller
40
+
41
+ File.open("invoice.pdf", "wb") { |file| formfeed.renders.download_to(render, file) }
42
+ ```
43
+
44
+ ## Waiting for a render
45
+
46
+ A render is synchronous by default, so the answer is the finished render. With `mode: "async"` it
47
+ comes back queued, and `wait_for` asks until it is done:
48
+
49
+ ```ruby
50
+ render = formfeed.renders.create(html: "<h1>Report</h1>", mode: "async")
51
+ render = formfeed.renders.wait_for(render, timeout: 120)
52
+ render.finished? # => true, succeeded or failed
53
+ ```
54
+
55
+ Every call that creates a render sends an `Idempotency-Key`, so a retry cannot charge twice; pass
56
+ your own to tie it to your order:
57
+
58
+ ```ruby
59
+ formfeed.renders.create(template: "invoice", data: data, idempotency_key: "order-1042")
60
+ ```
61
+
62
+ Lists are pages (`list`) or Enumerators that follow the cursor as you go (`all`):
63
+
64
+ ```ruby
65
+ formfeed.renders.all(status: "failed", since: "2026-11-01T00:00:00Z").each do |failed|
66
+ puts "#{failed.id} #{failed.error&.fetch("code", nil)}"
67
+ end
68
+ ```
69
+
70
+ ## Batches
71
+
72
+ Up to 1,000 renders in one job, always asynchronous. Its renders keep the order of `items`:
73
+
74
+ ```ruby
75
+ job = formfeed.renders.batch(
76
+ template: "certificate",
77
+ items: [
78
+ { data: { name: "Max Mustermann" } },
79
+ { data: { name: "Erika Mustermann" } }
80
+ ],
81
+ zip: true
82
+ )
83
+ job = formfeed.jobs.wait_for(job)
84
+ job.items.each_with_index do |item, index|
85
+ formfeed.renders.download_to(item, "certificate-#{index + 1}.pdf") if item.status == "succeeded"
86
+ end
87
+ ```
88
+
89
+ ## PDF tools
90
+
91
+ On a render, a file of the library (its id or its name), or an upload, which is never stored:
92
+
93
+ ```ruby
94
+ form = Formfeed::Upload.from_path("application.pdf")
95
+
96
+ info = formfeed.pdf.info(form)
97
+ info.form["fields"].map { |field| field["name"] } # the names fill takes
98
+
99
+ filled = formfeed.pdf.fill(form, fields: { "name" => "Max Mustermann", "accepted" => true }, flatten: true)
100
+ merged = formfeed.pdf.merge([filled, "terms.pdf"], filename: "application")
101
+ formfeed.renders.download_to(merged, "application.pdf")
102
+ ```
103
+
104
+ `merge`, `protect`, `watermark`, `split`, `compress`, `to_image`, `redact`, `fill`, `convert` and
105
+ `info`, and `einvoices.validate` for an e-invoice's rules. `Upload.from_string(bytes, "a.pdf")` takes
106
+ bytes in memory, and `Upload.from_io` a File or an upload a Rails or Rack application received.
107
+
108
+ ## Webhooks
109
+
110
+ `Formfeed::Webhook.parse` checks the `Webhook-Signature` header (HMAC-SHA256 of the raw body, at
111
+ most five minutes old, compared in constant time) and answers the event as a Hash; it raises
112
+ `Formfeed::Webhook::Error` when the signature does not match. `verify` answers true or false. Pass
113
+ the body exactly as it arrived.
114
+
115
+ In a Rails controller:
116
+
117
+ ```ruby
118
+ class FormfeedWebhooksController < ActionController::API
119
+ def create
120
+ event = Formfeed::Webhook.parse(
121
+ ENV.fetch("FORMFEED_WEBHOOK_SECRET"),
122
+ request.headers["Webhook-Signature"],
123
+ request.raw_post
124
+ )
125
+ case event["type"]
126
+ when "render.completed" then InvoiceMailer.ready(event["data"]["id"]).deliver_later
127
+ when "render.failed" then Rails.logger.warn("render #{event["data"]["id"]} failed")
128
+ end
129
+ head :no_content
130
+ rescue Formfeed::Webhook::Error
131
+ head :unauthorized
132
+ end
133
+ end
134
+ ```
135
+
136
+ As a Rack application:
137
+
138
+ ```ruby
139
+ receiver = lambda do |env|
140
+ request = Rack::Request.new(env)
141
+ event = Formfeed::Webhook.parse(
142
+ ENV.fetch("FORMFEED_WEBHOOK_SECRET"),
143
+ request.get_header("HTTP_WEBHOOK_SIGNATURE"),
144
+ request.body.read
145
+ )
146
+ puts "#{event["type"]} #{event["data"]["id"]}"
147
+ [204, {}, []]
148
+ rescue Formfeed::Webhook::Error
149
+ [401, {}, ["invalid signature"]]
150
+ end
151
+ ```
152
+
153
+ ## Errors and retries
154
+
155
+ Every problem the API answers is a `Formfeed::Error` with the problem's `code` (`quota_exceeded`,
156
+ `template_not_found`, …), the detail as its message, the HTTP `status`, the `request_id` support
157
+ asks for, and the whole `problem`. 429 and 503 answers and network errors are retried up to three
158
+ times, waiting what `Retry-After` says, else half a second doubling.
159
+
160
+ ```ruby
161
+ begin
162
+ formfeed.renders.create(template: "invoice", data: data)
163
+ rescue Formfeed::Error => e
164
+ warn "#{e.code} (#{e.status}): #{e.message} [#{e.request_id}]"
165
+ e.problem&.errors&.each { |error| warn " #{error["path"]}: #{error["message"]}" }
166
+ end
167
+ ```
168
+
169
+ ## Options
170
+
171
+ ```ruby
172
+ Formfeed::Client.new(
173
+ api_key: ENV.fetch("FORMFEED_API_KEY"),
174
+ region: "us", # eu (the default) or us; or base_url: "http://localhost:8787/v1"
175
+ max_retries: 5, # 0 turns retries off
176
+ timeout: 60 # seconds; 120 by default
177
+ )
178
+ ```
179
+
180
+ ## Anything else
181
+
182
+ Template authoring, release channels and shared partials have no methods here yet;
183
+ `request` reaches any call of the API with the client's key, retries and errors, and answers the
184
+ decoded JSON:
185
+
186
+ ```ruby
187
+ brand = formfeed.request(:get, "/brand")
188
+ ```
189
+
190
+ The [documentation](https://docs.formfeed.dev) describes every call.
191
+
192
+ ## License
193
+
194
+ MIT
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # The Formfeed API.
5
+ #
6
+ # formfeed = Formfeed::Client.new(api_key: ENV.fetch("FORMFEED_API_KEY"))
7
+ # render = formfeed.renders.create(template: "invoice", data: data)
8
+ # formfeed.renders.download_to(render, "invoice.pdf")
9
+ #
10
+ # It sends with Net::HTTP of Ruby's standard library, a connection per request, so one client can
11
+ # be shared by threads.
12
+ class Client
13
+ HOSTS = {
14
+ "eu" => "https://api-eu.formfeed.dev/v1",
15
+ "us" => "https://api-us.formfeed.dev/v1"
16
+ }.freeze
17
+
18
+ attr_reader :renders, :jobs, :pdf, :einvoices, :files, :templates, :webhooks, :account
19
+
20
+ # +region+ is +eu+ or +us+, ignored when +base_url+ (the full base URL with +/v1+, for a local
21
+ # or another gateway) is given. +max_retries+ counts the retries on 429, 503 and network errors,
22
+ # 0 turns them off; +timeout+ is in seconds, for connecting (at most 10), sending and each read;
23
+ # +headers+ are sent with every request, after the SDK's own. +sleep+ is how to wait between
24
+ # retries and polls (a callable taking seconds), +jitter+ what to add to a retry's wait (a
25
+ # callable answering 0 to 0.25 seconds); tests pass both.
26
+ def initialize(api_key:, region: "eu", base_url: nil, max_retries: 3, timeout: 120, headers: {},
27
+ sleep: nil, jitter: nil)
28
+ raise Error.new("invalid_request", "api_key is required") if api_key.nil? || api_key.to_s.empty?
29
+
30
+ host = base_url || HOSTS[region.to_s]
31
+ raise Error.new("invalid_request", "unknown region #{region}: eu or us, or a base_url") if host.nil?
32
+
33
+ @transport = Internal::Transport.new(
34
+ api_key: api_key.to_s, base_url: host.to_s.chomp("/"), max_retries: [0, max_retries.to_i].max,
35
+ timeout: timeout, headers: headers, sleep: sleep, jitter: jitter
36
+ )
37
+ build_resources
38
+ end
39
+
40
+ # Any call of the API with the client's key, retries and problems, for one without a method here
41
+ # (template authoring, channels, shared partials): the decoded JSON answer, nil for none.
42
+ #
43
+ # formfeed.request(:get, "/brand")
44
+ def request(method, path, body = nil, idempotency_key: nil)
45
+ @transport.json(method.to_s.upcase, path, body, idempotency_key)
46
+ end
47
+
48
+ # The key stays out of logs and consoles.
49
+ def inspect
50
+ "#<#{self.class.name} #{@transport.inspect}>"
51
+ end
52
+
53
+ private
54
+
55
+ def build_resources
56
+ @renders = Resources::Renders.new(@transport)
57
+ @jobs = Resources::Jobs.new(@transport)
58
+ @pdf = Resources::Pdf.new(@transport)
59
+ @einvoices = Resources::Einvoices.new(@transport)
60
+ @files = Resources::Files.new(@transport)
61
+ @templates = Resources::Templates.new(@transport)
62
+ @webhooks = Resources::Webhooks.new(@transport)
63
+ @account = Resources::Account.new(@transport)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ # An API problem (RFC 9457) or a failure on this side.
5
+ #
6
+ # +code+ is the problem's code (+quota_exceeded+, +template_not_found+, ...), or +network_error+,
7
+ # +timeout+, +not_ready+, +download_failed+ or +invalid_response+ for what went wrong before an
8
+ # answer; +status+ is the HTTP status, 0 when there was none; +problem+ the problem document as a
9
+ # Formfeed::Problem; +request_id+ the +X-Request-Id+ the API answered with, which support asks for.
10
+ class Error < StandardError
11
+ attr_reader :code, :status, :problem, :request_id
12
+
13
+ def initialize(code, message, status: 0, problem: nil, request_id: nil)
14
+ super(message)
15
+ @code = code
16
+ @status = status
17
+ @problem = problem
18
+ @request_id = request_id
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Internal
5
+ # One request with Net::HTTP on a connection of its own, within the client's time limits:
6
+ # connecting takes at most 10 seconds, sending and each read at most +timeout+. Net::HTTP's own
7
+ # retry is off, as the transport retries; network failures are raised as they are.
8
+ class Connection
9
+ # What Net::HTTP raises when a connection fails, times out or breaks off.
10
+ NETWORK_ERRORS = [
11
+ IOError, SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError,
12
+ Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error
13
+ ].freeze
14
+
15
+ def initialize(timeout)
16
+ @timeout = timeout
17
+ end
18
+
19
+ # The response; with a block, the response is handed to it before its body is read.
20
+ def perform(method, uri, headers, payload, &)
21
+ http = Net::HTTP.new(uri.hostname, uri.port)
22
+ http.use_ssl = uri.scheme == "https"
23
+ http.open_timeout = [@timeout, 10].min
24
+ http.read_timeout = @timeout
25
+ http.write_timeout = @timeout
26
+ http.max_retries = 0
27
+ # a body-less POST says so, without the form type Net::HTTP would give an empty body
28
+ headers = headers.merge("Content-Length" => "0") if payload.nil? && %w[POST PUT PATCH].include?(method)
29
+ request = Net::HTTPGenericRequest.new(method, !payload.nil?, method != "HEAD", uri.request_uri, headers)
30
+ request.body = payload unless payload.nil?
31
+ http.start { |connection| connection.request(request, &) }
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Internal
5
+ # A signed link of the CDN, fetched without the API key, which the link does not need. Not
6
+ # retried, as no SDK retries a download; redirects are followed, as the other SDKs' HTTP clients
7
+ # follow them.
8
+ class Download
9
+ REDIRECTS = [301, 302, 303, 307, 308].freeze
10
+ MAX_REDIRECTS = 5
11
+
12
+ # A failure to write, kept apart from the network errors while the body streams.
13
+ class WriteFailed < StandardError; end
14
+ private_constant :WriteFailed
15
+
16
+ def initialize(connection, user_agent)
17
+ @connection = connection
18
+ @headers = { "Accept" => "*/*", "User-Agent" => user_agent }.freeze
19
+ end
20
+
21
+ # The bytes, or with +target+ (a path or an IO) the number of bytes written there.
22
+ def call(url, target = nil)
23
+ uri = URI.parse(url)
24
+ (MAX_REDIRECTS + 1).times do
25
+ outcome = fetch(uri, target)
26
+ return outcome unless outcome.is_a?(URI::Generic)
27
+
28
+ uri = outcome
29
+ end
30
+ raise Error.new("download_failed", "download answered more than #{MAX_REDIRECTS} redirects")
31
+ end
32
+
33
+ private
34
+
35
+ # One step: the result, or the URI a redirect points at.
36
+ def fetch(uri, target)
37
+ outcome = nil
38
+ @connection.perform("GET", uri, @headers, nil) { |response| outcome = receive(uri, response, target) }
39
+ outcome
40
+ rescue WriteFailed => e
41
+ raise e.cause
42
+ rescue *Connection::NETWORK_ERRORS => e
43
+ raise Error.new("network_error", e.message)
44
+ end
45
+
46
+ def receive(uri, response, target)
47
+ status = response.code.to_i
48
+ location = response["Location"]
49
+ return uri + location if REDIRECTS.include?(status) && location && !location.empty?
50
+ raise Error.new("download_failed", "download answered HTTP #{status}", status: status) if status >= 400
51
+
52
+ target.nil? ? response.read_body.to_s.b : write(response, target)
53
+ end
54
+
55
+ # Into an IO as it is, or into a file a path names, which a broken download does not leave
56
+ # behind.
57
+ def write(response, target)
58
+ return stream(response, target) if target.respond_to?(:write)
59
+
60
+ file = begin
61
+ File.open(target, "wb")
62
+ rescue SystemCallError, IOError
63
+ raise WriteFailed
64
+ end
65
+ begin
66
+ stream(response, file)
67
+ rescue StandardError
68
+ file.close
69
+ remove(target)
70
+ raise
71
+ ensure
72
+ file.close unless file.closed?
73
+ end
74
+ end
75
+
76
+ def stream(response, io)
77
+ written = 0
78
+ response.read_body do |chunk|
79
+ begin
80
+ io.write(chunk)
81
+ rescue SystemCallError, IOError
82
+ raise WriteFailed
83
+ end
84
+ written += chunk.bytesize
85
+ end
86
+ written
87
+ end
88
+
89
+ def remove(path)
90
+ File.delete(path)
91
+ rescue SystemCallError
92
+ # already gone, or never there
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Internal
5
+ # Typed reads of a decoded answer. A field the API leaves out, or sends with a type this release
6
+ # does not expect, reads as its default, so an SDK of today reads the answers of a later API (the
7
+ # contract goldens hold that). Values the API may add to (statuses, outputs, kinds) stay strings.
8
+ module Fields
9
+ module_function
10
+
11
+ def string(from, key, default = "")
12
+ value = from[key]
13
+ case value
14
+ when String then value
15
+ when Integer, Float then value.to_s
16
+ else default
17
+ end
18
+ end
19
+
20
+ def string_or_nil(from, key)
21
+ value = from[key]
22
+ value.is_a?(String) ? value : nil
23
+ end
24
+
25
+ def int(from, key, default = 0)
26
+ int_or_nil(from, key) || default
27
+ end
28
+
29
+ def int_or_nil(from, key)
30
+ value = from[key]
31
+ case value
32
+ when Integer then value
33
+ when Float then value.finite? ? value.to_i : nil
34
+ end
35
+ end
36
+
37
+ def float(from, key, default = 0.0)
38
+ float_or_nil(from, key) || default
39
+ end
40
+
41
+ def float_or_nil(from, key)
42
+ value = from[key]
43
+ value.is_a?(Integer) || value.is_a?(Float) ? value.to_f : nil
44
+ end
45
+
46
+ def bool(from, key, default: false)
47
+ value = from[key]
48
+ [true, false].include?(value) ? value : default
49
+ end
50
+
51
+ def map(from, key)
52
+ map_or_nil(from, key) || {}
53
+ end
54
+
55
+ def map_or_nil(from, key)
56
+ value = from[key]
57
+ value.is_a?(Hash) ? value : nil
58
+ end
59
+
60
+ # The entries of a list that are strings.
61
+ def strings(from, key)
62
+ value = from[key]
63
+ value.is_a?(Array) ? value.grep(String) : []
64
+ end
65
+
66
+ # The entries of a list that are objects.
67
+ def objects(from, key)
68
+ value = from[key]
69
+ value.is_a?(Array) ? value.grep(Hash) : []
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Formfeed
4
+ module Internal
5
+ # A multipart body the way the API reads it: the file as +file+, strings as they are, booleans
6
+ # and numbers as text, arrays and hashes as JSON text. Nil fields are left out, as a form field
7
+ # cannot say null, but for redact's +fill+, whose nil draws no box and goes as the JSON text
8
+ # +null+.
9
+ class Multipart
10
+ # The fields as they are sent, for tests.
11
+ attr_reader :fields
12
+
13
+ def initialize(fields, file)
14
+ @boundary = "formfeed-#{SecureRandom.hex(12)}"
15
+ @file = file
16
+ @fields = {}
17
+ fields.each do |name, value|
18
+ name = name.to_s
19
+ next if value.nil? && name != "fill"
20
+
21
+ @fields[name] = self.class.text(value)
22
+ end
23
+ end
24
+
25
+ def self.text(value)
26
+ case value
27
+ when String then value
28
+ when true then "true"
29
+ when false then "false"
30
+ when Integer, Float, Symbol then value.to_s
31
+ else JSON.generate(value)
32
+ end
33
+ end
34
+
35
+ def content_type
36
+ "multipart/form-data; boundary=#{@boundary}"
37
+ end
38
+
39
+ # The bytes of the body, the same for every attempt.
40
+ def body
41
+ out = String.new(encoding: Encoding::BINARY)
42
+ if @file
43
+ out << "--#{@boundary}\r\n" \
44
+ "Content-Disposition: form-data; name=\"file\"; filename=\"#{quoted(@file.name)}\"\r\n" \
45
+ "Content-Type: #{@file.content_type}\r\n\r\n".b
46
+ out << @file.contents.b << "\r\n"
47
+ end
48
+ @fields.each do |name, value|
49
+ out << "--#{@boundary}\r\nContent-Disposition: form-data; name=\"#{quoted(name)}\"\r\n\r\n".b
50
+ out << value.b << "\r\n"
51
+ end
52
+ out << "--#{@boundary}--\r\n"
53
+ end
54
+
55
+ private
56
+
57
+ def quoted(value)
58
+ value.gsub('"', "%22").delete("\r\n")
59
+ end
60
+ end
61
+ end
62
+ end