# frozen_string_literal: true # Drop-in Ruby client library for the Production Board HTTP API. # # Save this file under your project as `prod_client.rb` and require # it directly: # # require_relative 'prod_client' # c = ProdClient::Client.new('pat_...') # rows = c.account_list(limit: 20, sort: '-created_at') # fresh = c.account_create({ 'name' => 'Example GmbH' }) # # Every endpoint exposed by the HTTP API is wrapped as an # `_` instance method on Client. List methods take keyword # args; get/update/delete methods take the row id as their first # positional argument. # # Provided as-is, with no warranty. Vendor freely; modify as needed. # Targets Ruby 3.0+; uses only the stdlib (`net/http`, `json`, # `securerandom`, `uri`). # # DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. # Local edits will be overwritten by the once-per-day version check. require 'net/http' require 'uri' require 'json' require 'securerandom' require 'fileutils' module ProdClient APP_SLUG = 'prod' APP_NAME = 'Production Board' MODULE_NAME = 'prod_client' CLIENT_VERSION = '0.3.13' LANGUAGE = 'ruby' DEFAULT_BASE = 'https://produktions-management-board.de' # Per-type metadata baked at generation time. Inspect with JSON.parse # if you need the legal filters / sorts / max_limit per model without # an extra round-trip. TYPES_JSON = <<~'JSON_BLOB' {"board":{"ops":["list","read","create","update","delete"],"create_fields":["name","description","accent","settings","tags","columns"],"update_fields":["name","description","accent","settings","tags","columns"],"allowed_filters":["data__name","data__accent","data__tags","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__name"],"default_sort":"created_at","max_limit":50,"fields":[{"name":"name","type":"string","max_len":200},{"name":"tags","type":"tags"},{"name":"accent","type":"enum","values":["slate","gray","blue","indigo","violet","fuchsia","amber","orange","emerald","green","rose","red"]},{"name":"settings","type":"dict"},{"name":"description","type":"string","max_len":2000}]},"card":{"ops":["list","read","create","update","delete"],"create_fields":["title","description","status","position","priority","tags","assignee","due_date","board_id"],"update_fields":["title","description","status","position","priority","tags","assignee","due_date","board_id"],"allowed_filters":["data__status","data__priority","data__tags","data__assignee","data__board_id","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__position","data__status","data__priority","data__due_date"],"default_sort":"data__position","max_limit":200,"fields":[{"name":"tags","type":"tags"},{"name":"title","type":"string","max_len":200},{"name":"status","type":"string","max_len":64},{"name":"assignee","type":"string","max_len":64},{"name":"board_id","type":"string","max_len":64,"ref":{"type":"board","owned":true,"optional":true}},{"name":"due_date","type":"string","max_len":32},{"name":"position","type":"number"},{"name":"priority","type":"enum","values":["low","medium","high","critical"]},{"name":"description","type":"string","max_len":4000}]}} JSON_BLOB RETRYABLE_STATUSES = [408, 425, 429, 500, 502, 503, 504].freeze MAX_RETRIES = 3 DEFAULT_TIMEOUT = 30 class ApiError < StandardError attr_reader :status, :body_raw def initialize(status, message, body = nil) super("HTTP #{status}: #{message}") @status = status @body_raw = body end end class Client def initialize(token = nil) env_base = ENV['XCLIENT_BASE_URL'] @base_url = (env_base && !env_base.empty? ? env_base : DEFAULT_BASE).sub(%r{/+\z}, '') @token = (token && !token.empty? ? token : ENV.fetch('XCLIENT_TOKEN', '')).to_s @device_id = self.class.send(:load_or_mint_device_id) @session_id = SecureRandom.uuid @meta_sent_once = false @autoupdate_tried = false @meta_lock = Mutex.new end def set_token(token); @token = (token || '').to_s; end def set_base_url(url); @base_url = (url || '').sub(%r{/+\z}, ''); end # ── Identifier persistence ───────────────────────────────────── def self.state_dir home = ENV['HOME'] || ENV['USERPROFILE'] return nil if home.nil? || home.empty? d = File.join(home, ".#prod_client") FileUtils.mkdir_p(d, mode: 0o700) d rescue StandardError nil end private_class_method :state_dir def self.load_or_mint_device_id d = state_dir return SecureRandom.uuid if d.nil? f = File.join(d, 'device.json') if File.exist?(f) begin blob = JSON.parse(File.read(f)) did = blob['device_id'] return did if did.is_a?(String) && did.length >= 32 rescue StandardError # fall through to mint end end fresh = SecureRandom.uuid begin File.write(f, JSON.dump('device_id' => fresh)) File.chmod(0o600, f) rescue StandardError end fresh end private_class_method :load_or_mint_device_id def self.autoupdate_enabled? v = (ENV['XCLIENT_NO_AUTOUPDATE'] || '').downcase !%w[1 true yes].include?(v) end private_class_method :autoupdate_enabled? # ── Editor / runtime fingerprint ─────────────────────────────── def self.fingerprint tp = (ENV['TERM_PROGRAM'] || '').downcase { 'ruby_version' => RUBY_VERSION, 'ruby_engine' => RUBY_ENGINE, 'os' => RUBY_PLATFORM, 'term_program' => ENV['TERM_PROGRAM'], 'editor_env' => ENV['EDITOR'], 'ci' => !!(ENV['CI'] || ENV['GITHUB_ACTIONS']), 'claude_code' => !!(ENV['CLAUDECODE'] || ENV['CLAUDE_CODE_ENTRYPOINT']), 'codex' => !!ENV['CODEX_HOME'], 'vscode' => tp == 'vscode' && ENV['CURSOR_TRACE_ID'].nil?, 'cursor' => !!ENV['CURSOR_TRACE_ID'], 'antigravity' => !!ENV['ANTIGRAVITY_TRACE_ID'], 'jetbrains' => tp.include?('jetbrains'), } end private_class_method :fingerprint # ── HTTP transport ───────────────────────────────────────────── def request_list(path, opts = nil) qs = [] if opts.is_a?(Hash) opts.each do |k, v| next if v.nil? if k.to_s == 'filters' && v.is_a?(Hash) v.each { |fk, fv| next if fv.nil?; qs << "#{URI.encode_www_form_component(fk.to_s)}=#{URI.encode_www_form_component(fv.to_s)}" } next end qs << "#{URI.encode_www_form_component(k.to_s)}=#{URI.encode_www_form_component(v.to_s)}" end end path = path + (path.include?('?') ? '&' : '?') + qs.join('&') unless qs.empty? request_json('GET', path, nil) end def request_json(method, path, body) maybe_autoupdate url = @base_url + path json = body.nil? ? nil : JSON.dump(body) last_err = nil MAX_RETRIES.times do |attempt| begin status, headers, raw_body = send_following_redirects(method.to_s.upcase, url, json) fresh = headers['x-auth-refresh-token'] @token = fresh if fresh && !fresh.empty? if RETRYABLE_STATUSES.include?(status) && attempt + 1 < MAX_RETRIES ra = headers['retry-after'] sleep(self.class.send(:backoff_seconds, attempt, ra ? ra.to_f : nil)) next end parsed = raw_body.empty? ? nil : (JSON.parse(raw_body) rescue nil) if status >= 400 msg = parsed.is_a?(Hash) ? (parsed['detail'] || parsed['message'] || 'request failed') : 'request failed' emit_call_event(method, path, status, false) raise ApiError.new(status, msg, parsed) end emit_call_event(method, path, status, true) return parsed rescue ApiError raise rescue StandardError => e last_err = e sleep(self.class.send(:backoff_seconds, attempt, nil)) if attempt + 1 < MAX_RETRIES next if attempt + 1 < MAX_RETRIES emit_call_event(method, path, 0, false) raise ApiError.new(0, e.message) end end emit_call_event(method, path, 0, false) raise ApiError.new(0, last_err ? last_err.message : 'request failed') end # Walk the redirect chain manually so Authorization can be dropped # on cross-origin hops. Caps at 5 hops; mirrors RFC 7231 method # rewrite semantics. def send_following_redirects(method, url, json) current_url = url current_method = method current_json = json strip_auth = false 6.times do |hop| uri = URI.parse(current_url) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: DEFAULT_TIMEOUT) do |http| klass = case current_method when 'GET' then Net::HTTP::Get when 'POST' then Net::HTTP::Post when 'PATCH' then Net::HTTP::Patch when 'PUT' then Net::HTTP::Put when 'DELETE' then Net::HTTP::Delete when 'HEAD' then Net::HTTP::Head else Net::HTTP::Get end req = klass.new(uri.request_uri) req['Accept'] = 'application/json' req['User-Agent'] = user_agent req['X-Client-Channel'] = 'client_' + LANGUAGE req['X-Client-Version'] = CLIENT_VERSION req['X-Analytics-Device-Id'] = @device_id req['X-Analytics-Session-Id'] = @session_id req['Authorization'] = 'Bearer ' + @token if !strip_auth && !@token.empty? if current_json && current_method != 'GET' && current_method != 'HEAD' req['Content-Type'] = 'application/json' req.body = current_json end resp = http.request(req) status = resp.code.to_i headers = {} resp.each_header { |k, v| headers[k.downcase] = v } if status < 300 || status >= 400 || status == 304 || hop == 5 return [status, headers, resp.body.to_s] end loc = headers['location'] return [status, headers, resp.body.to_s] if loc.nil? || loc.empty? next_uri = (URI.parse(loc).absolute? rescue false) ? URI.parse(loc) : uri + loc if origin_of(next_uri) != origin_of(uri) strip_auth = true end if status == 303 || ([301, 302].include?(status) && current_method != 'GET' && current_method != 'HEAD') current_method = 'GET' current_json = nil end current_url = next_uri.to_s end end [0, {}, ''] end private :send_following_redirects def origin_of(uri) port = uri.port || (uri.scheme == 'https' ? 443 : 80) "#{uri.scheme}://#{uri.host}:#{port}".downcase end private :origin_of def self.backoff_seconds(attempt, retry_after) return [retry_after, 60.0].min if retry_after && retry_after >= 0 [2 ** attempt, 60.0].min.to_f end private_class_method :backoff_seconds def user_agent "#prod_client/#{CLIENT_VERSION} (lib/#ruby; ruby/#{RUBY_VERSION})" end private :user_agent # ── Analytics ────────────────────────────────────────────────── def emit_call_event(method, path, status, ok) include_env = nil @meta_lock.synchronize do include_env = !@meta_sent_once @meta_sent_once = true end Thread.new do begin meta = { 'channel' => 'client_' + LANGUAGE, 'client_version' => CLIENT_VERSION, 'module_name' => MODULE_NAME, 'language' => LANGUAGE, 'os' => RUBY_PLATFORM, 'ruby_version' => RUBY_VERSION, } meta['env'] = self.class.send(:fingerprint) if include_env body = { 'device_id' => @device_id, 'session_id' => @session_id, 'events' => [{ 'type' => 'client.call', 'ts_client' => Time.now.to_i, 'meta' => { 'method' => method.to_s.upcase, 'path' => path.split('?').first[0, 128], 'status' => status.to_i, 'ok' => !!ok, }, }], 'meta' => meta, } uri = URI.parse(@base_url + '/xapi2/analytics/challenge') Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 2, read_timeout: 4) do |http| req = Net::HTTP::Post.new(uri.request_uri) req['Content-Type'] = 'application/json' req['User-Agent'] = user_agent req.body = JSON.dump(body) http.request(req) end rescue StandardError # fire and forget end end end private :emit_call_event # ── Auto-update ──────────────────────────────────────────────── def maybe_autoupdate return if @autoupdate_tried @autoupdate_tried = true return unless self.class.send(:autoupdate_enabled?) Thread.new { run_autoupdate } end private :maybe_autoupdate def run_autoupdate d = self.class.send(:state_dir) return if d.nil? stamp = File.join(d, 'update_check.json') if File.exist?(stamp) begin blob = JSON.parse(File.read(stamp)) return if (Time.now.to_i - blob['checked_at'].to_i) < 86400 rescue StandardError end end File.write(stamp, JSON.dump('checked_at' => Time.now.to_i)) uri = URI.parse(@base_url + '/xapi2/clients/version') payload = nil Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 2, read_timeout: 4) do |http| resp = http.request(Net::HTTP::Get.new(uri.request_uri)) payload = (JSON.parse(resp.body) rescue nil) end return unless payload.is_a?(Hash) && payload['version'] && payload['version'] != CLIENT_VERSION uri2 = URI.parse(@base_url + '/xapi2/clients/script.' + LANGUAGE) body = nil Net::HTTP.start(uri2.host, uri2.port, use_ssl: uri2.scheme == 'https', open_timeout: 2, read_timeout: 10) do |http| body = http.request(Net::HTTP::Get.new(uri2.request_uri)).body end return unless body.is_a?(String) && self.class.send(:looks_like_valid_client?, body) target = File.expand_path(__FILE__) tmp = "#{target}.tmp.#{SecureRandom.hex(6)}" File.write(tmp, body) File.rename(tmp, target) rescue StandardError # best-effort end private :run_autoupdate def self.looks_like_valid_client?(blob) return false unless blob.is_a?(String) && blob.bytesize >= 2000 %w[MODULE_NAME CLIENT_VERSION APP_SLUG request_json].all? { |m| blob.include?(m) } end private_class_method :looks_like_valid_client? # ── Generated per-type wrapper methods ───────────────────────── # Every model that exposes an op gets one `_` method # below. The runtime above does the heavy lifting; these wrappers # just pin the URL + HTTP verb. # List `board` rows. Pass any allowed filters as keyword args. def board_list(**opts) request_list('/xapi2/data/board', opts) end # Fetch one `board` row by id. def board_get(id) request_json('GET', '/xapi2/data/board/' + id, nil) end # Create a new `board` row. def board_create(data) request_json('POST', '/xapi2/data/board', data) end # Patch a `board` row. def board_update(id, data) request_json('PATCH', '/xapi2/data/board/' + id, data) end # Delete a `board` row. Returns true on success. def board_delete(id) request_json('DELETE', '/xapi2/data/board/' + id, nil) true end # List `card` rows. Pass any allowed filters as keyword args. def card_list(**opts) request_list('/xapi2/data/card', opts) end # Fetch one `card` row by id. def card_get(id) request_json('GET', '/xapi2/data/card/' + id, nil) end # Create a new `card` row. def card_create(data) request_json('POST', '/xapi2/data/card', data) end # Patch a `card` row. def card_update(id, data) request_json('PATCH', '/xapi2/data/card/' + id, data) end # Delete a `card` row. Returns true on success. def card_delete(id) request_json('DELETE', '/xapi2/data/card/' + id, nil) true end end end