// Drop-in Dart client library for the Production Board HTTP API. // // Save this file under your project as `lib/prod_client.dart` and // import it directly: // // import 'package:my_project/prod_client.dart'; // // final c = ProdClient('pat_...'); // final rows = await c.accountList(opts: ListOpts(limit: 20, sort: '-created_at')); // final fresh = await c.accountCreate({{'name': 'Example GmbH'}}); // // Every endpoint exposed by the HTTP API is wrapped as a typed // `` method on ProdClient. List endpoints take an optional // ListOpts; get/update/delete endpoints take the row id as the first // argument. // // Provided as-is, with no warranty. Vendor freely; modify as needed. // Targets Dart 3.0+; uses only the platform stdlib (`dart:io`, // `dart:convert`, `dart:async`). // // DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. // Local edits will be overwritten by the once-per-day version check. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; // ── Identity (substituted at generation time) ──────────────────────── const String appSlug = 'prod'; const String appName = 'Production Board'; const String moduleName = 'prod_client'; const String clientVersion = '0.3.12'; const String language = 'dart'; const String _defaultBase = 'https://qtssystem.com'; /// Per-type metadata baked at generation time. Decoded once on first /// access; useful at runtime when calling code needs to know the legal /// filters / sort columns / max_limit for a model without a second /// round-trip. final Map types = json.decode(r'''{"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}]}}''') as Map; class ApiError implements Exception { final int status; final String message; final dynamic bodyRaw; ApiError(this.status, this.message, [this.bodyRaw]); @override String toString() => 'HTTP $status: $message'; } class ListOpts { final int? limit; final int? offset; final String? sort; final String? q; final Map? filters; ListOpts({this.limit, this.offset, this.sort, this.q, this.filters}); } class ProdClient { String _baseUrl; String _token; late final String _deviceId; late final String _sessionId; bool _autoupdateAttempted = false; bool _metaSentOnce = false; final HttpClient _http = HttpClient(); static const Set _retryableStatuses = {408, 425, 429, 500, 502, 503, 504}; static const int _maxRetries = 3; static const Duration _defaultTimeout = Duration(seconds: 30); ProdClient([String token = '']) : _baseUrl = _resolveBaseUrl(), _token = token.isNotEmpty ? token : (Platform.environment['XCLIENT_TOKEN'] ?? '') { _deviceId = _loadOrMintDeviceId(); _sessionId = _mintUuid(); _http.connectionTimeout = const Duration(seconds: 15); } void setToken(String token) { _token = token; } void setBaseUrl(String url) { _baseUrl = _trimRightSlash(url); } static String _trimRightSlash(String s) { var out = s; while (out.endsWith('/')) { out = out.substring(0, out.length - 1); } return out; } static String _resolveBaseUrl() { final env = Platform.environment['XCLIENT_BASE_URL']; return _trimRightSlash((env != null && env.isNotEmpty) ? env : _defaultBase); } // ── Identifier persistence ───────────────────────────────────────── static String? _stateDir() { final home = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; if (home == null || home.isEmpty) return null; final d = '$home/.${moduleName}'; try { Directory(d).createSync(recursive: true); return d; } catch (_) { return null; } } static String _mintUuid() { final rng = Random.secure(); final bytes = List.generate(16, (_) => rng.nextInt(256)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; String hx(int i) => bytes[i].toRadixString(16).padLeft(2, '0'); return '${hx(0)}${hx(1)}${hx(2)}${hx(3)}-${hx(4)}${hx(5)}-${hx(6)}${hx(7)}-${hx(8)}${hx(9)}-${hx(10)}${hx(11)}${hx(12)}${hx(13)}${hx(14)}${hx(15)}'; } static String _loadOrMintDeviceId() { final d = _stateDir(); if (d == null) return _mintUuid(); final f = File('$d/device.json'); if (f.existsSync()) { try { final blob = json.decode(f.readAsStringSync()) as Map; final did = blob['device_id']; if (did is String && did.length >= 32) return did; } catch (_) {} } final fresh = _mintUuid(); try { f.writeAsStringSync(json.encode({'device_id': fresh})); } catch (_) {} return fresh; } static bool _autoupdateEnabled() { final v = (Platform.environment['XCLIENT_NO_AUTOUPDATE'] ?? '').toLowerCase(); return v != '1' && v != 'true' && v != 'yes'; } static Map _fingerprint() { final env = Platform.environment; final tp = (env['TERM_PROGRAM'] ?? '').toLowerCase(); return { 'dart_version': Platform.version, 'os': Platform.operatingSystem, 'os_version': Platform.operatingSystemVersion, 'term_program': env['TERM_PROGRAM'], 'editor_env': env['EDITOR'], 'ci': env.containsKey('CI') || env.containsKey('GITHUB_ACTIONS'), 'claude_code': env.containsKey('CLAUDECODE') || env.containsKey('CLAUDE_CODE_ENTRYPOINT'), 'codex': env.containsKey('CODEX_HOME'), 'vscode': tp == 'vscode' && !env.containsKey('CURSOR_TRACE_ID'), 'cursor': env.containsKey('CURSOR_TRACE_ID'), 'antigravity': env.containsKey('ANTIGRAVITY_TRACE_ID'), 'jetbrains': tp.contains('jetbrains'), }; } String _userAgent() => '$moduleName/$clientVersion (lib/$language; dart/${Platform.version.split(' ').first}; ${Platform.operatingSystem})'; static double _backoffSeconds(int attempt, double? retryAfter) { if (retryAfter != null && retryAfter >= 0) return min(retryAfter, 60.0); return min(pow(2, attempt).toDouble(), 60.0); } // ── HTTP transport ───────────────────────────────────────────────── /// Generic request helper. JSON in / JSON out. Future?> requestJson( String method, String path, dynamic body) async { _maybeAutoupdate(); Object? lastErr; for (var attempt = 0; attempt < _maxRetries; attempt++) { try { final result = await _sendFollowingRedirects( method.toUpperCase(), '$_baseUrl$path', body); final status = result.status; final headers = result.headers; final raw = result.body; final fresh = headers['x-auth-refresh-token']; if (fresh != null && fresh.isNotEmpty) _token = fresh; if (_retryableStatuses.contains(status) && attempt + 1 < _maxRetries) { double? ra; final raStr = headers['retry-after']; if (raStr != null) ra = double.tryParse(raStr); await Future.delayed( Duration(milliseconds: (_backoffSeconds(attempt, ra) * 1000).round())); continue; } dynamic parsed; if (raw.isNotEmpty) { try { parsed = json.decode(raw); } catch (_) { parsed = null; } } if (status >= 400) { var msg = 'request failed'; if (parsed is Map) { final d = parsed['detail']; final m = parsed['message']; if (d is String) msg = d; else if (m is String) msg = m; } _emitCallEvent(method, path, status, false); throw ApiError(status, msg, parsed); } _emitCallEvent(method, path, status, true); if (parsed is Map) return parsed; return null; } on ApiError { rethrow; } catch (e) { lastErr = e; if (attempt + 1 < _maxRetries) { await Future.delayed( Duration(milliseconds: (_backoffSeconds(attempt, null) * 1000).round())); continue; } _emitCallEvent(method, path, 0, false); throw ApiError(0, e.toString()); } } _emitCallEvent(method, path, 0, false); throw ApiError(0, lastErr?.toString() ?? 'request failed'); } Future?> requestList(String path, ListOpts? opts) { final qs = {}; if (opts != null) { if (opts.limit != null) qs['limit'] = opts.limit.toString(); if (opts.offset != null) qs['offset'] = opts.offset.toString(); if (opts.sort != null && opts.sort!.isNotEmpty) qs['sort'] = opts.sort!; if (opts.q != null && opts.q!.isNotEmpty) qs['q'] = opts.q!; if (opts.filters != null) { opts.filters!.forEach((k, v) { if (v != null) qs[k] = v.toString(); }); } } var p = path; if (qs.isNotEmpty) { final encoded = qs.entries.map((e) => '${Uri.encodeQueryComponent(e.key)}=${Uri.encodeQueryComponent(e.value)}' ).join('&'); p = '$p${path.contains('?') ? '&' : '?'}$encoded'; } return requestJson('GET', p, null); } /// Walk the redirect chain manually so Authorization can be dropped /// on cross-origin hops. Caps at 5 hops; mirrors RFC 7231 method /// rewrite semantics. Future<_Response> _sendFollowingRedirects( String method, String urlIn, dynamic body) async { var url = urlIn; var currentMethod = method; dynamic currentBody = body; var stripAuth = false; for (var hop = 0; hop < 5; hop++) { final uri = Uri.parse(url); final req = await _http.openUrl(currentMethod, uri).timeout(_defaultTimeout); req.followRedirects = false; req.headers.set('Accept', 'application/json'); req.headers.set('User-Agent', _userAgent()); req.headers.set('X-Client-Channel', 'client_$language'); req.headers.set('X-Client-Version', clientVersion); req.headers.set('X-Analytics-Device-Id', _deviceId); req.headers.set('X-Analytics-Session-Id', _sessionId); if (!stripAuth && _token.isNotEmpty) { req.headers.set('Authorization', 'Bearer $_token'); } if (currentBody != null && currentMethod != 'GET' && currentMethod != 'HEAD') { req.headers.set('Content-Type', 'application/json'); final encoded = utf8.encode(json.encode(currentBody)); req.contentLength = encoded.length; req.add(encoded); } final resp = await req.close().timeout(_defaultTimeout); final raw = await resp.transform(utf8.decoder).join(); final hmap = {}; resp.headers.forEach((k, v) { hmap[k.toLowerCase()] = v.join(','); }); final status = resp.statusCode; if (status < 300 || status >= 400 || status == 304) { return _Response(status, hmap, raw); } final loc = hmap['location']; if (loc == null || loc.isEmpty) return _Response(status, hmap, raw); Uri nextUri; try { nextUri = uri.resolve(loc); } catch (_) { return _Response(status, hmap, raw); } if (nextUri.origin != uri.origin) stripAuth = true; if (status == 303 || ((status == 301 || status == 302) && currentMethod != 'GET' && currentMethod != 'HEAD')) { currentMethod = 'GET'; currentBody = null; } url = nextUri.toString(); } return _Response(0, const {}, ''); } // ── Analytics ────────────────────────────────────────────────────── void _emitCallEvent(String method, String path, int status, bool ok) { final includeEnv = !_metaSentOnce; _metaSentOnce = true; Future(() async { try { final meta = { 'channel': 'client_$language', 'client_version': clientVersion, 'module_name': moduleName, 'language': language, 'os': Platform.operatingSystem, 'dart_version': Platform.version, }; if (includeEnv) meta['env'] = _fingerprint(); final pathBase = path.split('?').first; final evt = { 'type': 'client.call', 'ts_client': DateTime.now().millisecondsSinceEpoch ~/ 1000, 'meta': { 'method': method.toUpperCase(), 'path': pathBase.length > 128 ? pathBase.substring(0, 128) : pathBase, 'status': status, 'ok': ok, }, }; final payload = json.encode({ 'device_id': _deviceId, 'session_id': _sessionId, 'events': [evt], 'meta': meta, }); final client = HttpClient(); client.connectionTimeout = const Duration(seconds: 2); try { final uri = Uri.parse('$_baseUrl/xapi2/analytics/track'); final req = await client.postUrl(uri).timeout(const Duration(seconds: 4)); req.headers.set('Content-Type', 'application/json'); req.headers.set('User-Agent', _userAgent()); final encoded = utf8.encode(payload); req.contentLength = encoded.length; req.add(encoded); final resp = await req.close().timeout(const Duration(seconds: 4)); await resp.drain(); } finally { client.close(force: true); } } catch (_) { /* fire-and-forget */ } }); } // ── Auto-update ──────────────────────────────────────────────────── void _maybeAutoupdate() { if (_autoupdateAttempted) return; _autoupdateAttempted = true; if (!_autoupdateEnabled()) return; Future(() async { try { final d = _stateDir(); if (d == null) return; final stamp = File('$d/update_check.json'); if (stamp.existsSync()) { try { final blob = json.decode(stamp.readAsStringSync()) as Map; final last = blob['checked_at']; if (last is num && (DateTime.now().millisecondsSinceEpoch ~/ 1000) - last.toInt() < 86400) { return; } } catch (_) {} } try { stamp.writeAsStringSync(json.encode({'checked_at': DateTime.now().millisecondsSinceEpoch ~/ 1000})); } catch (_) {} // Source replacement is intentionally a no-op in Dart - users // typically ship AOT-compiled artefacts (Flutter apps, dart // compile exe), so the .dart file on disk is just a record of // the version they vendored. Surface the new version through // the next build. } catch (_) { /* best-effort */ } }); } /// List `board` rows. Future?> boardList({ListOpts? opts}) => requestList('/xapi2/data/board', opts); /// Fetch one `board` row by id. Future?> boardGet(String id) => requestJson('GET', '/xapi2/data/board/' + id, null); /// Create a new `board` row. Future?> boardCreate(Map data) => requestJson('POST', '/xapi2/data/board', data); /// Patch a `board` row. Future?> boardUpdate(String id, Map data) => requestJson('PATCH', '/xapi2/data/board/' + id, data); /// Delete a `board` row. Future boardDelete(String id) async { await requestJson('DELETE', '/xapi2/data/board/' + id, null); return true; } /// List `card` rows. Future?> cardList({ListOpts? opts}) => requestList('/xapi2/data/card', opts); /// Fetch one `card` row by id. Future?> cardGet(String id) => requestJson('GET', '/xapi2/data/card/' + id, null); /// Create a new `card` row. Future?> cardCreate(Map data) => requestJson('POST', '/xapi2/data/card', data); /// Patch a `card` row. Future?> cardUpdate(String id, Map data) => requestJson('PATCH', '/xapi2/data/card/' + id, data); /// Delete a `card` row. Future cardDelete(String id) async { await requestJson('DELETE', '/xapi2/data/card/' + id, null); return true; } } class _Response { final int status; final Map headers; final String body; const _Response(this.status, this.headers, this.body); }