pax-compiler 0.39.0

Compiler APIs for parsing and building Pax projects into application executables
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use color_eyre::eyre::{eyre, Report, Result};
use pax_designtime::messages::PrepareAppRevision;
use serde::{Deserialize, Serialize};

pub const DEV_DIR_NAME: &str = "dev";
pub const DEV_SESSION_STALE_AFTER_MS: u128 = 15_000;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevRequestEnvelope {
    pub request_id: String,
    pub kind: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevLookRequest {
    pub request_id: String,
    pub kind: String,
    pub output_dir: PathBuf,
    pub scale: f64,
    pub period_ms: u64,
    pub duration_ms: u64,
    pub format: String,
    pub quality: Option<f64>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevCapture {
    pub path: PathBuf,
    pub width: usize,
    pub height: usize,
    pub captured_at_ms: u128,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevLookResponse {
    pub request_id: String,
    pub status: String,
    pub captures: Vec<DevCapture>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevInspectTreeRequest {
    pub request_id: String,
    pub kind: String,
    pub max_depth: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevInspectTreeResponse {
    pub request_id: String,
    pub status: String,
    pub node_count: Option<usize>,
    pub tree_json: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevRayCastRequest {
    pub request_id: String,
    pub kind: String,
    pub x: f64,
    pub y: f64,
    pub hit_invisible: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevRayCastResponse {
    pub request_id: String,
    pub status: String,
    pub x: f64,
    pub y: f64,
    pub hit_invisible: bool,
    pub node_count: Option<usize>,
    pub nodes_json: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevSelectorQueryRequest {
    pub request_id: String,
    pub kind: String,
    pub selector: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevSelectorQueryResponse {
    pub request_id: String,
    pub status: String,
    pub selector: String,
    pub node_count: Option<usize>,
    pub nodes_json: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevReplaceNodeRequest {
    pub request_id: String,
    pub kind: String,
    pub component_type_id: String,
    pub template_node_id: usize,
    pub subtemplate: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevReplaceNodeResponse {
    pub request_id: String,
    pub status: String,
    pub component_type_id: String,
    pub template_node_id: usize,
    pub reload_scope: String,
    pub reloaded_template_node_id: Option<usize>,
    pub source_path: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevReloadLogicRequest {
    pub request_id: String,
    pub kind: String,
    pub revision: PrepareAppRevision,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevReloadLogicResponse {
    pub request_id: String,
    pub status: String,
    pub logic_revision_id: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevLogsRequest {
    pub request_id: String,
    pub kind: String,
    pub since_seq: Option<u64>,
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevLogEntry {
    pub seq: u64,
    pub level: String,
    pub message: String,
    pub timestamp_ms: u128,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevLogsResponse {
    pub request_id: String,
    pub status: String,
    pub entries: Vec<DevLogEntry>,
    pub next_seq: u64,
    pub oldest_seq: Option<u64>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DevSession {
    pub session_id: String,
    pub platform: String,
    pub designtime: bool,
    pub project_root: Option<PathBuf>,
    pub session_dir: Option<PathBuf>,
    pub app_pid: Option<u32>,
    pub design_server_addr: Option<String>,
    pub control_kind: String,
    pub location: Option<String>,
    pub started_at_ms: u128,
    pub last_seen_ms: u128,
}

impl DevSession {
    pub fn is_stale(&self, now_ms: u128) -> bool {
        now_ms.saturating_sub(self.last_seen_ms) > DEV_SESSION_STALE_AFTER_MS
    }
}

pub fn now_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

pub fn project_dev_dir(pax_dir: &Path) -> PathBuf {
    pax_dir.join(DEV_DIR_NAME)
}

pub fn project_active_session_file(pax_dir: &Path) -> PathBuf {
    project_dev_dir(pax_dir).join("active-session.json")
}

pub fn project_designtime_manifest_file(pax_dir: &Path) -> PathBuf {
    project_dev_dir(pax_dir).join("designtime-manifest.json")
}

pub fn global_dev_dir() -> Result<PathBuf, Report> {
    let root = if cfg!(target_os = "macos") {
        user_home_dir()?
            .join("Library")
            .join("Application Support")
            .join("Pax")
            .join(DEV_DIR_NAME)
    } else if cfg!(target_os = "windows") {
        if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {
            PathBuf::from(local_app_data).join("Pax").join(DEV_DIR_NAME)
        } else if let Some(app_data) = std::env::var_os("APPDATA") {
            PathBuf::from(app_data).join("Pax").join(DEV_DIR_NAME)
        } else {
            user_home_dir()?
                .join("AppData")
                .join("Local")
                .join("Pax")
                .join(DEV_DIR_NAME)
        }
    } else if let Some(xdg_state_home) = std::env::var_os("XDG_STATE_HOME") {
        PathBuf::from(xdg_state_home).join("pax").join(DEV_DIR_NAME)
    } else if let Some(xdg_data_home) = std::env::var_os("XDG_DATA_HOME") {
        PathBuf::from(xdg_data_home).join("pax").join(DEV_DIR_NAME)
    } else {
        user_home_dir()?
            .join(".local")
            .join("state")
            .join("pax")
            .join(DEV_DIR_NAME)
    };

    fs::create_dir_all(&root)?;
    Ok(root)
}

pub fn global_session_registry_dir() -> Result<PathBuf, Report> {
    let dir = global_dev_dir()?.join("sessions");
    fs::create_dir_all(&dir)?;
    Ok(dir)
}

pub fn global_session_registry_file(session_id: &str) -> Result<PathBuf, Report> {
    Ok(global_session_registry_dir()?.join(format!("{session_id}.json")))
}

pub fn write_project_active_session(pax_dir: &Path, session: &DevSession) -> Result<(), Report> {
    atomic_write_json(&project_active_session_file(pax_dir), session)
}

pub fn read_project_active_session(pax_dir: &Path) -> Result<Option<DevSession>, Report> {
    read_json_if_exists(&project_active_session_file(pax_dir))
}

pub fn remove_project_active_session(pax_dir: &Path, session_id: &str) -> Result<(), Report> {
    let path = project_active_session_file(pax_dir);
    if let Some(existing) = read_json_if_exists::<DevSession>(&path)? {
        if existing.session_id == session_id {
            let _ = fs::remove_file(path);
        }
    }
    Ok(())
}

pub fn write_registered_session(session: &DevSession) -> Result<(), Report> {
    atomic_write_json(&global_session_registry_file(&session.session_id)?, session)
}

pub fn remove_registered_session(session_id: &str) -> Result<(), Report> {
    let path = global_session_registry_file(session_id)?;
    if path.exists() {
        let _ = fs::remove_file(path);
    }
    Ok(())
}

pub fn list_registered_sessions() -> Result<Vec<DevSession>, Report> {
    let registry_dir = global_session_registry_dir()?;
    let mut sessions = vec![];
    for entry in fs::read_dir(registry_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
            continue;
        }
        match fs::read(&path)
            .ok()
            .and_then(|bytes| serde_json::from_slice::<DevSession>(&bytes).ok())
        {
            Some(session) => sessions.push(session),
            None => {
                let _ = fs::remove_file(path);
            }
        }
    }
    sessions.sort_by(|a, b| b.started_at_ms.cmp(&a.started_at_ms));
    Ok(sessions)
}

pub fn session_request_dir(session: &DevSession) -> Result<PathBuf, Report> {
    let session_dir = session.session_dir.as_ref().ok_or_else(|| {
        eyre!(
            "session {} does not expose a local request directory",
            session.session_id
        )
    })?;
    Ok(session_dir.join("requests"))
}

pub fn session_response_dir(session: &DevSession) -> Result<PathBuf, Report> {
    let session_dir = session.session_dir.as_ref().ok_or_else(|| {
        eyre!(
            "session {} does not expose a local response directory",
            session.session_id
        )
    })?;
    Ok(session_dir.join("responses"))
}

pub fn write_session_request_json<T: Serialize>(
    session_dir: &Path,
    request_id: &str,
    value: &T,
) -> Result<(), Report> {
    atomic_write_json(
        &session_dir
            .join("requests")
            .join(format!("{request_id}.json")),
        value,
    )
}

fn read_json_if_exists<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<Option<T>, Report> {
    if !path.exists() {
        return Ok(None);
    }
    Ok(Some(serde_json::from_slice(&fs::read(path)?)?))
}

fn atomic_write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), Report> {
    let bytes = serde_json::to_vec_pretty(value)?;
    let tmp_path = path.with_extension("tmp");
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&tmp_path, bytes)?;
    fs::rename(tmp_path, path)?;
    Ok(())
}

fn user_home_dir() -> Result<PathBuf, Report> {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("USERPROFILE").map(PathBuf::from))
        .or_else(
            || match (std::env::var_os("HOMEDRIVE"), std::env::var_os("HOMEPATH")) {
                (Some(drive), Some(path)) => Some(PathBuf::from(drive).join(path)),
                _ => None,
            },
        )
        .ok_or_else(|| eyre!("could not determine the current user's home directory"))
}

#[cfg(test)]
mod tests {
    use super::{DevReloadLogicRequest, DevReloadLogicResponse};
    use pax_designtime::messages::{DebugArtifact, DebugLogicExecutionMode, PrepareAppRevision};

    #[test]
    fn native_reload_request_round_trips_revision_envelope() {
        let request = DevReloadLogicRequest {
            request_id: "reload-logic-7".to_string(),
            kind: "reload-logic".to_string(),
            revision: PrepareAppRevision {
                logic_revision_id: "logic-7".to_string(),
                execution_mode: DebugLogicExecutionMode::CompiledArtifact,
                artifact: DebugArtifact {
                    kind: "macos-dylib".to_string(),
                    location: "/tmp/PaxCartridge-logic-7.dylib".to_string(),
                },
            },
        };

        let encoded = serde_json::to_vec(&request).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
        assert_eq!(
            json["revision"]["execution_mode"],
            serde_json::Value::String("compiled-artifact".to_string())
        );
        let decoded: DevReloadLogicRequest = serde_json::from_slice(&encoded).unwrap();

        assert_eq!(decoded.request_id, "reload-logic-7");
        assert_eq!(decoded.kind, "reload-logic");
        assert_eq!(decoded.revision.logic_revision_id, "logic-7");
        assert_eq!(decoded.revision.artifact.kind, "macos-dylib");
        assert_eq!(
            decoded.revision.artifact.location,
            "/tmp/PaxCartridge-logic-7.dylib"
        );
        assert!(matches!(
            decoded.revision.execution_mode,
            DebugLogicExecutionMode::CompiledArtifact
        ));
    }

    #[test]
    fn native_reload_response_round_trips_revision_identity() {
        let response = DevReloadLogicResponse {
            request_id: "reload-logic-7".to_string(),
            status: "ok".to_string(),
            logic_revision_id: Some("logic-7".to_string()),
            error: None,
        };

        let encoded = serde_json::to_vec(&response).unwrap();
        let decoded: DevReloadLogicResponse = serde_json::from_slice(&encoded).unwrap();

        assert_eq!(decoded.request_id, "reload-logic-7");
        assert_eq!(decoded.status, "ok");
        assert_eq!(decoded.logic_revision_id.as_deref(), Some("logic-7"));
        assert!(decoded.error.is_none());
    }
}