neutralipcrs 1.4.3

Neutral TS Rust IPC Client. Neutral is a web template engine designed to work with any programming language via IPC and natively as library/crate.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! High-level template processing interface.
//!
//! This module provides the main user-facing API for template processing
//! through the Neutral IPC server. It handles template setup, schema management,
//! and result processing.

use serde_json::Value;
use std::collections::HashMap;
use crate::client::NeutralIpcClient;
use crate::constants::*;
use crate::error::{NeutralIpcError, Result};

/// Main interface for template processing through the Neutral IPC server.
///
/// This struct provides a high-level API for:
/// - Template setup (from file path or source code)
/// - JSON/MsgPack schema management and merging
/// - Template rendering via IPC communication
/// - Result processing and error handling
///
/// # Examples
///
/// ```no_run
/// use neutralipcrs::NeutralIpcTemplate;
/// use serde_json::json;
///
/// let schema = json!({
///     "data": {
///         "text": "World"
///     }
/// });
///
/// let mut template = NeutralIpcTemplate::from_src_value("Hello {:;text:}!", schema).unwrap();
/// let result = template.render().unwrap();
///
/// println!("{}", result); // Output: "Hello World!"
/// ```
pub struct NeutralIpcTemplate {
    /// Template content or file path
    template: String,
    /// Content type identifier (CONTENT_PATH or CONTENT_TEXT)
    tpl_type: u8,
    /// Schema format identifier (CONTENT_JSON or CONTENT_MSGPACK)
    schema_type: u8,
    /// Schema bytes (JSON text bytes or MsgPack bytes)
    schema: Vec<u8>,
    /// Parsed result from the last rendering operation
    pub(crate) result: HashMap<String, Value>,
}

impl NeutralIpcTemplate {
    /// Create a new template instance with default settings.
    ///
    /// The template is initialized with:
    /// - Empty template content
    /// - File-based template type (CONTENT_PATH)
    /// - Empty JSON schema ("{}")
    /// - Empty result map
    ///
    /// # Returns
    ///
    /// A new `NeutralIpcTemplate` instance or an error if initialization fails.
    pub fn new() -> Result<Self> {
        Ok(Self {
            template: "".to_string(),
            tpl_type: CONTENT_PATH,
            schema_type: CONTENT_JSON,
            schema: b"{}".to_vec(),
            result: HashMap::new(),
        })
    }

    /// Create a template from a file path and JSON schema.
    ///
    /// # Arguments
    ///
    /// * `template` - File path to the template
    /// * `schema` - JSON schema as a `Value` or string
    ///
    /// # Returns
    ///
    /// A new `NeutralIpcTemplate` instance configured for file-based processing.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema cannot be serialized to JSON.
    pub fn from_file_value(template: &str, schema: Value) -> Result<Self> {
        let schema_str = if schema.is_string() {
            schema.as_str().unwrap().to_string()
        } else {
            serde_json::to_string(&schema)?
        };

        Ok(Self {
            template: template.to_string(),
            tpl_type: CONTENT_PATH,
            schema_type: CONTENT_JSON,
            schema: schema_str.into_bytes(),
            result: HashMap::new(),
        })
    }

    /// Create a template from source code and JSON schema.
    ///
    /// # Arguments
    ///
    /// * `template` - Template source code as a string
    /// * `schema` - JSON schema as a `Value` or string
    ///
    /// # Returns
    ///
    /// A new `NeutralIpcTemplate` instance configured for source-based processing.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema cannot be serialized to JSON.
    pub fn from_src_value(template: &str, schema: Value) -> Result<Self> {
        let schema_str = if schema.is_string() {
            schema.as_str().unwrap().to_string()
        } else {
            serde_json::to_string(&schema)?
        };

        Ok(Self {
            template: template.to_string(),
            tpl_type: CONTENT_TEXT,
            schema_type: CONTENT_JSON,
            schema: schema_str.into_bytes(),
            result: HashMap::new(),
        })
    }

    /// Create a template from a file path and MsgPack schema bytes.
    ///
    /// # Arguments
    ///
    /// * `template` - File path to the template
    /// * `schema` - MsgPack-encoded schema bytes
    pub fn from_file_msgpack(template: &str, schema: &[u8]) -> Result<Self> {
        Ok(Self {
            template: template.to_string(),
            tpl_type: CONTENT_PATH,
            schema_type: CONTENT_MSGPACK,
            schema: schema.to_vec(),
            result: HashMap::new(),
        })
    }

