// Drop-in Kotlin client library for the Friendship Tracker HTTP API. // // Save this file under your project as `FriendshipClient.kt`, in a // directory matching `package friendship_client`, then call the // FriendshipClient class: // // import friendship_client.FriendshipClient // // val c = FriendshipClient("pat_...") // val rows = c.accountList(mapOf("limit" to 20, "sort" to "-created_at")) // val fresh = c.accountCreate(mapOf("name" to "Example GmbH")) // // Every endpoint exposed by the HTTP API is wrapped as a typed method // on FriendshipClient. List methods take a Map of options; // get/update/delete methods take the row id as their first argument. // // Provided as-is, with no warranty. Vendor freely; modify as needed. // Targets Kotlin 1.9+ on JVM 11+; uses only the JDK (java.net.http). // // DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. // Local edits will be overwritten by the once-per-day version check. @file:Suppress("unused", "MemberVisibilityCanBePrivate", "ConstPropertyName") package friendship_client import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.Duration import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import kotlin.concurrent.thread class ApiException(val status: Int, message: String, val bodyRaw: String? = null) : RuntimeException("HTTP $status: $message") class FriendshipClient(token: String? = null) { companion object { const val APP_SLUG = "friendship" const val APP_NAME = "Friendship Tracker" const val MODULE_NAME = "friendship_client" const val CLIENT_VERSION = "0.3.13" const val LANGUAGE = "kotlin" private const val DEFAULT_BASE = "https://friendship-tracker.com" /** * Per-type metadata baked at generation time. Parse with your * preferred JSON library if you need the legal filters / sorts * / max_limit per model without an extra round-trip. */ const val TYPES_JSON = """{"activity":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","kind","summary","description","occurred_at","location"],"update_fields":["kind","summary","description","occurred_at","location"],"allowed_filters":["data__parent_id","data__kind","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__occurred_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"kind","type":"enum","values":["meeting","call","email","message","event","other"]},{"name":"summary","type":"string","max_len":400},{"name":"location","type":"string","max_len":200},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"description","type":"string","max_len":4000},{"name":"occurred_at","type":"string","max_len":32}]},"contact":{"ops":["list","read","create","update","delete"],"create_fields":["name","nickname","pronouns","email","phone","secondary_email","secondary_phone","company","job_title","address_line","city","country","website","linkedin","twitter","birthday","anniversary","gender","how_we_met","food_prefs","allergies","last_contacted_at","stay_in_touch_frequency","stay_in_touch_topic","notes","tags","favorite","avatar_blob_id","color"],"update_fields":["name","nickname","pronouns","email","phone","secondary_email","secondary_phone","company","job_title","address_line","city","country","website","linkedin","twitter","birthday","anniversary","gender","how_we_met","food_prefs","allergies","last_contacted_at","stay_in_touch_frequency","stay_in_touch_topic","notes","tags","favorite","avatar_blob_id","color"],"allowed_filters":["data__name","data__email","data__company","data__city","data__country","data__favorite","data__tags","data__gender","data__stay_in_touch_frequency","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__name","data__company","data__last_contacted_at","data__birthday","data__stay_in_touch_frequency"],"default_sort":"data__name","max_limit":200,"fields":[{"name":"city","type":"string","max_len":120},{"name":"name","type":"string","max_len":200},{"name":"tags","type":"tags"},{"name":"color","type":"string","max_len":24},{"name":"email","type":"string","max_len":320},{"name":"notes","type":"string","max_len":8000},{"name":"phone","type":"string","max_len":64},{"name":"gender","type":"enum","values":["male","female","other","unspecified"]},{"name":"company","type":"string","max_len":200},{"name":"country","type":"string","max_len":120},{"name":"twitter","type":"url"},{"name":"website","type":"url"},{"name":"birthday","type":"string","max_len":32},{"name":"favorite","type":"bool"},{"name":"linkedin","type":"url"},{"name":"nickname","type":"string","max_len":120},{"name":"pronouns","type":"string","max_len":32},{"name":"allergies","type":"string","max_len":600},{"name":"job_title","type":"string","max_len":200},{"name":"food_prefs","type":"string","max_len":600},{"name":"how_we_met","type":"string","max_len":1000},{"name":"anniversary","type":"string","max_len":32},{"name":"address_line","type":"string","max_len":200},{"name":"avatar_blob_id","type":"string","max_len":64},{"name":"secondary_email","type":"string","max_len":320},{"name":"secondary_phone","type":"string","max_len":64},{"name":"last_contacted_at","type":"string","max_len":32},{"name":"stay_in_touch_topic","type":"string","max_len":400},{"name":"stay_in_touch_frequency","type":"enum","values":["never","weekly","biweekly","monthly","quarterly","yearly"]}]},"conversation":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","channel","summary","content","occurred_at","sentiment","duration_minutes"],"update_fields":["channel","summary","content","occurred_at","sentiment","duration_minutes"],"allowed_filters":["data__parent_id","data__channel","data__sentiment","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__occurred_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"channel","type":"enum","values":["call","sms","whatsapp","email","in_person","video","voice","letter","other"]},{"name":"content","type":"string","max_len":8000},{"name":"summary","type":"string","max_len":400},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"sentiment","type":"enum","values":["positive","neutral","negative"]},{"name":"occurred_at","type":"string","max_len":32},{"name":"duration_minutes","type":"number"}]},"custom_field":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","label","value","kind","icon"],"update_fields":["label","value","kind","icon"],"allowed_filters":["data__parent_id","data__kind","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__label"],"default_sort":"created_at","max_limit":200,"fields":[{"name":"icon","type":"string","max_len":32},{"name":"kind","type":"enum","values":["text","number","date","url","bool"]},{"name":"label","type":"string","max_len":80},{"name":"value","type":"string","max_len":2000},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}}]},"gift":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","title","occasion","status","occurred_at","price","currency","url","notes"],"update_fields":["title","occasion","status","occurred_at","price","currency","url","notes"],"allowed_filters":["data__parent_id","data__status","data__occasion","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__occurred_at","data__title"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"url","type":"url"},{"name":"notes","type":"string","max_len":4000},{"name":"price","type":"number"},{"name":"title","type":"string","max_len":200},{"name":"status","type":"enum","values":["idea","given","received"]},{"name":"currency","type":"string","max_len":8},{"name":"occasion","type":"string","max_len":120},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"occurred_at","type":"string","max_len":32}]},"journal_entry":{"ops":["list","read","create","update","delete"],"create_fields":["title","body","mood","occurred_at","tags"],"update_fields":["title","body","mood","occurred_at","tags"],"allowed_filters":["data__mood","data__tags","status","is_archived","owned_by"],"allowed_sorts":["data__occurred_at","created_at","updated_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"body","type":"string","max_len":16000},{"name":"mood","type":"enum","values":["great","good","ok","down","awful"]},{"name":"tags","type":"tags"},{"name":"title","type":"string","max_len":200},{"name":"occurred_at","type":"string","max_len":32}]},"life_event":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","kind","title","occurred_at","description","location","recurring"],"update_fields":["kind","title","occurred_at","description","location","recurring"],"allowed_filters":["data__parent_id","data__kind","data__recurring","status","is_archived","owned_by"],"allowed_sorts":["data__occurred_at","created_at"],"default_sort":"data__occurred_at","max_limit":200,"fields":[{"name":"kind","type":"enum","values":["birthday","anniversary","met","graduation","job_start","job_end","move","marriage","birth","loss","milestone","custom"]},{"name":"title","type":"string","max_len":200},{"name":"location","type":"string","max_len":200},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"recurring","type":"bool"},{"name":"description","type":"string","max_len":4000},{"name":"occurred_at","type":"string","max_len":32}]},"note":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","body","pinned"],"update_fields":["body","pinned"],"allowed_filters":["data__parent_id","data__pinned","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at"],"default_sort":"created_at","max_limit":200,"fields":[{"name":"body","type":"string","max_len":8000},{"name":"pinned","type":"bool"},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}}]},"pet":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","name","species","species_other","breed","born_at","color","notes"],"update_fields":["name","species","species_other","breed","born_at","color","notes"],"allowed_filters":["data__parent_id","data__species","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__name","data__born_at"],"default_sort":"data__name","max_limit":200,"fields":[{"name":"name","type":"string","max_len":80},{"name":"breed","type":"string","max_len":120},{"name":"color","type":"string","max_len":80},{"name":"notes","type":"string","max_len":2000},{"name":"born_at","type":"string","max_len":32},{"name":"species","type":"enum","values":["dog","cat","bird","fish","rabbit","hamster","guinea_pig","reptile","horse","other"]},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"species_other","type":"string","max_len":80}]},"relationship":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","target_id","kind","label","since","notes"],"update_fields":["kind","label","since","notes"],"allowed_filters":["data__parent_id","data__target_id","data__kind","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__kind"],"default_sort":"data__kind","max_limit":200,"fields":[{"name":"kind","type":"enum","values":["partner","spouse","parent","child","sibling","friend","colleague","manager","report","mentor","mentee","other"]},{"name":"label","type":"string","max_len":80},{"name":"notes","type":"string","max_len":2000},{"name":"since","type":"string","max_len":32},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}},{"name":"target_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}}]},"reminder":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","message","due_date","completed"],"update_fields":["message","due_date","completed"],"allowed_filters":["data__parent_id","data__completed","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__due_date"],"default_sort":"data__due_date","max_limit":200,"fields":[{"name":"message","type":"string","max_len":400},{"name":"due_date","type":"string","max_len":32},{"name":"completed","type":"bool"},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"contact","owned":true,"optional":false}}]}}""" private val META_SENT_ONCE = AtomicBoolean(false) private val AUTOUPDATE_TRIED = AtomicBoolean(false) private val RETRYABLE = setOf(408, 425, 429, 500, 502, 503, 504) private const val MAX_RETRIES = 3 private fun stateDir(): Path? { val home = System.getProperty("user.home") ?: System.getenv("HOME") ?: System.getenv("USERPROFILE") ?: return null return try { val p = Paths.get(home, ".$MODULE_NAME") Files.createDirectories(p) p } catch (_: Exception) { null } } private fun loadOrMintDeviceId(): String { val d = stateDir() ?: return UUID.randomUUID().toString() val f = d.resolve("device.json") if (Files.exists(f)) { try { val raw = Files.readString(f, StandardCharsets.UTF_8) val did = jsonExtractString(raw, "device_id") if (!did.isNullOrEmpty() && did.length >= 32) return did } catch (_: Exception) { /* fall through */ } } val fresh = UUID.randomUUID().toString() try { Files.writeString(f, "{\"device_id\":\"$fresh\"}", StandardCharsets.UTF_8) } catch (_: Exception) {} return fresh } private fun autoupdateEnabled(): Boolean { val v = (System.getenv("XCLIENT_NO_AUTOUPDATE") ?: "").lowercase() return v != "1" && v != "true" && v != "yes" } private fun fingerprint(): Map { val tp = (System.getenv("TERM_PROGRAM") ?: "").lowercase() return mapOf( "kotlin_version" to KotlinVersion.CURRENT.toString(), "java_version" to System.getProperty("java.version"), "os" to System.getProperty("os.name"), "term_program" to System.getenv("TERM_PROGRAM"), "editor_env" to System.getenv("EDITOR"), "ci" to (System.getenv("CI") != null || System.getenv("GITHUB_ACTIONS") != null), "claude_code" to (System.getenv("CLAUDECODE") != null || System.getenv("CLAUDE_CODE_ENTRYPOINT") != null), "codex" to (System.getenv("CODEX_HOME") != null), "vscode" to (tp == "vscode" && System.getenv("CURSOR_TRACE_ID") == null), "cursor" to (System.getenv("CURSOR_TRACE_ID") != null), "antigravity" to (System.getenv("ANTIGRAVITY_TRACE_ID") != null), "jetbrains" to tp.contains("jetbrains"), ) } private fun originOf(uri: URI): String { val scheme = (uri.scheme ?: "").lowercase() val host = (uri.host ?: "").lowercase() val port = if (uri.port < 0) (if (scheme == "https") 443 else 80) else uri.port return "$scheme://$host:$port" } private fun backoffMillis(attempt: Int, retryAfter: String?): Long { if (!retryAfter.isNullOrEmpty()) { val v = retryAfter.toDoubleOrNull() if (v != null) return (minOf(v, 60.0) * 1000.0).toLong() } return (minOf(Math.pow(2.0, attempt.toDouble()), 60.0) * 1000.0).toLong() } // ── Tiny stdlib JSON helpers (encoder + extractor + decoder) ─ // The JDK ships no JSON parser. We hand-roll the bare minimum // so the library stays dependency-free; users wanting a full // model layer should plug Jackson / Moshi / kotlinx.serialization // around the Map we return. @Suppress("UNCHECKED_CAST") fun encodeJson(value: Any?): String = buildString { encodeAny(this, value) } private fun encodeAny(sb: StringBuilder, value: Any?) { when (value) { null -> sb.append("null") is String -> encodeString(sb, value) is Boolean, is Number -> sb.append(value.toString()) is Map<*, *> -> { sb.append("{") var first = true for ((k, v) in value) { if (!first) sb.append(",") encodeString(sb, k.toString()) sb.append(":") encodeAny(sb, v) first = false } sb.append("}") } is Iterable<*> -> { sb.append("[") var first = true for (v in value) { if (!first) sb.append(",") encodeAny(sb, v) first = false } sb.append("]") } is Array<*> -> encodeAny(sb, value.toList()) else -> encodeString(sb, value.toString()) } } private fun encodeString(sb: StringBuilder, s: String) { sb.append('"') for (c in s) { when (c) { '"' -> sb.append("\\\"") '\\' -> sb.append("\\\\") '\n' -> sb.append("\\n") '\r' -> sb.append("\\r") '\t' -> sb.append("\\t") else -> if (c.code < 0x20) sb.append("\\u%04x".format(c.code)) else sb.append(c) } } sb.append('"') } fun jsonExtractString(json: String?, key: String): String? { if (json == null) return null val needle = "\"$key\"" val idx = json.indexOf(needle); if (idx < 0) return null val colon = json.indexOf(':', idx + needle.length); if (colon < 0) return null var i = colon + 1 while (i < json.length && json[i].isWhitespace()) i++ if (i >= json.length || json[i] != '"') return null val out = StringBuilder() i++ while (i < json.length) { val c = json[i] if (c == '\\' && i + 1 < json.length) { val n = json[i + 1] when (n) { '"', '\\', '/' -> { out.append(n); i += 2 } 'n' -> { out.append('\n'); i += 2 } 't' -> { out.append('\t'); i += 2 } 'r' -> { out.append('\r'); i += 2 } else -> { out.append(n); i += 2 } } continue } if (c == '"') break out.append(c); i++ } return out.toString() } fun decodeJsonObject(json: String): Map { val pos = intArrayOf(0) return when (val v = parseJsonValue(json, pos)) { is Map<*, *> -> @Suppress("UNCHECKED_CAST") (v as Map) else -> mapOf("data" to v) } } private fun parseJsonValue(s: String, pos: IntArray): Any? { skipWs(s, pos) if (pos[0] >= s.length) return null return when (s[pos[0]]) { '{' -> parseJsonObject(s, pos) '[' -> parseJsonArray(s, pos) '"' -> parseJsonString(s, pos) 't', 'f' -> parseJsonBool(s, pos) 'n' -> { pos[0] += 4; null } else -> parseJsonNumber(s, pos) } } private fun parseJsonObject(s: String, pos: IntArray): MutableMap { val out = LinkedHashMap() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == '}') { pos[0]++; return out } while (pos[0] < s.length) { skipWs(s, pos) val key = parseJsonString(s, pos) ?: "" skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ':') pos[0]++ out[key] = parseJsonValue(s, pos) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == '}') { pos[0]++; break } } return out } private fun parseJsonArray(s: String, pos: IntArray): MutableList { val out = mutableListOf() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ']') { pos[0]++; return out } while (pos[0] < s.length) { out.add(parseJsonValue(s, pos)) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == ']') { pos[0]++; break } } return out } private fun parseJsonString(s: String, pos: IntArray): String? { if (pos[0] >= s.length || s[pos[0]] != '"') return null pos[0]++ val out = StringBuilder() while (pos[0] < s.length) { val c = s[pos[0]] if (c == '"') { pos[0]++; return out.toString() } if (c == '\\' && pos[0] + 1 < s.length) { val n = s[pos[0] + 1] pos[0] += 2 when (n) { '"' -> out.append('"') '\\' -> out.append('\\') '/' -> out.append('/') 'n' -> out.append('\n') 't' -> out.append('\t') 'r' -> out.append('\r') 'b' -> out.append('\b') 'f' -> out.append('\u000c') 'u' -> { if (pos[0] + 4 <= s.length) { try { out.append(Integer.parseInt(s.substring(pos[0], pos[0] + 4), 16).toChar()) pos[0] += 4 } catch (_: NumberFormatException) {} } } else -> out.append(n) } continue } out.append(c); pos[0]++ } return out.toString() } private fun parseJsonBool(s: String, pos: IntArray): Boolean? { if (s.startsWith("true", pos[0])) { pos[0] += 4; return true } if (s.startsWith("false", pos[0])) { pos[0] += 5; return false } pos[0]++ return null } private fun parseJsonNumber(s: String, pos: IntArray): Any? { val start = pos[0]; var fp = false while (pos[0] < s.length) { val c = s[pos[0]] if (c == '-' || c == '+' || c.isDigit()) pos[0]++ else if (c == '.' || c == 'e' || c == 'E') { fp = true; pos[0]++ } else break } val num = s.substring(start, pos[0]) return try { if (fp) num.toDouble() else num.toLong() } catch (_: NumberFormatException) { num } } private fun skipWs(s: String, pos: IntArray) { while (pos[0] < s.length && s[pos[0]].isWhitespace()) pos[0]++ } } private val http: HttpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(15)) .followRedirects(HttpClient.Redirect.NEVER) .build() private var baseUrl: String = (System.getenv("XCLIENT_BASE_URL")?.takeIf { it.isNotEmpty() } ?: DEFAULT_BASE).trimEnd('/') private var token: String = (token?.takeIf { it.isNotEmpty() } ?: System.getenv("XCLIENT_TOKEN") ?: "") private val deviceId: String = loadOrMintDeviceId() private val sessionId: String = UUID.randomUUID().toString() fun setToken(token: String?) { this.token = token ?: "" } fun setBaseUrl(baseUrl: String){ this.baseUrl = baseUrl.trimEnd('/') } // ── HTTP transport ─────────────────────────────────────────────── fun requestList(path: String, opts: Map?): Map? { val qs = StringBuilder() if (opts != null) { for ((k, v) in opts) { if (v == null) continue if (qs.isNotEmpty()) qs.append("&") qs.append(URLEncoder.encode(k, StandardCharsets.UTF_8)) qs.append("=") qs.append(URLEncoder.encode(v.toString(), StandardCharsets.UTF_8)) } } val full = if (qs.isNotEmpty()) "$path?$qs" else path return requestJson("GET", full, null) } fun requestJson(method: String, path: String, body: Map?): Map? { maybeAutoupdate() val url = baseUrl + path val json = body?.let { encodeJson(it) } var lastErr: Throwable? = null for (attempt in 0 until MAX_RETRIES) { try { val resp = sendFollowingRedirects(method, url, json) resp.headers().firstValue("x-auth-refresh-token").orElse(null)?.takeIf { it.isNotEmpty() }?.let { token = it } val status = resp.statusCode() if (RETRYABLE.contains(status) && attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, resp.headers().firstValue("Retry-After").orElse(null))) continue } if (status >= 400) { emitCallEvent(method, path, status, false) val msg = jsonExtractString(resp.body(), "detail") ?: jsonExtractString(resp.body(), "message") ?: "HTTP $status" throw ApiException(status, msg, resp.body()) } emitCallEvent(method, path, status, true) val raw = resp.body() ?: return null return if (raw.isEmpty()) null else decodeJsonObject(raw) } catch (e: ApiException) { throw e } catch (e: Exception) { lastErr = e if (attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, null)) continue } emitCallEvent(method, path, 0, false) throw ApiException(0, e.message ?: "request failed") } } emitCallEvent(method, path, 0, false) throw ApiException(0, lastErr?.message ?: "request failed") } private fun sendFollowingRedirects(method: String, url: String, json: String?): HttpResponse { var currentUrl = url var currentMethod = method.uppercase() var currentJson = json var stripAuth = false val maxHops = 5 for (hop in 0..maxHops) { val b = HttpRequest.newBuilder() .uri(URI.create(currentUrl)) .timeout(Duration.ofSeconds(30)) .header("Accept", "application/json") .header("User-Agent", userAgent()) .header("X-Client-Channel", "client_$LANGUAGE") .header("X-Client-Version", CLIENT_VERSION) .header("X-Analytics-Device-Id", deviceId) .header("X-Analytics-Session-Id", sessionId) if (!stripAuth && token.isNotEmpty()) b.header("Authorization", "Bearer $token") if (currentJson != null && currentMethod != "GET" && currentMethod != "HEAD") { b.header("Content-Type", "application/json") b.method(currentMethod, HttpRequest.BodyPublishers.ofString(currentJson, StandardCharsets.UTF_8)) } else { b.method(currentMethod, HttpRequest.BodyPublishers.noBody()) } val resp = http.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)) val status = resp.statusCode() if (status < 300 || status >= 400 || status == 304 || hop == maxHops) return resp val loc = resp.headers().firstValue("Location").orElse(null) ?: return resp val nextUri = try { URI.create(currentUrl).resolve(loc) } catch (_: IllegalArgumentException) { return resp } if (!originOf(URI.create(currentUrl)).equals(originOf(nextUri), ignoreCase = true)) { stripAuth = true } if (status == 303 || ((status == 301 || status == 302) && currentMethod != "GET" && currentMethod != "HEAD")) { currentMethod = "GET" currentJson = null } currentUrl = nextUri.toString() } throw java.io.IOException("redirect chain exceeded max hops") } private fun userAgent() = "$MODULE_NAME/$CLIENT_VERSION (lib/$LANGUAGE; kotlin/${KotlinVersion.CURRENT}; java/${System.getProperty("java.version")})" // ── Analytics ──────────────────────────────────────────────────── private fun emitCallEvent(method: String, path: String, status: Int, ok: Boolean) { val includeEnv = META_SENT_ONCE.compareAndSet(false, true) thread(start = true, isDaemon = true, name = "$MODULE_NAME-analytics") { try { val meta = LinkedHashMap() meta["channel"] = "client_$LANGUAGE" meta["client_version"] = CLIENT_VERSION meta["module_name"] = MODULE_NAME meta["language"] = LANGUAGE meta["os"] = System.getProperty("os.name") meta["kotlin_version"] = KotlinVersion.CURRENT.toString() if (includeEnv) meta["env"] = fingerprint() val evt = mapOf( "type" to "client.call", "ts_client" to (System.currentTimeMillis() / 1000L), "meta" to mapOf( "method" to method.uppercase(), "path" to path.split('?').first(), "status" to status, "ok" to ok, ), ) val body = mapOf( "device_id" to deviceId, "session_id" to sessionId, "events" to listOf(evt), "meta" to meta, ) val req = HttpRequest.newBuilder() .uri(URI.create("$baseUrl/xapi2/analytics/challenge")) .timeout(Duration.ofSeconds(4)) .header("Content-Type", "application/json") .header("User-Agent", userAgent()) .POST(HttpRequest.BodyPublishers.ofString(encodeJson(body), StandardCharsets.UTF_8)) .build() http.send(req, HttpResponse.BodyHandlers.discarding()) } catch (_: Throwable) { /* fire and forget */ } } } // ── Auto-update ────────────────────────────────────────────────── private fun maybeAutoupdate() { if (!AUTOUPDATE_TRIED.compareAndSet(false, true)) return if (!autoupdateEnabled()) return thread(start = true, isDaemon = true, name = "$MODULE_NAME-autoupdate") { try { val d = stateDir() ?: return@thread val stamp = d.resolve("update_check.json") val now = System.currentTimeMillis() / 1000L if (Files.exists(stamp)) { try { val raw = Files.readString(stamp, StandardCharsets.UTF_8) val checked = jsonExtractString(raw, "checked_at")?.toLongOrNull() if (checked != null && now - checked < 86400) return@thread } catch (_: Exception) {} } Files.writeString(stamp, "{\"checked_at\":\"$now\"}", StandardCharsets.UTF_8) // Source replacement is intentionally a no-op - the // user is running compiled JVM bytecode, the .kt file // is just a record of the version they vendored. } catch (_: Throwable) {} } } // ── 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 `activity` rows. */ fun activityList(opts: Map? = null): Map? = requestList("/xapi2/data/activity", opts) /** Fetch one `activity` row by id. */ fun activityGet(id: String): Map? = requestJson("GET", "/xapi2/data/activity/" + id, null) /** Create a new `activity` row. */ fun activityCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/activity", data) /** Patch a `activity` row. */ fun activityUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/activity/" + id, data) /** Delete a `activity` row. */ fun activityDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/activity/" + id, null) return true } /** List `contact` rows. */ fun contactList(opts: Map? = null): Map? = requestList("/xapi2/data/contact", opts) /** Fetch one `contact` row by id. */ fun contactGet(id: String): Map? = requestJson("GET", "/xapi2/data/contact/" + id, null) /** Create a new `contact` row. */ fun contactCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/contact", data) /** Patch a `contact` row. */ fun contactUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/contact/" + id, data) /** Delete a `contact` row. */ fun contactDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/contact/" + id, null) return true } /** List `conversation` rows. */ fun conversationList(opts: Map? = null): Map? = requestList("/xapi2/data/conversation", opts) /** Fetch one `conversation` row by id. */ fun conversationGet(id: String): Map? = requestJson("GET", "/xapi2/data/conversation/" + id, null) /** Create a new `conversation` row. */ fun conversationCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/conversation", data) /** Patch a `conversation` row. */ fun conversationUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/conversation/" + id, data) /** Delete a `conversation` row. */ fun conversationDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/conversation/" + id, null) return true } /** List `custom_field` rows. */ fun customFieldList(opts: Map? = null): Map? = requestList("/xapi2/data/custom_field", opts) /** Fetch one `custom_field` row by id. */ fun customFieldGet(id: String): Map? = requestJson("GET", "/xapi2/data/custom_field/" + id, null) /** Create a new `custom_field` row. */ fun customFieldCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/custom_field", data) /** Patch a `custom_field` row. */ fun customFieldUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/custom_field/" + id, data) /** Delete a `custom_field` row. */ fun customFieldDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/custom_field/" + id, null) return true } /** List `gift` rows. */ fun giftList(opts: Map? = null): Map? = requestList("/xapi2/data/gift", opts) /** Fetch one `gift` row by id. */ fun giftGet(id: String): Map? = requestJson("GET", "/xapi2/data/gift/" + id, null) /** Create a new `gift` row. */ fun giftCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/gift", data) /** Patch a `gift` row. */ fun giftUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/gift/" + id, data) /** Delete a `gift` row. */ fun giftDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/gift/" + id, null) return true } /** List `journal_entry` rows. */ fun journalEntryList(opts: Map? = null): Map? = requestList("/xapi2/data/journal_entry", opts) /** Fetch one `journal_entry` row by id. */ fun journalEntryGet(id: String): Map? = requestJson("GET", "/xapi2/data/journal_entry/" + id, null) /** Create a new `journal_entry` row. */ fun journalEntryCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/journal_entry", data) /** Patch a `journal_entry` row. */ fun journalEntryUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/journal_entry/" + id, data) /** Delete a `journal_entry` row. */ fun journalEntryDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/journal_entry/" + id, null) return true } /** List `life_event` rows. */ fun lifeEventList(opts: Map? = null): Map? = requestList("/xapi2/data/life_event", opts) /** Fetch one `life_event` row by id. */ fun lifeEventGet(id: String): Map? = requestJson("GET", "/xapi2/data/life_event/" + id, null) /** Create a new `life_event` row. */ fun lifeEventCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/life_event", data) /** Patch a `life_event` row. */ fun lifeEventUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/life_event/" + id, data) /** Delete a `life_event` row. */ fun lifeEventDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/life_event/" + id, null) return true } /** List `note` rows. */ fun noteList(opts: Map? = null): Map? = requestList("/xapi2/data/note", opts) /** Fetch one `note` row by id. */ fun noteGet(id: String): Map? = requestJson("GET", "/xapi2/data/note/" + id, null) /** Create a new `note` row. */ fun noteCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/note", data) /** Patch a `note` row. */ fun noteUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/note/" + id, data) /** Delete a `note` row. */ fun noteDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/note/" + id, null) return true } /** List `pet` rows. */ fun petList(opts: Map? = null): Map? = requestList("/xapi2/data/pet", opts) /** Fetch one `pet` row by id. */ fun petGet(id: String): Map? = requestJson("GET", "/xapi2/data/pet/" + id, null) /** Create a new `pet` row. */ fun petCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/pet", data) /** Patch a `pet` row. */ fun petUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/pet/" + id, data) /** Delete a `pet` row. */ fun petDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/pet/" + id, null) return true } /** List `relationship` rows. */ fun relationshipList(opts: Map? = null): Map? = requestList("/xapi2/data/relationship", opts) /** Fetch one `relationship` row by id. */ fun relationshipGet(id: String): Map? = requestJson("GET", "/xapi2/data/relationship/" + id, null) /** Create a new `relationship` row. */ fun relationshipCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/relationship", data) /** Patch a `relationship` row. */ fun relationshipUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/relationship/" + id, data) /** Delete a `relationship` row. */ fun relationshipDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/relationship/" + id, null) return true } /** List `reminder` rows. */ fun reminderList(opts: Map? = null): Map? = requestList("/xapi2/data/reminder", opts) /** Fetch one `reminder` row by id. */ fun reminderGet(id: String): Map? = requestJson("GET", "/xapi2/data/reminder/" + id, null) /** Create a new `reminder` row. */ fun reminderCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/reminder", data) /** Patch a `reminder` row. */ fun reminderUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/reminder/" + id, data) /** Delete a `reminder` row. */ fun reminderDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/reminder/" + id, null) return true } }