evenframe_core 0.4.0

Core functionality for Evenframe - TypeScript type generation and database schema synchronization
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
use crate::registry::{get_struct_config, get_tagged_union};
use crate::types::{
    EnumRepresentation, FieldType, ForeignTypeRegistry, StructConfig, TaggedUnion, VariantData,
};
use serde_json::Value;

/// Convert a JSON value (already extracted from our struct) into the SurrealDB
/// syntax, guided by a FieldType.  Strings get single quotes in SurrealDB,
/// numeric/bool remain unquoted, arrays get bracketed, etc. This function
/// includes the special logic for EvenframeRecordId (no quotes).
pub fn to_surreal_string(
    field_type: &FieldType,
    value: &Value,
    registry: &ForeignTypeRegistry,
) -> String {
    match field_type {
        FieldType::String | FieldType::Char => {
            let s = value.as_str().unwrap_or_default();
            format!("'{}'", escape_single_quotes(s))
        }
        FieldType::Bool => {
            if value.as_bool().unwrap_or(false) {
                "true".to_string()
            } else {
                "false".to_string()
            }
        }
        FieldType::Other(name) => {
            if let Some(ftc) = registry.lookup(name) {
                match ftc.surql_value_format.as_str() {
                    "datetime" => {
                        if let Some(s) = value.as_str() {
                            format!("d'{}'", escape_single_quotes(s))
                        } else {
                            format!("d'{}'", chrono::Utc::now().to_rfc3339())
                        }
                    }
                    "duration_from_nanos" => {
                        if let Some(nanos) = value.as_i64() {
                            format!("duration::from_nanos({})", nanos)
                        } else if let Some(nanos) = value.as_u64() {
                            format!("duration::from_nanos({})", nanos)
                        } else if let Some(arr) = value.as_array() {
                            let seconds = arr.first().and_then(|v| v.as_i64()).unwrap_or(0);
                            let nanos = arr.get(1).and_then(|v| v.as_i64()).unwrap_or(0);
                            let total_nanos = seconds * 1_000_000_000 + nanos;
                            format!("duration::from_nanos({})", total_nanos)
                        } else {
                            "duration::from_nanos(0)".to_string()
                        }
                    }
                    "quoted_string" => {
                        if let Some(s) = value.as_str() {
                            format!("'{}'", escape_single_quotes(s))
                        } else {
                            "'UTC'".to_string()
                        }
                    }
                    "decimal_number" => {
                        // Emit with the `dec` suffix so SurrealDB stores the value
                        // as a `decimal` type. Without the suffix, SurrealQL
                        // interprets `10` as `int` and `10.0` as `float`, which
                        // round-trip back as JSON-number rather than the
                        // string-encoded decimal Rust's `Decimal::deserialize`
                        // expects — even though the field's DEFINE FIELD type
                        // is `decimal`, CONTENT-form CREATE/UPDATE doesn't
                        // coerce on the way in.
                        let raw = if value.is_string() {
                            value.as_str().unwrap_or("0.0").to_string()
                        } else if value.is_number() {
                            value.to_string()
                        } else {
                            "0.0".to_string()
                        };
                        format!("{}dec", raw)
                    }
                    "record_id" => {
                        let id_string = value.as_str().unwrap_or_default();
                        id_string.replace('`', "")
                    }
                    "uuid_literal" => {
                        if let Some(s) = value.as_str() {
                            format!("u'{}'", escape_single_quotes(s))
                        } else {
                            "rand::uuid::v7()".to_string()
                        }
                    }
                    "bytes_literal" => {
                        // SurrealDB's `bytes` column expects a typed literal —
                        // `b"deadbeef"` for hex or `b64"..."` for base64.
                        // The JSON wire format is base64.
                        if let Some(s) = value.as_str() {
                            format!("b64\"{}\"", s)
                        } else {
                            "b64\"\"".to_string()
                        }
                    }
                    "geometry_literal" => {
                        // SurrealDB geometry: pass through GeoJSON object as a
                        // SurrealQL object literal. The `geometry` type coerces
                        // a `{ type, coordinates }` object.
                        to_surreal_string_inferred(value)
                    }
                    _ => to_surreal_string_inferred(value),
                }
            } else if let Some(tagged_union) = get_tagged_union(name) {
                // Tagged union (e.g. an `EventKind` field). Without this
                // branch the call falls through to
                // `to_surreal_string_inferred`, which has no way to know
                // that nested fields like `kind.resources` are
                // `RecordLink<Resource>` and emits them as quoted
                // strings — which SurrealDB then refuses to coerce to
                // `record<resource>`. Walking the variant's struct
                // config gives every nested field its real `FieldType`.
                tagged_union_to_surreal_string(&tagged_union, value, registry)
            } else if let Some(struct_config) = get_struct_config(name) {
                // Plain (non-table) embedded struct. Same reasoning as
                // tagged unions — walk fields with their real types so
                // nested `RecordLink<T>` / typed primitives (datetime,
                // decimal, etc.) survive the round trip.
                struct_config_to_surreal_string(&struct_config, value, registry)
            } else {
                to_surreal_string_inferred(value)
            }
        }
        FieldType::F32
        | FieldType::F64
        | FieldType::I8
        | FieldType::I16
        | FieldType::I32
        | FieldType::I64
        | FieldType::I128
        | FieldType::Isize
        | FieldType::U8
        | FieldType::U16
        | FieldType::U32
        | FieldType::U64
        | FieldType::U128
        | FieldType::Usize => {
            if value.is_number() {
                value.to_string()
            } else {
                "0".to_string()
            }
        }
        FieldType::Unit => "null".to_string(),
        FieldType::Vec(inner_type) => {
            if let Some(array) = value.as_array() {
                let items: Vec<String> = array
                    .iter()
                    .map(|item_value| to_surreal_string(inner_type, item_value, registry))
                    .collect();
                format!("[{}]", items.join(", "))
            } else {
                "[]".to_string()
            }
        }
        FieldType::Option(inner_type) => {
            if value.is_null() {
                "null".to_string()
            } else {
                to_surreal_string(inner_type, value, registry)
            }
        }
        FieldType::Tuple(field_types) => {
            if let Some(arr) = value.as_array() {
                let mut parts = Vec::new();
                for (sub_ftype, sub_val) in field_types.iter().zip(arr.iter()) {
                    let s = to_surreal_string(sub_ftype, sub_val, registry);
                    parts.push(s);
                }
                format!("[{}]", parts.join(", "))
            } else {
                "".to_string()
            }
        }
        FieldType::Struct(fields) => {
            if let Some(obj) = value.as_object() {
                let mut pairs = Vec::new();
                for (sub_field_name, sub_field_type) in fields {
                    if let Some(sub_val) = obj.get(sub_field_name) {
                        let s = to_surreal_string(sub_field_type, sub_val, registry);
                        pairs.push(format!("{}: {}", sub_field_name, s));
                    }
                }
                format!("{{ {} }}", pairs.join(", "))
            } else {
                "{}".to_string()
            }
        }
        FieldType::HashMap(key_type, value_type) => {
            if let Some(obj) = value.as_object() {
                let mut pairs = Vec::new();
                for (k, v) in obj {
                    let key_str = match &**key_type {
                        FieldType::String | FieldType::Char | FieldType::Other(_) => {
                            format!("'{}'", escape_single_quotes(k))
                        }
                        _ => k.clone(),
                    };
                    let val_str = to_surreal_string(value_type, v, registry);
                    pairs.push(format!("{}: {}", key_str, val_str));
                }
                format!("{{ {} }}", pairs.join(", "))
            } else {
                "{}".to_string()
            }
        }
        FieldType::BTreeMap(key_type, value_type) => {
            if let Some(obj) = value.as_object() {
                let mut pairs = Vec::new();
                for (k, v) in obj {
                    let key_str = match &**key_type {
                        FieldType::String | FieldType::Char | FieldType::Other(_) => {
                            format!("'{}'", escape_single_quotes(k))
                        }
                        _ => k.clone(),
                    };
                    let val_str = to_surreal_string(value_type, v, registry);
                    pairs.push(format!("{}: {}", key_str, val_str));
                }
                format!("{{ {} }}", pairs.join(", "))
            } else {
                "{}".to_string()
            }
        }
        FieldType::RecordLink(inner_ftype) => {
            // Wrap every record-link string in `type::record('…')` so
            // SurrealDB parses it via the dedicated record-id grammar
            // instead of injecting it raw into the query. Bare
            // injection breaks the moment an ID contains a colon,
            // backtick, or other character that needs quoting — e.g.
            // a record stored as `user:⟨user:test_sso⟩` becomes
            // `WHERE owner = user:user:test_sso` after backtick-strip,
            // which is invalid SurrealQL. `type::record` accepts the
            // full string verbatim and resolves to the right record.
            if value.is_string() {
                let link_string = value
                    .as_str()
                    .expect("Record link value should not be None");
                format!("type::record('{}')", escape_single_quotes(link_string))
            } else if let Some(obj) = value.as_object() {
                if let Some(id_value) = obj.get("Id") {
                    if let Some(id_str) = id_value.as_str() {
                        format!("type::record('{}')", escape_single_quotes(id_str))
                    } else {
                        "null".to_string()
                    }
                } else if let Some(id_value) = obj.get("id") {
                    // When the record was FETCHed, the full object is present
                    // with a lowercase "id" field. Extract just the ID.
                    if let Some(id_str) = id_value.as_str() {
                        format!("type::record('{}')", escape_single_quotes(id_str))
                    } else {
                        "null".to_string()
                    }
                } else if let Some(obj_value) = obj.get("Object") {
                    to_surreal_string(inner_ftype, obj_value, registry)
                } else {
                    to_surreal_string(inner_ftype, value, registry)
                }
            } else {
                "null".to_string()
            }
        }
    }
}