    /// Create a template from source code and MsgPack schema bytes.
    ///
    /// # Arguments
    ///
    /// * `template` - Template source code
    /// * `schema` - MsgPack-encoded schema bytes
    pub fn from_src_msgpack(template: &str, schema: &[u8]) -> Result<Self> {
        Ok(Self {
            template: template.to_string(),
            tpl_type: CONTENT_TEXT,
            schema_type: CONTENT_MSGPACK,
            schema: schema.to_vec(),
            result: HashMap::new(),
        })
    }


    /// Render the template with the current schema through the Neutral server.
    ///
    /// This method:
    /// 1. Creates an IPC client with the current template and schema
    /// 2. Sends the request to the Neutral server
    /// 3. Processes the response and extracts the rendered content
    /// 4. Stores the complete result in the `result` field for later inspection
    ///
    /// # Returns
    ///
    /// The rendered template content as a string.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - IPC communication with the server fails
    /// - The server returns an invalid response
    /// - The response cannot be parsed as JSON
    ///
    /// # Example
    ///
    /// ```no_run
    /// use neutralipcrs::NeutralIpcTemplate;
    /// use serde_json::json;
    ///
    /// let schema = json!({
    ///     "data": {
    ///         "text": "World"
    ///     }
    /// });
    ///
    /// let mut template = NeutralIpcTemplate::from_src_value("Hello {:;text:}!", schema).unwrap();
    /// let result = template.render().unwrap();
    ///
    /// assert_eq!(result, "Hello World!");
    /// ```
    pub fn render(&mut self) -> Result<String> {
        let mut client = NeutralIpcClient::new(
            CTRL_PARSE_TEMPLATE,
            self.schema_type,
            self.schema.as_slice(),
            self.tpl_type,
            &self.template
        );

        let result = client.start()?;

        let status = result.get("control")
            .and_then(|v| v.as_u64())
            .ok_or(NeutralIpcError::InvalidResponse)? as u8;

        let content1 = result.get("content-1")
            .and_then(|v| v.as_str())
            .ok_or(NeutralIpcError::InvalidResponse)?;

        let content2 = result.get("content-2")
            .and_then(|v| v.as_str())
            .ok_or(NeutralIpcError::InvalidResponse)?;

        let result_data: Value = serde_json::from_str(content1)?;
        self.result = HashMap::new();
        self.result.insert("status".to_string(), Value::Number(status.into()));
        self.result.insert("result".to_string(), result_data);
        self.result.insert("content".to_string(), Value::String(content2.to_string()));

        Ok(content2.to_string())
    }

    /// Set the template to use a file path.
    ///
    /// Changes the template type to `CONTENT_PATH` and updates the template content
    /// to the specified file path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the template file
    pub fn set_path(&mut self, path: &str) {
        self.tpl_type = CONTENT_PATH;
        self.template = path.to_string();
    }

    /// Set the template to use source code directly.
    ///
    /// Changes the template type to `CONTENT_TEXT` and updates the template content
    /// to the provided source code string.
    ///
    /// # Arguments
    ///
    /// * `source` - Template source code
    pub fn set_source(&mut self, source: &str) {
        self.tpl_type = CONTENT_TEXT;
        self.template = source.to_string();
    }

    /// Merge new schema data with the existing schema.
    ///
    /// This method performs a deep merge of JSON objects, allowing you to
    /// incrementally build up complex schemas. For objects with overlapping
    /// keys, the new values will override the existing ones.
    ///
    /// # Arguments
    ///
    /// * `schema` - New schema data to merge (as `Value` or string)
    ///
    /// # Returns
    ///
    /// `Ok(())` if the merge was successful, or an error if schema parsing fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use neutralipcrs::NeutralIpcTemplate;
    /// use serde_json::json;
    ///
    /// let mut template = NeutralIpcTemplate::new().unwrap();
    /// template.merge_schema(json!({"data": {"value": 1}})).unwrap();
    /// template.merge_schema(json!({"data": {"extra": 2}})).unwrap();
    /// // Schema now contains: {"base": {"value": 1, "extra": 2}}
    /// ```
    pub fn merge_schema(&mut self, schema: Value) -> Result<()> {
        let current_schema: Value = match self.schema_type {
            CONTENT_MSGPACK => rmp_serde::from_slice(&self.schema)?,
            _ => serde_json::from_slice(&self.schema)?,
        };
        let new_schema = if schema.is_string() {
            serde_json::from_str(schema.as_str().unwrap())?
        } else {
            schema
        };

        let merged = Self::deep_merge(current_schema, new_schema);
        self.schema = match self.schema_type {
            CONTENT_MSGPACK => rmp_serde::to_vec(&merged)?,
            _ => serde_json::to_vec(&merged)?,
        };
        Ok(())
    }

