Scroll: the Flutter operator console for the DBBASIC Object Server, for people building alongside AI agents.

0 downloads

dbbasic-scroll/lib/api.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-scroll.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-scroll.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-scroll.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

quellhorst Extension fields + schema conflict field names e8a817f 4 months, 1 week ago History
api.dart · 54.5 KB · 1765 lines
1import 'dart:convert';
2import 'package:flutter/foundation.dart';
3import 'package:http/http.dart' as http;
4import 'package:shared_preferences/shared_preferences.dart';
5
6enum _AuthMode { none, objectServer, platform }
7
8/// Scroll connects to two services:
9/// 1. Object Server (required) — Python objects, execution, state, clustering
10/// 2. Platform API (optional) — askrobots.com collections (contacts, tasks, etc.)
11class ScrollAPI {
12 String? _objectServerUrl; // e.g. https://object.example.com
13 String? _platformUrl; // e.g. https://askrobots.com
14 String? _token;
15 final http.Client _client = http.Client();
16
17 static final ScrollAPI _instance = ScrollAPI._();
18 factory ScrollAPI() => _instance;
19 ScrollAPI._();
20
21 String? get objectServerUrl => _objectServerUrl;
22 String? get platformUrl => _platformUrl;
23 bool get isConnected => _objectServerUrl != null && _token != null;
24 bool get hasPlatform => _platformUrl != null;
25
26 /// Token for WebView JS injection only (dev helper — don't expose elsewhere)
27 String get tokenForWebView => _token ?? '';
28
29 /// Websocket endpoint for realtime push (/ws), or null when not
30 /// connected. http(s) → ws(s), trailing slash trimmed.
31 String? get realtimeUrl {
32 final base = _objectServerUrl;
33 if (base == null || _token == null) return null;
34 final trimmed = base.endsWith('/')
35 ? base.substring(0, base.length - 1)
36 : base;
37 return '${trimmed.replaceFirst(RegExp(r'^http'), 'ws')}/ws';
38 }
39
40 /// Auth headers for the realtime websocket handshake.
41 Map<String, dynamic> get realtimeHeaders =>
42 _token == null ? const {} : {'Authorization': 'Bearer $_token'};
43
44 /// Fires (once per connection) when the object server rejects the stored
45 /// credential with a 401 — typically an expired session token. The shell
46 /// listens and prompts the operator to sign in again.
47 final ValueNotifier<bool> authRejected = ValueNotifier(false);
48
49 void _noteAuthResult(int statusCode, _AuthMode authMode) {
50 if (statusCode == 401 &&
51 authMode == _AuthMode.objectServer &&
52 isConnected) {
53 authRejected.value = true;
54 }
55 }
56
57 // --- Connection ---
58
59 Future<void> loadSavedConnection() async {
60 final prefs = await SharedPreferences.getInstance();
61 _objectServerUrl = prefs.getString('object_server_url');
62 _platformUrl = prefs.getString('platform_url');
63 _token = prefs.getString('server_token');
64 _sessionUserId = prefs.getString('session_user_id');
65 }
66
67 Future<bool> connect({
68 required String objectServerUrl,
69 required String token,
70 String? platformUrl,
71 }) async {
72 final objUrl = objectServerUrl.endsWith('/')
73 ? objectServerUrl
74 : '$objectServerUrl/';
75 try {
76 // Test object server connection via /health (public, no auth needed)
77 final health = await _getRaw('${objUrl}health');
78 if (health == null) return false;
79
80 _objectServerUrl = objUrl;
81 _token = token;
82 authRejected.value = false;
83
84 // Test platform connection if provided
85 if (platformUrl != null && platformUrl.isNotEmpty) {
86 final platUrl = platformUrl.endsWith('/')
87 ? platformUrl
88 : '$platformUrl/';
89 final platTest = await _getRaw(
90 '${platUrl}api/projects/',
91 token: token,
92 authMode: _AuthMode.platform,
93 );
94 if (platTest != null) {
95 _platformUrl = platUrl;
96 }
97 }
98
99 final prefs = await SharedPreferences.getInstance();
100 await prefs.setString('object_server_url', _objectServerUrl!);
101 await prefs.setString('server_token', _token!);
102 if (_platformUrl != null) {
103 await prefs.setString('platform_url', _platformUrl!);
104 }
105 return true;
106 } catch (_) {}
107 return false;
108 }
109
110 // --- OpenAI key (user-provided, optional) ---
111
112 Future<String?> getOpenAIKey() async {
113 final prefs = await SharedPreferences.getInstance();
114 return prefs.getString('openai_api_key');
115 }
116
117 Future<void> setOpenAIKey(String? key) async {
118 final prefs = await SharedPreferences.getInstance();
119 if (key == null || key.isEmpty) {
120 await prefs.remove('openai_api_key');
121 } else {
122 await prefs.setString('openai_api_key', key);
123 }
124 }
125
126 /// Call OpenAI directly (user's key) to extract structured data from text.
127 /// Returns parsed JSON map or null on failure.
128 Future<Map<String, dynamic>?> aiExtract({
129 required String prompt,
130 required String userText,
131 }) async {
132 final key = await getOpenAIKey();
133 if (key == null || key.isEmpty) return null;
134 try {
135 final response = await _client.post(
136 Uri.parse('https://api.openai.com/v1/chat/completions'),
137 headers: {
138 'Authorization': 'Bearer $key',
139 'Content-Type': 'application/json',
140 },
141 body: jsonEncode({
142 'model': 'gpt-4o-mini',
143 'messages': [
144 {
145 'role': 'system',
146 'content':
147 'You extract structured data. Output ONLY valid JSON, no markdown, no explanations.',
148 },
149 {'role': 'user', 'content': '$prompt\n\nInput text:\n$userText'},
150 ],
151 'response_format': {'type': 'json_object'},
152 }),
153 );
154 if (response.statusCode == 200) {
155 final body = jsonDecode(response.body);
156 final content = body['choices']?[0]?['message']?['content'];
157 if (content is String) {
158 return jsonDecode(content) as Map<String, dynamic>;
159 }
160 }
161 } catch (_) {}
162 return null;
163 }
164
165 /// Generate Python object code from a natural language description.
166 /// Returns {name: suggested_object_name, code: python_source} or null.
167 Future<Map<String, String>?> aiGenerateObject({
168 required String description,
169 required String objectType, // 'view', 'data', 'object', 'trigger'
170 }) async {
171 final key = await getOpenAIKey();
172 if (key == null || key.isEmpty) return null;
173
174 final typeGuide = switch (objectType) {
175 'view' =>
176 'This is a VIEW object — GET(request) should return {"content_type": "text/html; charset=utf-8", "body": "<full html document>"} for interactive UI, or a plain dict for JSON API. HTML can include forms that POST to the same object.',
177 'data' =>
178 'This is a DATA STORE object — GET(request) returns stored data as JSON, POST(request) accepts data to add/update. Use _state_manager.get("items", []) and _state_manager.set("items", new_list).',
179 'trigger' =>
180 'This is a TRIGGER object — GET(request) runs the scheduled work, returns status dict. Called by the cron runner periodically.',
181 _ => 'Generic object — define GET(request) and POST(request) as needed.',
182 };
183
184 final systemPrompt =
185 '''You are generating Python code for the dbbasic Object Server (a live Python runtime).
186
187OBJECT CONVENTIONS:
188- Every object is a single Python file defining uppercase HTTP verb functions at module top level: GET(request), POST(request), PUT(request), DELETE(request). Only define the ones needed.
189- request is a dict carrying the query params / request payload. request["_identity"] is server-controlled: {"user_id", "account_id", "roles", "subscriptions", "auth_method"} — user_id is None for anonymous visitors. Use it for per-user content; it cannot be spoofed.
190- Persistent state: _state_manager.get(key, default) to read, _state_manager.set(key, value) to write. It is an injected global — no import needed. No database needed.
191- Logging: _logger.info("message", key=value) — also an injected global.
192- Return a Python dict. Plain dict → returned as JSON. For an HTML page return {"content_type": "text/html; charset=utf-8", "body": "<!doctype html>..."}.
193- For HTML views, include full <html>...</html> with <style>. Use dark theme (bg #0a0a0a, fg #e0e0e0). Make it functional and clean.
194- Forms POST to the same object URL — no separate routes. Use <form method="POST"> with onsubmit fetch to stay on the page.
195
196$typeGuide
197
198OUTPUT: JSON object with two keys:
199- "name": short snake_case object name (e.g. "expense_tracker", "deals_kanban"). No u_{id}_ prefix - server adds it.
200- "code": complete Python source as a string, starting with GET or POST.
201
202No markdown, no backticks, no explanations. Only JSON.''';
203
204 try {
205 final response = await _client.post(
206 Uri.parse('https://api.openai.com/v1/chat/completions'),
207 headers: {
208 'Authorization': 'Bearer $key',
209 'Content-Type': 'application/json',
210 },
211 body: jsonEncode({
212 'model': 'gpt-4o',
213 'messages': [
214 {'role': 'system', 'content': systemPrompt},
215 {'role': 'user', 'content': description},
216 ],
217 'response_format': {'type': 'json_object'},
218 'temperature': 0.7,
219 }),
220 );
221 if (response.statusCode == 200) {
222 final body = jsonDecode(response.body);
223 final content = body['choices']?[0]?['message']?['content'];
224 if (content is String) {
225 final parsed = jsonDecode(content) as Map<String, dynamic>;
226 final name = parsed['name']?.toString() ?? '';
227 final code = parsed['code']?.toString() ?? '';
228 if (name.isNotEmpty && code.isNotEmpty) {
229 return {'name': name, 'code': code};
230 }
231 }
232 } else {
233 lastError = 'OpenAI HTTP ${response.statusCode}: ${response.body}';
234 }
235 } catch (e) {
236 lastError = 'AI error: $e';
237 }
238 return null;
239 }
240
241 /// Password login — POST /identity/session with no Authorization header.
242 /// Returns {status, body} (or {error}) so callers can show the raw result.
243 Future<Map<String, dynamic>> loginWithPassword({
244 required String objectServerUrl,
245 String? email,
246 String? userId,
247 required String password,
248 String? label,
249 int? ttlSeconds,
250 }) async {
251 final base = objectServerUrl.endsWith('/')
252 ? objectServerUrl
253 : '$objectServerUrl/';
254 try {
255 final response = await _client.post(
256 Uri.parse('${base}identity/session'),
257 headers: {'Content-Type': 'application/json'},
258 body: jsonEncode({
259 if (email != null && email.trim().isNotEmpty) 'email': email.trim(),
260 if (userId != null && userId.trim().isNotEmpty)
261 'user_id': userId.trim(),
262 'password': password,
263 if (label != null && label.trim().isNotEmpty) 'label': label,
264 if (ttlSeconds != null) 'ttl_seconds': ttlSeconds,
265 }),
266 );
267 return {
268 'status': response.statusCode,
269 'body': _decodeResponseBody(response.body),
270 };
271 } catch (e) {
272 return {'error': e.toString()};
273 }
274 }
275
276 /// Extract the session bearer token from a loginWithPassword result.
277 String? sessionTokenFromLogin(Map<String, dynamic> result) {
278 dynamic body = result['body'];
279 for (var depth = 0; depth < 2 && body is Map; depth++) {
280 for (final key in const [
281 'token',
282 'session_token',
283 'access_token',
284 'bearer_token',
285 ]) {
286 final value = body[key];
287 if (value is String && value.isNotEmpty) return value;
288 }
289 body = body['session'];
290 }
291 return null;
292 }
293
294 /// Extract the user id from a loginWithPassword result.
295 String? sessionUserIdFromLogin(Map<String, dynamic> result) {
296 dynamic body = result['body'];
297 for (var depth = 0; depth < 2 && body is Map; depth++) {
298 final value = body['user_id'];
299 if (value is String && value.isNotEmpty) return value;
300 body = body['session'];
301 }
302 return null;
303 }
304
305 String? _sessionUserId;
306
307 /// The user id behind the current session token, when known (password
308 /// logins set it; deployment-token connections have none). Used to
309 /// prefill owner_id on record creates for owner-scoped app collections.
310 String? get sessionUserId => _sessionUserId;
311
312 Future<void> setSessionUser(String? userId) async {
313 _sessionUserId = (userId == null || userId.isEmpty) ? null : userId;
314 final prefs = await SharedPreferences.getInstance();
315 if (_sessionUserId == null) {
316 await prefs.remove('session_user_id');
317 } else {
318 await prefs.setString('session_user_id', _sessionUserId!);
319 }
320 }
321
322 // --- AI provider service keys (write-only) + AI chat ---
323
324 /// Store an AI provider key for a user (self-service with the user's own
325 /// session). The server never returns key material — GET lists which
326 /// services have keys, nothing more.
327 Future<Map<String, dynamic>> setServiceKey(
328 String userId, {
329 required String service,
330 required String key,
331 }) {
332 return rawRequest(
333 'PUT',
334 _objUrl('identity/users/${_pathSegment(userId)}/service-keys'),
335 data: {'service': service, 'key': key},
336 );
337 }
338
339 Future<Map<String, dynamic>> listServiceKeys(String userId) {
340 return rawRequest(
341 'GET',
342 _objUrl('identity/users/${_pathSegment(userId)}/service-keys'),
343 );
344 }
345
346 Future<Map<String, dynamic>> removeServiceKey(String userId, String service) {
347 return rawRequest(
348 'DELETE',
349 _objUrl(
350 'identity/users/${_pathSegment(userId)}/service-keys/'
351 '${_pathSegment(service)}',
352 ),
353 );
354 }
355
356 /// One AI conversation turn using the caller's stored provider key.
357 /// Tool calls dispatch with the caller's credentials — the AI can do
358 /// exactly what the session could, permission-checked and audited.
359 /// [history] is prior turns as [{role, content}] (server caps at 40).
360 Future<Map<String, dynamic>> aiChat({
361 required String message,
362 String? model,
363 List<String>? tools,
364 int? maxRounds,
365 List<Map<String, String>>? history,
366 }) {
367 return rawRequest(
368 'POST',
369 _objUrl('api/ai/chat'),
370 data: {
371 'message': message,
372 if (model != null && model.isNotEmpty) 'model': model,
373 if (tools != null) 'tools': tools,
374 if (maxRounds != null) 'max_rounds': maxRounds,
375 if (history != null && history.isNotEmpty) 'history': history,
376 },
377 );
378 }
379
380 /// Ops event stream: object execution failures + auth activity.
381 /// kind: execution_error | auth; event: e.g. login_failed.
382 Future<Map<String, dynamic>> listAdminOpsEvents({
383 String? kind,
384 String? event,
385 String? identifier,
386 int limit = 200,
387 }) {
388 var query = 'limit=$limit';
389 if (kind != null && kind.isNotEmpty) {
390 query += '&kind=${Uri.encodeQueryComponent(kind)}';
391 }
392 if (event != null && event.isNotEmpty) {
393 query += '&event=${Uri.encodeQueryComponent(event)}';
394 }
395 if (identifier != null && identifier.isNotEmpty) {
396 query += '&identifier=${Uri.encodeQueryComponent(identifier)}';
397 }
398 return rawRequest('GET', _objUrl('admin/ops?$query'));
399 }
400
401 // --- Caller-scoped record routes (/collections/*) ---
402 // Unlike the admin routes these run inside the permission engine: rows
403 // arrive pre-filtered for the session's user, which is what shell
404 // history/preferences want.
405
406 Future<Map<String, dynamic>> listUserCollectionRecords(
407 String collection, {
408 int limit = 100,
409 }) {
410 return rawRequest(
411 'GET',
412 _objUrl('collections/${_pathSegment(collection)}/records?limit=$limit'),
413 );
414 }
415
416 Future<Map<String, dynamic>> getUserCollectionRecord(
417 String collection,
418 String recordId,
419 ) {
420 return rawRequest(
421 'GET',
422 _objUrl(
423 'collections/${_pathSegment(collection)}/records/'
424 '${_pathSegment(recordId)}',
425 ),
426 );
427 }
428
429 Future<Map<String, dynamic>> putUserCollectionRecord(
430 String collection,
431 String recordId,
432 Map<String, dynamic> changes,
433 ) {
434 return rawRequest(
435 'PUT',
436 _objUrl(
437 'collections/${_pathSegment(collection)}/records/'
438 '${_pathSegment(recordId)}',
439 ),
440 data: changes,
441 );
442 }
443
444 Future<Map<String, dynamic>> createUserCollectionRecord(
445 String collection,
446 Map<String, dynamic> record,
447 ) {
448 return rawRequest(
449 'POST',
450 _objUrl('collections/${_pathSegment(collection)}/records'),
451 data: record,
452 );
453 }
454
455 Future<void> disconnect() async {
456 _objectServerUrl = null;
457 _platformUrl = null;
458 _token = null;
459 _sessionUserId = null;
460 authRejected.value = false;
461 final prefs = await SharedPreferences.getInstance();
462 await prefs.remove('object_server_url');
463 await prefs.remove('platform_url');
464 await prefs.remove('server_token');
465 await prefs.remove('session_user_id');
466 }
467
468 // --- HTTP helpers ---
469
470 Map<String, String> _headers({
471 String? token,
472 _AuthMode authMode = _AuthMode.objectServer,
473 }) {
474 final headers = {'Content-Type': 'application/json'};
475 final resolvedToken = token ?? _token;
476 if (resolvedToken == null ||
477 resolvedToken.isEmpty ||
478 authMode == _AuthMode.none) {
479 return headers;
480 }
481 final prefix = authMode == _AuthMode.platform ? 'Token' : 'Bearer';
482 headers['Authorization'] = '$prefix $resolvedToken';
483 return headers;
484 }
485
486 // Public raw request helpers for API Explorer
487 Future<dynamic> rawGet(String url, {bool platformAuth = false}) => _getRaw(
488 url,
489 authMode: platformAuth ? _AuthMode.platform : _AuthMode.objectServer,
490 );
491
492 Future<Map<String, dynamic>> rawRequest(
493 String method,
494 String url, {
495 Map<String, dynamic>? data,
496 bool platformAuth = false,
497 }) async {
498 final authMode = platformAuth ? _AuthMode.platform : _AuthMode.objectServer;
499 try {
500 final uri = Uri.parse(url);
501 final headers = _headers(authMode: authMode);
502 final response = switch (method.toUpperCase()) {
503 'POST' => await _client.post(
504 uri,
505 headers: headers,
506 body: jsonEncode(data ?? {}),
507 ),
508 'PUT' => await _client.put(
509 uri,
510 headers: headers,
511 body: jsonEncode(data ?? {}),
512 ),
513 'PATCH' => await _client.patch(
514 uri,
515 headers: headers,
516 body: jsonEncode(data ?? {}),
517 ),
518 'DELETE' => await _client.delete(uri, headers: headers),
519 _ => await _client.get(uri, headers: headers),
520 };
521 _noteAuthResult(response.statusCode, authMode);
522 return {
523 'status': response.statusCode,
524 'body': _decodeResponseBody(response.body),
525 };
526 } catch (e) {
527 return {'error': e.toString()};
528 }
529 }
530
531 dynamic _decodeResponseBody(String body) {
532 if (body.isEmpty) return null;
533 try {
534 return jsonDecode(body);
535 } catch (_) {
536 return body;
537 }
538 }
539
540 Future<dynamic> _getRaw(
541 String url, {
542 String? token,
543 _AuthMode authMode = _AuthMode.objectServer,
544 }) async {
545 try {
546 final response = await _client.get(
547 Uri.parse(url),
548 headers: _headers(token: token, authMode: authMode),
549 );
550 if (response.statusCode == 200) {
551 lastError = null;
552 return _decodeResponseBody(response.body);
553 }
554 _noteAuthResult(response.statusCode, authMode);
555 lastError = 'HTTP ${response.statusCode}: ${response.body}';
556 } catch (e) {
557 lastError = 'Error: $e';
558 }
559 return null;
560 }
561
562 // Last error from a POST/PUT/PATCH, for debugging
563 String? lastError;
564
565 Future<dynamic> _postRaw(
566 String url,
567 Map<String, dynamic> data, {
568 _AuthMode authMode = _AuthMode.objectServer,
569 }) async {
570 try {
571 final response = await _client.post(
572 Uri.parse(url),
573 headers: _headers(authMode: authMode),
574 body: jsonEncode(data),
575 );
576 if (response.statusCode == 200 || response.statusCode == 201) {
577 lastError = null;
578 return _decodeResponseBody(response.body);
579 }
580 _noteAuthResult(response.statusCode, authMode);
581 lastError = 'HTTP ${response.statusCode}: ${response.body}';
582 } catch (e) {
583 lastError = 'Error: $e';
584 }
585 return null;
586 }
587
588 Future<dynamic> _putRaw(
589 String url,
590 Map<String, dynamic> data, {
591 _AuthMode authMode = _AuthMode.objectServer,
592 }) async {
593 try {
594 final response = await _client.put(
595 Uri.parse(url),
596 headers: _headers(authMode: authMode),
597 body: jsonEncode(data),
598 );
599 if (response.statusCode == 200) {
600 return _decodeResponseBody(response.body);
601 }
602 _noteAuthResult(response.statusCode, authMode);
603 } catch (_) {}
604 return null;
605 }
606
607 Future<bool> _deleteRaw(
608 String url, {
609 _AuthMode authMode = _AuthMode.objectServer,
610 }) async {
611 try {
612 final response = await _client.delete(
613 Uri.parse(url),
614 headers: _headers(authMode: authMode),
615 );
616 _noteAuthResult(response.statusCode, authMode);
617 return response.statusCode == 200 || response.statusCode == 204;
618 } catch (_) {}
619 return false;
620 }
621
622 String _objUrl(String path) => '${_objectServerUrl}$path';
623 String _platUrl(String path) => '${_platformUrl}api/$path';
624
625 // =====================================================================
626 // OBJECT SERVER API (core)
627 // =====================================================================
628
629 // --- Health & Cluster ---
630
631 /// Get health from a specific station URL (for station detail view)
632 Future<Map<String, dynamic>?> getStationHealth(
633 String stationUrl, {
634 bool metrics = false,
635 }) async {
636 final baseUrl = stationUrl.endsWith('/') ? stationUrl : '$stationUrl/';
637 final url = metrics
638 ? '${baseUrl}health?metrics=true&format=json'
639 : '${baseUrl}health?format=json';
640 final result = await _getRaw(url);
641 return result is Map<String, dynamic> ? result : null;
642 }
643
644 Future<Map<String, dynamic>?> getHealth({
645 bool metrics = false,
646 bool history = false,
647 int historyLimit = 360,
648 }) async {
649 var url = metrics
650 ? 'health?metrics=true&format=json'
651 : 'health?format=json';
652 if (history) url += '&history=true&history_limit=$historyLimit';
653 final result = await _getRaw(_objUrl(url));
654 return result is Map<String, dynamic> ? result : null;
655 }
656
657 // --- Theme / design system (/style is a themeable object) ---
658
659 /// GET /style?info=true (public) → {active, available, previews, tokens}.
660 /// `previews` maps each theme to a small swatch (bg/panel/accent/text).
661 Future<Map<String, dynamic>?> getStyleInfo() async {
662 final result = await _getRaw(_objUrl('style?info=true'));
663 return result is Map<String, dynamic> ? result : null;
664 }
665
666 /// POST /style {theme} — switch the whole instance's theme live.
667 /// Admin-gated server-side (the object self-gates on identity; non-admin
668 /// sessions get 403).
669 Future<Map<String, dynamic>> setStyleTheme(String theme) {
670 return rawRequest('POST', _objUrl('style'), data: {'theme': theme});
671 }
672
673 Future<Map<String, dynamic>?> getAdminStatus() async {
674 final result = await _getRaw(_objUrl('admin/status'));
675 return result is Map<String, dynamic> ? result : null;
676 }
677
678 /// GET /packages/{id} (admin-gated) → {status, package, provenance}.
679 /// The provenance block reports install-once baseline state: whether the
680 /// package is installed, at what version, and per-artifact pristine/
681 /// customized/removed vs the shipped baseline.
682 Future<Map<String, dynamic>?> getPackage(String id) async {
683 final result = await _getRaw(_objUrl('packages/${_pathSegment(id)}'));
684 return result is Map<String, dynamic> ? result : null;
685 }
686
687 /// In-place package upgrade: POST /packages/{id}/install {allow_replace:true}.
688 /// Objects/schema/permissions update, records preserved, conflicts parked
689 /// as pending-reconcile records rather than overwritten.
690 Future<Map<String, dynamic>> installPackage(
691 String id, {
692 bool allowReplace = true,
693 }) {
694 return rawRequest(
695 'POST',
696 _objUrl('packages/${_pathSegment(id)}/install'),
697 data: {'allow_replace': allowReplace},
698 );
699 }
700
701 // --- Reconcile inbox (parked upgrade conflicts) ---
702
703 /// GET /admin/reconciles → {status, count, reconciles:[...]}.
704 Future<Map<String, dynamic>> listReconciles({
705 String? status,
706 String? package,
707 }) {
708 final params = <String>[
709 if (status != null && status.isNotEmpty)
710 'status=${Uri.encodeQueryComponent(status)}',
711 if (package != null && package.isNotEmpty)
712 'package=${Uri.encodeQueryComponent(package)}',
713 ];
714 final query = params.isEmpty ? '' : '?${params.join('&')}';
715 return rawRequest('GET', _objUrl('admin/reconciles$query'));
716 }
717
718 /// POST /admin/reconciles/{id}/resolve {choice: keep_mine|take_theirs}.
719 Future<Map<String, dynamic>> resolveReconcile(String id, String choice) {
720 return rawRequest(
721 'POST',
722 _objUrl('admin/reconciles/${_pathSegment(id)}/resolve'),
723 data: {'choice': choice},
724 );
725 }
726
727 // --- Backups (admin-gated; a backup contains ALL data, never public) ---
728
729 /// GET /admin/backups → {backups: [{id, created_at, size, kind, scope}],
730 /// count, schedule} newest-first.
731 Future<Map<String, dynamic>> listBackups() {
732 return rawRequest('GET', _objUrl('admin/backups'));
733 }
734
735 /// POST /admin/backups → 201 {backup: {...}} — creates a full-runtime
736 /// backup now. Synchronous; returns the finished record.
737 Future<Map<String, dynamic>> createBackup() {
738 return rawRequest('POST', _objUrl('admin/backups'));
739 }
740
741 /// GET /admin/backups/{id}/download → the archive bytes. Returns the raw
742 /// bytes plus the server-suggested filename, or null on failure.
743 Future<({List<int> bytes, String filename})?> downloadBackup(
744 String id,
745 ) async {
746 final uri = Uri.parse(
747 _objUrl('admin/backups/${_pathSegment(id)}/download'),
748 );
749 try {
750 final response = await _client
751 .get(uri, headers: _headers())
752 .timeout(const Duration(seconds: 90));
753 _noteAuthResult(response.statusCode, _AuthMode.objectServer);
754 if (response.statusCode >= 200 && response.statusCode < 300) {
755 var filename = 'backup-$id.tar.gz';
756 final disposition = response.headers['content-disposition'];
757 if (disposition != null) {
758 final match = RegExp(
759 'filename\\*?=(?:"([^"]+)"|([^;]+))',
760 ).firstMatch(disposition);
761 final captured = (match?.group(1) ?? match?.group(2))?.trim();
762 if (captured != null && captured.isNotEmpty) filename = captured;
763 }
764 return (bytes: response.bodyBytes, filename: filename);
765 }
766 lastError = 'HTTP ${response.statusCode}';
767 } catch (e) {
768 lastError = 'Error: $e';
769 }
770 return null;
771 }
772
773 Future<Map<String, dynamic>?> getDaemonStatus() async {
774 final result = await _getRaw(_objUrl('daemon/status'));
775 return result is Map<String, dynamic> ? result : null;
776 }
777
778 Future<Map<String, dynamic>?> getDaemonSchedulerTasks() async {
779 final result = await _getRaw(_objUrl('daemon/scheduler/tasks'));
780 return result is Map<String, dynamic> ? result : null;
781 }
782
783 Future<Map<String, dynamic>?> getDaemonQueueMessages() async {
784 final result = await _getRaw(_objUrl('daemon/queue/messages'));
785 return result is Map<String, dynamic> ? result : null;
786 }
787
788 Future<Map<String, dynamic>?> getEventDeliveries({int limit = 100}) async {
789 final result = await _getRaw(_objUrl('events/deliveries?limit=$limit'));
790 return result is Map<String, dynamic> ? result : null;
791 }
792
793 Future<Map<String, dynamic>?> getPermissionsStatus() async {
794 final result = await _getRaw(_objUrl('permissions/status'));
795 return result is Map<String, dynamic> ? result : null;
796 }
797
798 Future<Map<String, dynamic>?> getPermissionsPolicy() async {
799 final result = await _getRaw(_objUrl('permissions/policy'));
800 return result is Map<String, dynamic> ? result : null;
801 }
802
803 Future<Map<String, dynamic>?> listAdminChanges({
804 int limit = 100,
805 int offset = 0,
806 String? kind,
807 String? objectId,
808 String? collection,
809 String? recordId,
810 String? packageId,
811 String? file,
812 }) async {
813 final params = <String, String>{'limit': '$limit', 'offset': '$offset'};
814 void addParam(String key, String? value) {
815 final trimmed = value?.trim();
816 if (trimmed != null && trimmed.isNotEmpty) params[key] = trimmed;
817 }
818
819 addParam('kind', kind);
820 addParam('object_id', objectId);
821 addParam('collection', collection);
822 addParam('record_id', recordId);
823 addParam('package_id', packageId);
824 addParam('file', file);
825
826 final query = Uri(queryParameters: params).query;
827 final result = await _getRaw(_objUrl('admin/changes?$query'));
828 return _asStringMap(result);
829 }
830
831 Future<List<dynamic>> listAdminIdentityAccounts() async {
832 final result = await _getRaw(_objUrl('admin/identity/accounts'));
833 return _listFromObjectInspection(result, const [
834 'accounts',
835 'items',
836 'results',
837 'records',
838 'rows',
839 ]);
840 }
841
842 Future<Map<String, dynamic>?> getAdminIdentityAccount(
843 String accountId,
844 ) async {
845 final id = _pathSegment(accountId);
846 final result = await _getRaw(_objUrl('admin/identity/accounts/$id'));
847 return _mapFromObjectInspection(
848 result,
849 nestedKeys: const ['account', 'identity', 'detail'],
850 );
851 }
852
853 Future<List<dynamic>> listAdminIdentityUsers({String? accountId}) async {
854 final query = accountId == null || accountId.isEmpty
855 ? ''
856 : '?account_id=${Uri.encodeQueryComponent(accountId)}';
857 final result = await _getRaw(_objUrl('admin/identity/users$query'));
858 return _listFromObjectInspection(result, const [
859 'users',
860 'items',
861 'results',
862 'records',
863 'rows',
864 ]);
865 }
866
867 Future<Map<String, dynamic>?> getAdminIdentityUser(String userId) async {
868 final id = _pathSegment(userId);
869 final result = await _getRaw(_objUrl('admin/identity/users/$id'));
870 return _mapFromObjectInspection(
871 result,
872 nestedKeys: const ['user', 'identity', 'detail'],
873 );
874 }
875
876 Future<Map<String, dynamic>> setAdminUserPassword(
877 String userId,
878 String password,
879 ) {
880 final id = _pathSegment(userId);
881 return rawRequest(
882 'POST',
883 _objUrl('admin/identity/users/$id/password'),
884 data: {'password': password},
885 );
886 }
887
888 Future<Map<String, dynamic>> removeAdminUserPassword(String userId) {
889 final id = _pathSegment(userId);
890 return rawRequest('DELETE', _objUrl('admin/identity/users/$id/password'));
891 }
892
893 Future<List<dynamic>> listAdminIdentitySessions() async {
894 final result = await _getRaw(_objUrl('admin/identity/sessions'));
895 return _listFromObjectInspection(result, const [
896 'sessions',
897 'items',
898 'results',
899 'records',
900 'rows',
901 ]);
902 }
903
904 Future<Map<String, dynamic>?> getAdminIdentitySession(
905 String sessionId,
906 ) async {
907 final id = _pathSegment(sessionId);
908 final result = await _getRaw(_objUrl('admin/identity/sessions/$id'));
909 return _mapFromObjectInspection(
910 result,
911 nestedKeys: const ['session', 'identity', 'detail'],
912 );
913 }
914
915 Future<Map<String, dynamic>?> getClusterInfo() async {
916 final result = await _getRaw(_objUrl('cluster/info'));
917 return result is Map<String, dynamic> ? result : null;
918 }
919
920 Future<dynamic> getClusterStations() async {
921 return _getRaw(_objUrl('cluster/stations?format=json'));
922 }
923
924 // --- Objects ---
925
926 Future<dynamic> _getFirstObjectInspection(List<String> paths) async {
927 for (final path in paths) {
928 final result = await _getRaw(_objUrl(path));
929 if (result != null) return result;
930 }
931 return null;
932 }
933
934 String _pathSegment(String value) => Uri.encodeComponent(value);
935
936 Map<String, dynamic>? _asStringMap(dynamic value) {
937 if (value is Map<String, dynamic>) return value;
938 if (value is Map) {
939 return value.map((key, item) => MapEntry(key.toString(), item));
940 }
941 return null;
942 }
943
944 List<dynamic> _listFromObjectInspection(dynamic result, List<String> keys) {
945 if (result is List) return result;
946 final map = _asStringMap(result);
947 if (map == null) return const [];
948 for (final key in keys) {
949 final value = map[key];
950 if (value is List) return value;
951 }
952 return const [];
953 }
954
955 Map<String, dynamic>? _mapFromObjectInspection(
956 dynamic result, {
957 List<String> nestedKeys = const [],
958 }) {
959 final map = _asStringMap(result);
960 if (map == null) return null;
961 for (final key in nestedKeys) {
962 final nested = _asStringMap(map[key]);
963 if (nested != null) return nested;
964 }
965 return map;
966 }
967
968 String? _sourceFromObjectInspection(dynamic result) {
969 if (result is String) return result;
970 final map = _asStringMap(result);
971 if (map == null) return null;
972 for (final key in const ['source', 'code', 'content', 'text']) {
973 final value = map[key];
974 if (value is String) return value;
975 }
976 final object = _asStringMap(map['object']);
977 if (object != null) {
978 for (final key in const ['source', 'code', 'content', 'text']) {
979 final value = object[key];
980 if (value is String) return value;
981 }
982 }
983 return const JsonEncoder.withIndent(' ').convert(map);
984 }
985
986 Future<List<dynamic>> listAdminObjects() async {
987 final result = await _getFirstObjectInspection([
988 'admin/objects',
989 'admin/objects?format=json',
990 ]);
991 return _listFromObjectInspection(result, const [
992 'objects',
993 'items',
994 'results',
995 'records',
996 'rows',
997 ]);
998 }
999
1000 Future<Map<String, dynamic>?> getAdminObjectMetadata(String objectId) async {
1001 final id = _pathSegment(objectId);
1002 final result = await _getFirstObjectInspection([
1003 'admin/objects/$id',
1004 'admin/objects/$id?metadata=true',
1005 ]);
1006 return _mapFromObjectInspection(
1007 result,
1008 nestedKeys: const ['object', 'metadata', 'status', 'detail'],
1009 );
1010 }
1011
1012 Future<String?> getAdminObjectSource(String objectId) async {
1013 final id = _pathSegment(objectId);
1014 final result = await _getRaw(
1015 _objUrl('admin/objects/$id?source=true&format=json'),
1016 );
1017 return _sourceFromObjectInspection(result);
1018 }
1019
1020 Future<Map<String, dynamic>?> getAdminObjectState(String objectId) async {
1021 final id = _pathSegment(objectId);
1022 final result = await _getRaw(_objUrl('admin/objects/$id?state=true'));
1023 return _mapFromObjectInspection(
1024 result,
1025 nestedKeys: const ['state', 'data'],
1026 );
1027 }
1028
1029 Future<List<dynamic>> getAdminObjectLogs(
1030 String objectId, {
1031 int limit = 100,
1032 }) async {
1033 final id = _pathSegment(objectId);
1034 final result = await _getRaw(
1035 _objUrl('admin/objects/$id?logs=true&limit=$limit'),
1036 );
1037 return _listFromObjectInspection(result, const [
1038 'logs',
1039 'events',
1040 'items',
1041 'results',
1042 'records',
1043 'rows',
1044 ]);
1045 }
1046
1047 Future<List<dynamic>> getAdminObjectVersions(
1048 String objectId, {
1049 int limit = 10,
1050 }) async {
1051 final id = _pathSegment(objectId);
1052 final result = await _getRaw(
1053 _objUrl('admin/objects/$id?versions=true&limit=$limit'),
1054 );
1055 return _listFromObjectInspection(result, const [
1056 'versions',
1057 'items',
1058 'results',
1059 'records',
1060 'rows',
1061 ]);
1062 }
1063
1064 Future<dynamic> getAdminObjectVersion(String objectId, int version) async {
1065 final id = _pathSegment(objectId);
1066 return _getRaw(_objUrl('admin/objects/$id?version=$version'));
1067 }
1068
1069 Future<List<dynamic>> getAdminObjectSourceChanges(
1070 String objectId, {
1071 int limit = 100,
1072 }) async {
1073 final id = _pathSegment(objectId);
1074 final result = await _getRaw(
1075 _objUrl('admin/objects/$id?source_changes=true&limit=$limit'),
1076 );
1077 return _listFromObjectInspection(result, const [
1078 'source_changes',
1079 'changes',
1080 'events',
1081 'items',
1082 'results',
1083 'records',
1084 'rows',
1085 ]);
1086 }
1087
1088 Future<List<dynamic>> getAdminObjectChanges(
1089 String objectId, {
1090 int limit = 100,
1091 }) async {
1092 final id = _pathSegment(objectId);
1093 final result = await _getRaw(
1094 _objUrl('admin/objects/$id?changes=true&limit=$limit'),
1095 );
1096 return _listFromObjectInspection(result, const [
1097 'changes',
1098 'source_changes',
1099 'events',
1100 'items',
1101 'results',
1102 'records',
1103 'rows',
1104 ]);
1105 }
1106
1107 Future<List<dynamic>> getAdminObjectFiles(String objectId) async {
1108 final id = _pathSegment(objectId);
1109 final result = await _getRaw(_objUrl('admin/objects/$id?files=true'));
1110 return _listFromObjectInspection(result, const [
1111 'files',
1112 'items',
1113 'results',
1114 'records',
1115 'rows',
1116 ]);
1117 }
1118
1119 Future<Map<String, dynamic>> getAdminObjectFileContent(
1120 String objectId,
1121 String fileName,
1122 ) {
1123 final id = _pathSegment(objectId);
1124 final file = Uri.encodeQueryComponent(fileName);
1125 return rawRequest('GET', _objUrl('admin/objects/$id?file=$file'));
1126 }
1127
1128 Future<List<dynamic>> listAdminCollections() async {
1129 final result = await _getRaw(_objUrl('admin/collections'));
1130 return _listFromObjectInspection(result, const [
1131 'collections',
1132 'items',
1133 'results',
1134 'records',
1135 'rows',
1136 ]);
1137 }
1138
1139 Future<Map<String, dynamic>?> getAdminCollection(String collection) async {
1140 final name = _pathSegment(collection);
1141 final result = await _getRaw(_objUrl('admin/collections/$name'));
1142 return _mapFromObjectInspection(
1143 result,
1144 nestedKeys: const ['collection', 'metadata', 'detail'],
1145 );
1146 }
1147
1148 Future<List<dynamic>> listAdminCollectionRecords(
1149 String collection, {
1150 int limit = 100,
1151 }) async {
1152 final name = _pathSegment(collection);
1153 final result = await _getRaw(
1154 _objUrl('admin/collections/$name/records?limit=$limit'),
1155 );
1156 return _listFromObjectInspection(result, const [
1157 'records',
1158 'items',
1159 'results',
1160 'rows',
1161 ]);
1162 }
1163
1164 /// Global search across searchable collections (schemas with a `search`
1165 /// key opt in). Permission-aware server-side: denied collections are
1166 /// skipped, row filters and field redaction apply before matching.
1167 /// Returns {status, query, limit, results: {collection: [records]},
1168 /// total_count, warnings?} or null on failure.
1169 Future<Map<String, dynamic>?> globalSearch(
1170 String query, {
1171 int limit = 10,
1172 List<String>? collections,
1173 }) async {
1174 var url = 'api/search?q=${Uri.encodeQueryComponent(query)}&limit=$limit';
1175 if (collections != null && collections.isNotEmpty) {
1176 url += '&collections=${Uri.encodeQueryComponent(collections.join(","))}';
1177 }
1178 final result = await _getRaw(_objUrl(url));
1179 return result is Map<String, dynamic> ? result : null;
1180 }
1181
1182 Future<Map<String, dynamic>?> getAdminCollectionRecord(
1183 String collection,
1184 String recordId,
1185 ) async {
1186 final name = _pathSegment(collection);
1187 final id = _pathSegment(recordId);
1188 final result = await _getRaw(
1189 _objUrl('admin/collections/$name/records/$id'),
1190 );
1191 return _mapFromObjectInspection(
1192 result,
1193 nestedKeys: const ['record', 'item', 'data', 'detail'],
1194 );
1195 }
1196
1197 Future<List<dynamic>> listAdminCollectionChanges(
1198 String collection, {
1199 int limit = 100,
1200 }) async {
1201 final name = _pathSegment(collection);
1202 final result = await _getRaw(
1203 _objUrl('admin/collections/$name/changes?limit=$limit'),
1204 );
1205 return _listFromObjectInspection(result, const [
1206 'changes',
1207 'events',
1208 'items',
1209 'results',
1210 'records',
1211 'rows',
1212 ]);
1213 }
1214
1215 Future<List<dynamic>> listAdminCollectionRecordChanges(
1216 String collection,
1217 String recordId, {
1218 int limit = 100,
1219 }) async {
1220 final name = _pathSegment(collection);
1221 final id = _pathSegment(recordId);
1222 final result = await _getRaw(
1223 _objUrl('admin/collections/$name/records/$id/changes?limit=$limit'),
1224 );
1225 return _listFromObjectInspection(result, const [
1226 'changes',
1227 'events',
1228 'items',
1229 'results',
1230 'records',
1231 'rows',
1232 ]);
1233 }
1234
1235 Future<Map<String, dynamic>> createAdminCollectionRecord(
1236 String collection,
1237 Map<String, dynamic> record,
1238 ) {
1239 final name = _pathSegment(collection);
1240 return rawRequest(
1241 'POST',
1242 _objUrl('admin/collections/$name/records'),
1243 data: record,
1244 );
1245 }
1246
1247 Future<Map<String, dynamic>> updateAdminCollectionRecord(
1248 String collection,
1249 String recordId,
1250 Map<String, dynamic> record,
1251 ) {
1252 final name = _pathSegment(collection);
1253 final id = _pathSegment(recordId);
1254 return rawRequest(
1255 'PUT',
1256 _objUrl('admin/collections/$name/records/$id'),
1257 data: record,
1258 );
1259 }
1260
1261 Future<Map<String, dynamic>> deleteAdminCollectionRecord(
1262 String collection,
1263 String recordId,
1264 ) {
1265 final name = _pathSegment(collection);
1266 final id = _pathSegment(recordId);
1267 return rawRequest('DELETE', _objUrl('admin/collections/$name/records/$id'));
1268 }
1269
1270 Future<List<dynamic>> listAdminSchemas() async {
1271 final result = await _getRaw(_objUrl('admin/schemas'));
1272 return _listFromObjectInspection(result, const [
1273 'schemas',
1274 'items',
1275 'results',
1276 'records',
1277 'rows',
1278 ]);
1279 }
1280
1281 Future<Map<String, dynamic>?> getAdminSchema(String collection) async {
1282 final name = _pathSegment(collection);
1283 final result = await _getRaw(_objUrl('admin/schemas/$name'));
1284 return _mapFromObjectInspection(
1285 result,
1286 nestedKeys: const ['schema', 'metadata', 'detail'],
1287 );
1288 }
1289
1290 Future<List<dynamic>> getAdminSchemaVersions(
1291 String collection, {
1292 int limit = 10,
1293 }) async {
1294 final name = _pathSegment(collection);
1295 final result = await _getRaw(
1296 _objUrl('admin/schemas/$name?versions=true&limit=$limit'),
1297 );
1298 return _listFromObjectInspection(result, const [
1299 'versions',
1300 'items',
1301 'results',
1302 'records',
1303 'rows',
1304 ]);
1305 }
1306
1307 Future<dynamic> getAdminSchemaVersion(String collection, int version) async {
1308 final name = _pathSegment(collection);
1309 return _getRaw(_objUrl('admin/schemas/$name?version=$version'));
1310 }
1311
1312 Future<Map<String, dynamic>> updateAdminSchema(
1313 String collection, {
1314 required Map<String, dynamic> schema,
1315 String? author,
1316 String? message,
1317 }) {
1318 final name = _pathSegment(collection);
1319 return rawRequest(
1320 'PUT',
1321 _objUrl('admin/schemas/$name'),
1322 data: {
1323 'schema': schema,
1324 if (author != null && author.trim().isNotEmpty) 'author': author,
1325 if (message != null && message.trim().isNotEmpty) 'message': message,
1326 },
1327 );
1328 }
1329
1330 Future<Map<String, dynamic>> rollbackAdminSchema(
1331 String collection,
1332 int versionId,
1333 ) {
1334 final name = _pathSegment(collection);
1335 return rawRequest(
1336 'POST',
1337 _objUrl('admin/schemas/$name'),
1338 data: {'action': 'rollback', 'version_id': versionId},
1339 );
1340 }
1341
1342 Future<Map<String, dynamic>?> listAdminFiles({
1343 int limit = 100,
1344 int offset = 0,
1345 String? objectId,
1346 }) async {
1347 final params = <String, String>{
1348 'limit': '$limit',
1349 'offset': '$offset',
1350 if (objectId != null && objectId.isNotEmpty) 'object_id': objectId,
1351 };
1352 final query = Uri(queryParameters: params).query;
1353 final result = await _getRaw(_objUrl('admin/files?$query'));
1354 return result is Map<String, dynamic> ? result : _asStringMap(result);
1355 }
1356
1357 Future<List<dynamic>> listAdminFilesForObject(String objectId) async {
1358 final id = _pathSegment(objectId);
1359 final result = await _getRaw(_objUrl('admin/files/$id'));
1360 return _listFromObjectInspection(result, const [
1361 'files',
1362 'items',
1363 'results',
1364 'records',
1365 'rows',
1366 ]);
1367 }
1368
1369 Future<Map<String, dynamic>> getAdminFileContent(
1370 String objectId,
1371 String fileName,
1372 ) {
1373 final id = _pathSegment(objectId);
1374 final file = Uri.encodeQueryComponent(fileName);
1375 return rawRequest('GET', _objUrl('admin/files/$id?file=$file'));
1376 }
1377
1378 Future<Map<String, dynamic>> createAdminFile(
1379 String objectId, {
1380 required String name,
1381 required String content,
1382 }) {
1383 final id = _pathSegment(objectId);
1384 return rawRequest(
1385 'POST',
1386 _objUrl('admin/files/$id'),
1387 data: {
1388 'name': name,
1389 'content_base64': base64Encode(utf8.encode(content)),
1390 },
1391 );
1392 }
1393
1394 Future<Map<String, dynamic>> overwriteAdminFile(
1395 String objectId, {
1396 required String name,
1397 required String content,
1398 }) {
1399 final id = _pathSegment(objectId);
1400 return rawRequest(
1401 'PUT',
1402 _objUrl('admin/files/$id'),
1403 data: {
1404 'name': name,
1405 'content_base64': base64Encode(utf8.encode(content)),
1406 },
1407 );
1408 }
1409
1410 Future<Map<String, dynamic>> deleteAdminFile(
1411 String objectId,
1412 String fileName,
1413 ) {
1414 final id = _pathSegment(objectId);
1415 final file = Uri.encodeQueryComponent(fileName);
1416 return rawRequest('DELETE', _objUrl('admin/files/$id?file=$file'));
1417 }
1418
1419 Future<List<dynamic>> listObjects() async {
1420 final result = await _getRaw(_objUrl('objects?format=json'));
1421 if (result is Map && result.containsKey('objects'))
1422 return result['objects'] as List;
1423 if (result is List) return result;
1424 return [];
1425 }
1426
1427 Future<dynamic> executeObject(
1428 String objectId, {
1429 String method = 'GET',
1430 Map<String, dynamic>? data,
1431 }) async {
1432 if (method == 'GET') {
1433 final result = await _getRaw(_objUrl('objects/$objectId?format=json'));
1434 // If the object returns HTML, format=json will error with raw_response containing the HTML
1435 if (result is Map &&
1436 result['error'] == 'Invalid JSON response from remote station' &&
1437 result.containsKey('raw_response')) {
1438 return {'_html': result['raw_response'], '_type': 'html'};
1439 }
1440 return result;
1441 }
1442 return _postRaw(_objUrl('objects/$objectId?format=json'), data ?? {});
1443 }
1444
1445 Future<Map<String, dynamic>> executeAdminObject(
1446 String objectId, {
1447 String method = 'GET',
1448 Map<String, dynamic>? payload,
1449 }) {
1450 final id = _pathSegment(objectId);
1451 return rawRequest(
1452 'POST',
1453 _objUrl('admin/objects/$id/execute'),
1454 data: {'method': method, 'payload': payload ?? {}},
1455 );
1456 }
1457
1458 /// Fetch raw HTML for an HTML-returning object (used for WebView rendering)
1459 Future<String?> getObjectHTML(String objectId) async {
1460 try {
1461 final response = await _client.get(
1462 Uri.parse(_objUrl('objects/$objectId')),
1463 headers: _headers(),
1464 );
1465 if (response.statusCode == 200) {
1466 final body = response.body;
1467 // If it looks like HTML, return it. If JSON, skip.
1468 if (body.trimLeft().startsWith('<')) return body;
1469 }
1470 } catch (_) {}
1471 return null;
1472 }
1473
1474 Future<String?> getObjectSource(String objectId) async {
1475 final result = await _getRaw(
1476 _objUrl('objects/$objectId?source=true&format=json'),
1477 );
1478 if (result is Map<String, dynamic>) {
1479 return result['source'] as String? ?? result.toString();
1480 }
1481 if (result is String) return result;
1482 return null;
1483 }
1484
1485 Future<Map<String, dynamic>?> getObjectState(String objectId) async {
1486 final result = await _getRaw(
1487 _objUrl('objects/$objectId?state=true&format=json'),
1488 );
1489 return result is Map<String, dynamic> ? result : null;
1490 }
1491
1492 Future<List<dynamic>> getObjectLogs(String objectId, {int limit = 50}) async {
1493 final result = await _getRaw(
1494 _objUrl('objects/$objectId?logs=true&limit=$limit&format=json'),
1495 );
1496 if (result is List) return result;
1497 if (result is Map && result.containsKey('logs'))
1498 return result['logs'] as List;
1499 return [];
1500 }
1501
1502 Future<Map<String, dynamic>?> getObjectMetadata(String objectId) async {
1503 final result = await _getRaw(
1504 _objUrl('objects/$objectId?metadata=true&format=json'),
1505 );
1506 return result is Map<String, dynamic> ? result : null;
1507 }
1508
1509 Future<List<dynamic>> getObjectVersions(String objectId) async {
1510 final result = await _getRaw(
1511 _objUrl('objects/$objectId?versions=true&format=json'),
1512 );
1513 if (result is List) return result;
1514 if (result is Map && result.containsKey('versions'))
1515 return result['versions'] as List;
1516 return [];
1517 }
1518
1519 Future<dynamic> getObjectVersion(String objectId, int version) async {
1520 return _getRaw(_objUrl('objects/$objectId?version=$version&format=json'));
1521 }
1522
1523 Future<List<dynamic>> getObjectFiles(String objectId) async {
1524 final result = await _getRaw(
1525 _objUrl('objects/$objectId?files=true&format=json'),
1526 );
1527 if (result is List) return result;
1528 if (result is Map && result.containsKey('files'))
1529 return result['files'] as List;
1530 return [];
1531 }
1532
1533 Future<dynamic> createObject(
1534 String name,
1535 String code, {
1536 String? description,
1537 }) async {
1538 return _postRaw(_objUrl('admin/objects'), {
1539 'name': name,
1540 'code': code,
1541 if (description != null) 'description': description,
1542 });
1543 }
1544
1545 Future<dynamic> updateObjectSource(String objectId, String code) async {
1546 final id = _pathSegment(objectId);
1547 return _putRaw(_objUrl('admin/objects/$id?source=true'), {'code': code});
1548 }
1549
1550 Future<bool> deleteObject(String objectId) async {
1551 return _deleteRaw(_objUrl('objects/$objectId'));
1552 }
1553
1554 Future<dynamic> rollbackObject(String objectId, int toVersion) async {
1555 return _postRaw(_objUrl('objects/$objectId'), {
1556 'action': 'rollback',
1557 'to': toVersion,
1558 });
1559 }
1560
1561 // --- New OSS object-server dogfood routes ---
1562
1563 Future<Map<String, dynamic>?> getSession() async {
1564 final result = await _getRaw(_objUrl('identity/session'));
1565 return result is Map<String, dynamic> ? result : null;
1566 }
1567
1568 Future<Map<String, dynamic>?> getSchema(String collection) async {
1569 final result = await _getRaw(_objUrl('schemas/$collection'));
1570 return result is Map<String, dynamic> ? result : null;
1571 }
1572
1573 Future<List<dynamic>> listProbeRecords() async {
1574 final result = await _getRaw(_objUrl('collections/dbbasic_probe/records'));
1575 return _listFromResult(result, preferredKey: 'records');
1576 }
1577
1578 Future<Map<String, dynamic>?> createProbeRecord(
1579 Map<String, dynamic> data,
1580 ) async {
1581 final result = await _postRaw(
1582 _objUrl('collections/dbbasic_probe/records'),
1583 data,
1584 );
1585 return result is Map<String, dynamic> ? result : null;
1586 }
1587
1588 Future<Map<String, dynamic>?> updateProbeRecord(
1589 String id,
1590 Map<String, dynamic> data,
1591 ) async {
1592 final result = await _putRaw(
1593 _objUrl('collections/dbbasic_probe/records/${Uri.encodeComponent(id)}'),
1594 data,
1595 );
1596 return result is Map<String, dynamic> ? result : null;
1597 }
1598
1599 Future<bool> deleteProbeRecord(String id) async {
1600 return _deleteRaw(
1601 _objUrl('collections/dbbasic_probe/records/${Uri.encodeComponent(id)}'),
1602 );
1603 }
1604
1605 Future<List<dynamic>> listProbeChanges() async {
1606 final result = await _getRaw(_objUrl('collections/dbbasic_probe/changes'));
1607 return _listFromResult(result, preferredKey: 'changes');
1608 }
1609
1610 Future<List<dynamic>> listProbeRecordChanges(String id) async {
1611 final result = await _getRaw(
1612 _objUrl(
1613 'collections/dbbasic_probe/records/${Uri.encodeComponent(id)}/changes',
1614 ),
1615 );
1616 return _listFromResult(result, preferredKey: 'changes');
1617 }
1618
1619 List<dynamic> _listFromResult(
1620 dynamic result, {
1621 required String preferredKey,
1622 }) {
1623 if (result is List) return result;
1624 if (result is Map) {
1625 final preferred = result[preferredKey];
1626 if (preferred is List) return preferred;
1627 final results = result['results'];
1628 if (results is List) return results;
1629 final items = result['items'];
1630 if (items is List) return items;
1631 }
1632 return [];
1633 }
1634
1635 // =====================================================================
1636 // PLATFORM API (optional — askrobots.com collections)
1637 // =====================================================================
1638
1639 Future<List<dynamic>> _platformList(
1640 String collection, {
1641 int limit = 50,
1642 }) async {
1643 if (!hasPlatform) return [];
1644 final result = await _getRaw(
1645 _platUrl('$collection/?limit=$limit'),
1646 authMode: _AuthMode.platform,
1647 );
1648 if (result is Map && result.containsKey('results'))
1649 return result['results'] as List;
1650 if (result is List) return result;
1651 return [];
1652 }
1653
1654 Future<Map<String, dynamic>?> _platformGet(
1655 String collection,
1656 String id,
1657 ) async {
1658 if (!hasPlatform) return null;
1659 final result = await _getRaw(
1660 _platUrl('$collection/$id/'),
1661 authMode: _AuthMode.platform,
1662 );
1663 return result is Map<String, dynamic> ? result : null;
1664 }
1665
1666 Future<Map<String, dynamic>?> _platformCreate(
1667 String collection,
1668 Map<String, dynamic> data,
1669 ) async {
1670 if (!hasPlatform) return null;
1671 final result = await _postRaw(
1672 _platUrl('$collection/'),
1673 data,
1674 authMode: _AuthMode.platform,
1675 );
1676 return result is Map<String, dynamic> ? result : null;
1677 }
1678
1679 // Public create for any collection
1680 Future<Map<String, dynamic>?> create(
1681 String collection,
1682 Map<String, dynamic> data,
1683 ) async {
1684 return _platformCreate(collection, data);
1685 }
1686
1687 // Update (PATCH) an existing record
1688 Future<Map<String, dynamic>?> update(
1689 String collection,
1690 String id,
1691 Map<String, dynamic> data,
1692 ) async {
1693 if (!hasPlatform) return null;
1694 try {
1695 final response = await _client.patch(
1696 Uri.parse(_platUrl('$collection/$id/')),
1697 headers: _headers(authMode: _AuthMode.platform),
1698 body: jsonEncode(data),
1699 );
1700 if (response.statusCode == 200 || response.statusCode == 201) {
1701 lastError = null;
1702 return jsonDecode(response.body) as Map<String, dynamic>;
1703 }
1704 lastError = 'HTTP ${response.statusCode}: ${response.body}';
1705 } catch (e) {
1706 lastError = 'Error: $e';
1707 }
1708 return null;
1709 }
1710
1711 // Delete a record
1712 Future<bool> delete(String collection, String id) async {
1713 if (!hasPlatform) return false;
1714 return _deleteRaw(
1715 _platUrl('$collection/$id/'),
1716 authMode: _AuthMode.platform,
1717 );
1718 }
1719
1720 // Count (fetches 1 record just to get the count)
1721 Future<int> platformCount(String collection) async {
1722 if (!hasPlatform) return 0;
1723 final result = await _getRaw(
1724 _platUrl('$collection/?limit=1'),
1725 authMode: _AuthMode.platform,
1726 );
1727 if (result is Map && result.containsKey('count'))
1728 return result['count'] as int? ?? 0;
1729 return 0;
1730 }
1731
1732 // Collections
1733 Future<List<dynamic>> listContacts({int limit = 50}) =>
1734 _platformList('contacts', limit: limit);
1735 Future<List<dynamic>> listProjects({int limit = 50}) =>
1736 _platformList('projects', limit: limit);
1737 Future<List<dynamic>> listTasks({int limit = 50}) =>
1738 _platformList('tasks', limit: limit);
1739 Future<List<dynamic>> listInvoices({int limit = 50}) =>
1740 _platformList('invoices', limit: limit);
1741 Future<List<dynamic>> listOrders({int limit = 50}) =>
1742 _platformList('orders', limit: limit);
1743 Future<List<dynamic>> listProducts({int limit = 50}) =>
1744 _platformList('products', limit: limit);
1745 Future<List<dynamic>> listArticles({int limit = 50}) =>
1746 _platformList('articles', limit: limit);
1747 Future<List<dynamic>> listFiles({int limit = 50}) =>
1748 _platformList('files', limit: limit);
1749
1750 Future<Map<String, dynamic>?> getContact(String id) =>
1751 _platformGet('contacts', id);
1752 Future<Map<String, dynamic>?> getProject(String id) =>
1753 _platformGet('projects', id);
1754 Future<Map<String, dynamic>?> getTask(String id) => _platformGet('tasks', id);
1755
1756 // Search
1757 Future<Map<String, dynamic>?> search(String query) async {
1758 if (!hasPlatform) return null;
1759 final result = await _getRaw(
1760 _platUrl('search/?q=${Uri.encodeComponent(query)}'),
1761 authMode: _AuthMode.platform,
1762 );
1763 return result is Map<String, dynamic> ? result : null;
1764 }
1765}