/// Walk a `TaggedUnion` value with full field-type information so nested
/// `RecordLink<T>`, datetime, decimal, etc. fields produce correct
/// SurrealQL syntax (record refs, `d'…'`, bare numbers) instead of being
/// emitted as quoted strings via `to_surreal_string_inferred`.
///
/// Honors the union's `representation`:
/// - `ExternallyTagged`: `{ "VariantName": { …fields… } }` or `"VariantName"`
/// - `InternallyTagged { tag }`: `{ tag: "VariantName", …fields… }`
/// - `AdjacentlyTagged { tag, content }`: `{ tag: "VariantName", content: { …fields… } }`
/// - `Untagged`: best-effort match against each variant's struct fields
fn tagged_union_to_surreal_string(
    tu: &TaggedUnion,
    value: &Value,
    registry: &ForeignTypeRegistry,
) -> String {
    let tu = tu.effective();

    // Pull `(variant_name, payload_obj_or_none)` out of the value
    // according to the union's serde representation.
    let (variant_name, variant_obj) = match (&tu.representation, value) {
        (EnumRepresentation::ExternallyTagged, Value::String(s)) => (s.clone(), None),
        (EnumRepresentation::ExternallyTagged, Value::Object(obj)) => {
            // Object should have exactly one key — the variant name —
            // mapped to the variant's data.
            if let Some((k, v)) = obj.iter().next() {
                (k.clone(), Some(v.clone()))
            } else {
                return to_surreal_string_inferred(value);
            }
        }
        (EnumRepresentation::InternallyTagged { tag }, Value::Object(obj)) => {
            let name = obj
                .get(tag.as_str())
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            // Strip the tag so the remaining fields are the variant data.
            let mut without_tag = obj.clone();
            without_tag.remove(tag.as_str());
            (name, Some(Value::Object(without_tag)))
        }
        (EnumRepresentation::AdjacentlyTagged { tag, content }, Value::Object(obj)) => {
            let name = obj
                .get(tag.as_str())
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            (name, obj.get(content.as_str()).cloned())
        }
        (EnumRepresentation::Untagged, Value::Object(obj)) => {
            // No discriminator — match structurally: the variant whose
            // inline-struct field names cover every key of the object,
            // preferring the largest overlap. Without this, a nested
            // `RecordLink` inside an untagged variant (e.g.
            // `EmployeeIdentity::LinkedUser { user }`) falls into
            // inference and is emitted as a quoted string, which fails
            // the schema's `record<>` coercion.
            let mut best: Option<(String, usize)> = None;
            for candidate in &tu.variants {
                if let Some(VariantData::InlineStruct(sc)) = candidate.data.as_ref() {
                    let sc = sc.effective();
                    let names: std::collections::HashSet<&str> =
                        sc.fields.iter().map(|f| f.field_name.as_str()).collect();
                    if obj.keys().all(|k| names.contains(k.as_str()))
                        && best.as_ref().is_none_or(|(_, n)| obj.len() > *n)
                    {
                        best = Some((candidate.name.clone(), obj.len()));
                    }
                }
            }
            match best {
                Some((name, _)) => (name, Some(value.clone())),
                None => return to_surreal_string_inferred(value),
            }
        }
        (EnumRepresentation::Untagged, _) => {
            // Non-object untagged payloads (unit strings, scalars) carry
            // no structure to match — inference is already correct.
            return to_surreal_string_inferred(value);
        }
        _ => return to_surreal_string_inferred(value),
    };

    let Some(variant) = tu.variants.iter().find(|v| v.name == variant_name) else {
        return to_surreal_string_inferred(value);
    };

    let mut pairs: Vec<String> = Vec::new();

    // Re-emit the discriminator the same way it arrived.
    match &tu.representation {
        EnumRepresentation::InternallyTagged { tag } => {
            pairs.push(format!(
                "{}: '{}'",
                tag,
                escape_single_quotes(&variant_name)
            ));
        }
        EnumRepresentation::AdjacentlyTagged { tag, .. } => {
            pairs.push(format!(
                "{}: '{}'",
                tag,
                escape_single_quotes(&variant_name)
            ));
        }
        _ => {}
    }

    // Walk the variant's inline-struct fields (if any) with their real
    // field types. `DataStructureRef` (newtype / single-payload tuple
    // variants) is handled separately below.
    if let Some(VariantData::InlineStruct(struct_config)) = variant.data.as_ref()
        && let Some(payload_obj) = variant_obj.as_ref().and_then(|v| v.as_object())
    {
        for field in &struct_config.effective().fields {
            if let Some(sub_val) = payload_obj.get(&field.field_name) {
                let s = to_surreal_string(&field.field_type, sub_val, registry);
                pairs.push(format!("{}: {}", field.field_name, s));
            }
        }
    }

    // Newtype variants carry one typed payload (e.g.
    // `Service(Box<RecordLink<Service>>)`). Format the payload with the
    // variant's `FieldType` and emit it under the discriminator shape so
    // record links / typed primitives survive the round trip — without
    // this, the ExternallyTagged branch below saw empty `pairs` and
    // emitted `{ Variant: {} }`, dropping the payload.
    if let Some(VariantData::DataStructureRef(ft)) = variant.data.as_ref()
        && let Some(payload) = variant_obj.as_ref()
    {
        let payload_str = to_surreal_string(ft, payload, registry);
        return match &tu.representation {
            EnumRepresentation::ExternallyTagged => format!(
                "{{ '{}': {} }}",
                escape_single_quotes(&variant_name),
                payload_str
            ),
            EnumRepresentation::AdjacentlyTagged { tag, content } => format!(
                "{{ {}: '{}', {}: {} }}",
                tag,
                escape_single_quotes(&variant_name),
                content,
                payload_str
            ),
            EnumRepresentation::InternallyTagged { tag } => format!(
                "{{ {}: '{}', value: {} }}",
                tag,
                escape_single_quotes(&variant_name),
                payload_str
            ),
            EnumRepresentation::Untagged => payload_str,
        };
    }

    // Adjacently-tagged unions wrap the variant payload under `content`.
    if let EnumRepresentation::AdjacentlyTagged { content, .. } = &tu.representation {
        // Replace the body fields we just emitted with a nested
        // `content: { … }` object that matches serde's adjacent shape.
        let body_pairs: Vec<String> = pairs
            .iter()
            .filter(|p| {
                !p.starts_with(&format!("{}:", content))
                    && !p.starts_with(&format!("{}: ", content))
            })
            .cloned()
            .collect();
        let tag_pair = body_pairs
            .iter()
            .find(|p| p.contains(": '"))
            .cloned()
            .unwrap_or_default();
        let inner_pairs: Vec<String> = body_pairs.into_iter().filter(|p| p != &tag_pair).collect();
        return format!(
            "{{ {}, {}: {{ {} }} }}",
            tag_pair,
            content,
            inner_pairs.join(", ")
        );
    }

    // Externally-tagged with payload: `{ VariantName: { …fields… } }`.
    if matches!(tu.representation, EnumRepresentation::ExternallyTagged) && variant_obj.is_some() {
        return format!(
            "{{ '{}': {{ {} }} }}",
            escape_single_quotes(&variant_name),
            pairs.join(", ")
        );
    }
    // Externally-tagged unit variant: `'VariantName'`.
    if matches!(tu.representation, EnumRepresentation::ExternallyTagged) && variant_obj.is_none() {
        return format!("'{}'", escape_single_quotes(&variant_name));
    }

    format!("{{ {} }}", pairs.join(", "))
}