    /// Replace the current schema with MsgPack bytes.
    ///
    /// This method switches the schema format to `CONTENT_MSGPACK`.
    pub fn set_schema_msgpack(&mut self, schema: &[u8]) {
        self.schema_type = CONTENT_MSGPACK;
        self.schema = schema.to_vec();
    }

    /// Check if the last rendering operation resulted in an error.
    ///
    /// This method examines the result from the last `render()` call and
    /// determines if an error occurred based on:
    /// - The status code (non-zero indicates error)
    /// - The `has_error` field in the result data
    ///
    /// # Returns
    ///
    /// `true` if an error occurred, `false` otherwise.
    pub fn has_error(&self) -> bool {
        if let Some(status) = self.result.get("status").and_then(|v| v.as_u64()) {
            if status != 0 {
                return true;
            }
        }

        if let Some(result) = self.result.get("result") {
            if let Some(has_error) = result.get("has_error").and_then(|v| v.as_bool()) {
                return has_error;
            }
        }

        false
    }

    /// Get the status code from the last rendering result.
    ///
    /// # Returns
    ///
    /// The status code as `&str` from the JSON, or an empty string if not present or if
    /// any error occurs during extraction.
    pub fn get_status_code(&self) -> &str {
        self.result.get("result")
            .and_then(|r| r.get("status_code"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
    }

    /// Get the status text from the last rendering result.
    ///
    /// # Returns
    ///
    /// The status text as `&str` from the JSON, or an empty string reference
    /// if not present or if any error occurs during extraction.
    pub fn get_status_text(&self) -> &str {
        self.result.get("result")
            .and_then(|r| r.get("status_text"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
    }

    /// Get the status parameter from the last rendering result.
    ///
    /// # Returns
    ///
    /// The status parameter as `&str` from the JSON, or an empty string reference
    /// if not present or if any error occurs during extraction.
    pub fn get_status_param(&self) -> &str {
        self.result.get("result")
            .and_then(|r| r.get("status_param"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
    }

    /// Get the complete result data from the last rendering operation.
    ///
    /// # Returns
    ///
    /// A reference to the complete result `Value` if available, or `None`
    /// if no result has been stored yet.
    pub fn get_result(&self) -> Option<&Value> {
        self.result.get("result")
    }

    /// Recursively merge two JSON values.
    ///
    /// For objects, this performs a deep merge where fields from `b` override
    /// or are added to fields in `a`. For all other types, `b` completely
    /// replaces `a`.
    ///
    /// # Arguments
    ///
    /// * `a` - The base JSON value
    /// * `b` - The JSON value to merge into `a`
    ///
    /// # Returns
    ///
    /// The merged JSON value.
    fn deep_merge(a: Value, b: Value) -> Value {
        match (a, b) {
            (Value::Object(mut map_a), Value::Object(map_b)) => {
                for (key, value_b) in map_b {
                    if let Some(value_a) = map_a.get_mut(&key) {
                        *value_a = Self::deep_merge(value_a.clone(), value_b);
                    } else {
                        map_a.insert(key, value_b);
                    }
                }
                Value::Object(map_a)
            }
            (_, b) => b,
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use rmp_serde::from_slice;
    use serde_json::json;
    use crate::client::is_server_available;

    /// Skip test if the Neutral server is not available.
    ///
    /// This helper function checks server availability and panics with a
    /// clear message if the server is not running, allowing tests to be
    /// skipped gracefully during development.
    fn skip_if_server_unavailable() {
        if !is_server_available() {
            panic!("Neutral TS server not available - skipping test");
        }
    }

    #[test]
    fn test_template_src() {
        skip_if_server_unavailable();

        let schema = json!({
            "data": {
                "text": "Hello!",
                "number": 123
            }
        });

        let mut template = NeutralIpcTemplate::from_src_value("Rust IPC client: {:;text:} {:;number:}", schema).unwrap();
        let result = template.render().unwrap();
        let status_code = template.get_status_code();
        let status_text = template.get_status_text();
        let status_param = template.get_status_param();

        assert!(!template.has_error());
        assert_eq!(status_code, "200");
        assert_eq!(status_text, "OK");
        assert_eq!(status_param, "");
        assert_eq!(result, "Rust IPC client: Hello! 123");
    }

    #[test]
    fn test_template_file() {
        skip_if_server_unavailable();

        let schema = json!({
            "data": {
                "text": "Hello!",
                "number": 123
            }
        });

        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let tpl_file = format!("{}/tests/template.ntpl", manifest_dir);

        let mut template = NeutralIpcTemplate::from_file_value(&tpl_file, schema).unwrap();
        let result = template.render().unwrap();
        let status_code = template.get_status_code();
        let status_text = template.get_status_text();
        let status_param = template.get_status_param();

        assert!(!template.has_error());
        assert_eq!(status_code, "200");
        assert_eq!(status_text, "OK");
        assert_eq!(status_param, "");
        assert_eq!(result, "Rust IPC client: Hello! 123");
    }


    #[test]
    fn test_template_merge_schema() {
        skip_if_server_unavailable();

        let schema = json!({
            "data": {
                "text": "Hello!",
                "number": 123
            }
        });

        let schema_merge = json!({
            "data": {
                "text": "Hello! (merged)"
            }
        });

        let mut template = NeutralIpcTemplate::from_src_value("Rust IPC client: {:;text:} {:;number:}", schema).unwrap();
        let _ = template.merge_schema(schema_merge).unwrap();
        let result = template.render().unwrap();
        let status_code = template.get_status_code();
        let status_text = template.get_status_text();
        let status_param = template.get_status_param();

        assert!(!template.has_error());
        assert_eq!(status_code, "200");
        assert_eq!(status_text, "OK");
        assert_eq!(status_param, "");
        assert_eq!(result, "Rust IPC client: Hello! (merged) 123");
    }

    #[test]
    fn test_template_404() {
        skip_if_server_unavailable();

        let schema = json!({
            "data": {
                "text": "Hello!",
                "number": 123
            }
        });

        let mut template = NeutralIpcTemplate::from_src_value("Rust IPC client: {:exit; 404 :}", schema).unwrap();
        let result = template.render().unwrap();
        let status_code = template.get_status_code();
        let status_text = template.get_status_text();
        let status_param = template.get_status_param();

        assert!(!template.has_error());
        assert_eq!(status_code, "404");
        assert_eq!(status_text, "Not Found");
        assert_eq!(status_param, "");
        assert_eq!(result, "404 Not Found");
    }

    #[test]
    fn test_template_redirect() {
        skip_if_server_unavailable();

        let schema = json!({
            "data": {
                "text": "Hello!",
                "number": 123
            }
        });

        let mut template = NeutralIpcTemplate::from_src_value("Rust IPC client: {:redirect; 301 >> https://crates.io/crates/neutralts :}", schema).unwrap();
        let result = template.render().unwrap();
        let status_code = template.get_status_code();
        let status_text = template.get_status_text();
        let status_param = template.get_status_param();

        assert!(!template.has_error());
        assert_eq!(status_code, "301");
        assert_eq!(status_text, "Moved Permanently");
        assert_eq!(status_param, "https://crates.io/crates/neutralts");
        assert_eq!(result, "301 Moved Permanently\nhttps://crates.io/crates/neutralts");
    }

    #[test]
    fn test_from_src_msgpack_and_merge_schema() {
        let schema = json!({
            "data": {
                "text": "Hello!"
            }
        });
        let msgpack = rmp_serde::to_vec(&schema).unwrap();

        let mut template = NeutralIpcTemplate::from_src_msgpack("tpl", &msgpack).unwrap();
        template.merge_schema(json!({"data": {"number": 123}})).unwrap();

        assert_eq!(template.schema_type, CONTENT_MSGPACK);
        let merged: Value = from_slice(&template.schema).unwrap();
        assert_eq!(merged["data"]["text"], "Hello!");
        assert_eq!(merged["data"]["number"], 123);
    }

    #[test]
    fn test_set_schema_msgpack_switches_type() {
        let schema = json!({"data": {"value": 1}});
        let msgpack = rmp_serde::to_vec(&schema).unwrap();

        let mut template = NeutralIpcTemplate::new().unwrap();
        template.set_schema_msgpack(&msgpack);

        assert_eq!(template.schema_type, CONTENT_MSGPACK);
        let decoded: Value = from_slice(&template.schema).unwrap();
        assert_eq!(decoded["data"]["value"], 1);
    }

}