/// Walk a plain (non-table) struct value with full field-type information
/// so nested `RecordLink<T>` and other typed primitives serialize to the
/// right SurrealQL form. Without this, `FieldType::Other(StructName)`
/// fell through to `to_surreal_string_inferred` and lost type info on
/// every nested field.
fn struct_config_to_surreal_string(
    sc: &StructConfig,
    value: &Value,
    registry: &ForeignTypeRegistry,
) -> String {
    let sc = sc.effective();
    let Some(obj) = value.as_object() else {
        return to_surreal_string_inferred(value);
    };
    let mut pairs: Vec<String> = Vec::new();
    for field in &sc.fields {
        if let Some(sub_val) = obj.get(&field.field_name) {
            let s = to_surreal_string(&field.field_type, sub_val, registry);
            pairs.push(format!("{}: {}", field.field_name, s));
        }
    }
    format!("{{ {} }}", pairs.join(", "))
}

/// Recursively convert a JSON value to SurrealQL syntax by inferring types.
/// Used for `FieldType::Other` (nested Evenframe structs) where field type
/// information is not available. Detects ISO 8601 datetimes and wraps them
/// in SurrealQL `d'...'` syntax so they are stored as proper datetime values
/// rather than strings.
fn to_surreal_string_inferred(value: &Value) -> String {
    match value {
        Value::Null => "null".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => {
            if is_iso8601_datetime(s) {
                format!("d'{}'", escape_single_quotes(s))
            } else {
                format!("'{}'", escape_single_quotes(s))
            }
        }
        Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(to_surreal_string_inferred).collect();
            format!("[{}]", items.join(", "))
        }
        Value::Object(obj) => {
            let pairs: Vec<String> = obj
                .iter()
                .map(|(k, v)| format!("{}: {}", k, to_surreal_string_inferred(v)))
                .collect();
            format!("{{ {} }}", pairs.join(", "))
        }
    }
}

/// Check if a string is an ISO 8601 datetime (e.g. "2025-05-29T23:00:00Z").
fn is_iso8601_datetime(s: &str) -> bool {
    if s.len() < 20 {
        return false;
    }
    let b = s.as_bytes();
    // YYYY-MM-DDTHH:MM:SS...
    b[4] == b'-' && b[7] == b'-' && b[10] == b'T' && b[13] == b':' && b[16] == b':'
}

fn escape_single_quotes(s: &str) -> String {
    s.replace('\'', "\\'")
}