surrealkit 0.7.0

Manage migrations, seeding, typgen and tests for SurrealDB via CLI
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
600
//! Output emitters for a [`SchemaTypes`] document.
//!
//! Two emitters share the same structured document:
//! - [`to_json`] serialises the document verbatim.
//! - [`to_typescript`] renders TypeScript interfaces for the surrealdb JS SDK (v2): one `interface`
//!   per table, every table carrying an `id: RecordId<'table'>`, with field types mapped to SDK
//!   wrapper types.

use std::collections::{BTreeMap, BTreeSet};

use anyhow::Result;

use super::types::{FieldDef, FieldType, ObjectField, PrimitiveType, SchemaTypes, TableDef};

pub fn to_json(doc: &SchemaTypes, pretty: bool) -> Result<String> {
	Ok(if pretty {
		serde_json::to_string_pretty(doc)?
	} else {
		serde_json::to_string(doc)?
	})
}

/// Render a [`SchemaTypes`] document as TypeScript interfaces targeting the
/// surrealdb JS SDK (v2). Returns the full file contents.
pub fn to_typescript(doc: &SchemaTypes) -> Result<String> {
	let mut imports: BTreeSet<&'static str> = BTreeSet::new();
	let mut body = String::new();

	// Skip SurrealKit's internal bookkeeping tables (`__entity`, `__rollout`,
	// …) — they are framework state, not user schema.
	let tables = doc.tables.iter().filter(|t| !t.name.starts_with("__"));
	for (idx, table) in tables.enumerate() {
		if idx > 0 {
			body.push('\n');
		}
		render_table(table, &mut body, &mut imports);
	}

	let mut out = String::new();
	out.push_str("// Generated by SurrealKit — do not edit.\n");
	out.push_str("// Run `surrealkit typegen` to regenerate.\n\n");
	if !imports.is_empty() {
		let list = imports.iter().copied().collect::<Vec<_>>().join(", ");
		out.push_str(&format!("import type {{ {list} }} from 'surrealdb';\n\n"));
	}
	out.push_str(&body);
	Ok(out)
}

fn render_table(table: &TableDef, out: &mut String, imports: &mut BTreeSet<&'static str>) {
	imports.insert("RecordId");
	out.push_str(&format!("export interface {} {{\n", pascal_case(&table.name)));
	// Every record has a typed id. The synthesized field wins over any
	// introspected `id` field (every record id is a RecordId).
	out.push_str(&format!("  id: RecordId<'{}'>;\n", table.name));

	let tree = build_field_tree(&table.fields);
	for (name, node) in &tree.children {
		render_node(name, node, 1, out, imports);
	}
	out.push_str("}\n");
}

/// A node in the field tree reconstructed from flattened field paths
/// (`address.city`, `tags[*]`, `addresses[*].street`).
#[derive(Default)]
struct Node {
	/// Type declared for this exact path (no trailing `[*]`).
	own_type: Option<FieldType>,
	/// Whether the declaring field was `option<...>`.
	own_optional: bool,
	/// Element scalar type from a leaf `[*]` entry (e.g. `tags[*]`).
	elem_type: Option<FieldType>,
	/// Object properties below this node (from `.` descent).
	children: BTreeMap<String, Node>,
	/// `true` when this node's children describe an array element (reached via `[*]`).
	child_array: bool,
}

/// Build a nested tree from the table's flattened field paths.
///
/// SurrealDB reports nested fields dot-separated (`address.city`) and array
/// element shapes via a `*` segment (`tags.*`, `addresses.*.street`). A `*`
/// segment marks the *current* node as an array rather than introducing a
/// child. The top-level `id` field (if introspected) is dropped — it is
/// synthesized separately.
fn build_field_tree(fields: &[FieldDef]) -> Node {
	let mut root = Node::default();
	for field in fields {
		let segments: Vec<&str> =
			field.name.split('.').map(str::trim).filter(|s| !s.is_empty()).collect();
		if segments.is_empty() {
			continue;
		}
		// Skip a synthesized-equivalent top-level `id` field.
		if segments.len() == 1 && segments[0] == "id" {
			continue;
		}

		let mut node = &mut root;
		let last = segments.len() - 1;
		for (i, raw) in segments.iter().enumerate() {
			let is_last = i == last;
			// `*` (or a trailing `[*]` in older SurrealDB) marks the current
			// node as an array. It modifies the node we are already on instead
			// of descending into a child.
			let (name, is_array) = strip_array_marker(raw);
			if name == "*" || (name.is_empty() && is_array) {
				node.child_array = true;
				if is_last {
					// Leaf `*` entry such as `tags.*`: the type describes the
					// array element scalar, not the node itself.
					node.elem_type = Some(field.r#type.clone());
				}
				continue;
			}

			node = node.children.entry(name.clone()).or_default();
			if is_array {
				// Older `name[*]` syntax: the named field itself is the array.
				node.child_array = true;
			}
			if is_last {
				node.own_type = Some(field.r#type.clone());
				node.own_optional = field.optional;
			}
		}
	}
	root
}

fn render_node(
	name: &str,
	node: &Node,
	depth: usize,
	out: &mut String,
	imports: &mut BTreeSet<&'static str>,
) {
	let indent = "  ".repeat(depth);
	let optional = if node.own_optional {
		"?"
	} else {
		""
	};
	let key = format_key(name);
	let ty = render_node_type(node, depth, imports);
	out.push_str(&format!("{indent}{key}{optional}: {ty};\n"));
}

fn render_node_type(node: &Node, depth: usize, imports: &mut BTreeSet<&'static str>) -> String {
	if !node.children.is_empty() {
		let inner_indent = "  ".repeat(depth + 1);
		let close_indent = "  ".repeat(depth);
		let mut obj = String::from("{\n");
		for (name, child) in &node.children {
			let optional = if child.own_optional {
				"?"
			} else {
				""
			};
			let key = format_key(name);
			let ty = render_node_type(child, depth + 1, imports);
			obj.push_str(&format!("{inner_indent}{key}{optional}: {ty};\n"));
		}
		obj.push_str(&format!("{close_indent}}}"));

		let is_array = node.child_array
			|| matches!(node.own_type, Some(FieldType::Array { .. } | FieldType::Set { .. }));
		if is_array {
			format!("({obj})[]")
		} else {
			obj
		}
	} else if let Some(ty) = &node.own_type {
		field_type_to_ts(ty, imports)
	} else if let Some(elem) = &node.elem_type {
		let inner = field_type_to_ts(elem, imports);
		wrap_array(&inner)
	} else {
		"unknown".to_string()
	}
}

/// Map a parsed [`FieldType`] to a TypeScript type expression, recording any
/// surrealdb SDK symbols that need importing.
fn field_type_to_ts(ty: &FieldType, imports: &mut BTreeSet<&'static str>) -> String {
	match ty {
		FieldType::Primitive {
			name,
		} => primitive_to_ts(*name, imports),
		FieldType::Option {
			inner,
		} => {
			format!("{} | undefined", field_type_to_ts(inner, imports))
		}
		FieldType::Array {
			inner,
			..
		}
		| FieldType::Set {
			inner,
			..
		} => wrap_array(&field_type_to_ts(inner, imports)),
		FieldType::Record {
			tables,
		} => {
			imports.insert("RecordId");
			if tables.is_empty() {
				"RecordId".to_string()
			} else {
				tables.iter().map(|t| format!("RecordId<'{t}'>")).collect::<Vec<_>>().join(" | ")
			}
		}
		FieldType::Geometry {
			kinds,
		} => geometry_to_ts(kinds, imports),
		FieldType::Literal {
			value,
		} => literal_to_ts(value),
		FieldType::Union {
			variants,
		} => variants.iter().map(|v| field_type_to_ts(v, imports)).collect::<Vec<_>>().join(" | "),
		FieldType::Object {
			fields,
		} => object_to_ts(fields, imports),
		FieldType::Unknown {
			..
		} => "unknown".to_string(),
	}
}

fn primitive_to_ts(name: PrimitiveType, imports: &mut BTreeSet<&'static str>) -> String {
	match name {
		PrimitiveType::String => "string",
		PrimitiveType::Int | PrimitiveType::Float | PrimitiveType::Number => "number",
		PrimitiveType::Decimal => {
			imports.insert("Decimal");
			"Decimal"
		}
		PrimitiveType::Bool => "boolean",
		PrimitiveType::Datetime => "Date",
		PrimitiveType::Duration => {
			imports.insert("Duration");
			"Duration"
		}
		PrimitiveType::Uuid => {
			imports.insert("Uuid");
			"Uuid"
		}
		PrimitiveType::Bytes => "Uint8Array",
		PrimitiveType::Any => "any",
		PrimitiveType::Null => "null",
		PrimitiveType::None => "undefined",
		PrimitiveType::Object => "{ [key: string]: unknown }",
		PrimitiveType::Function => "unknown",
	}
	.to_string()
}

fn geometry_to_ts(kinds: &[String], imports: &mut BTreeSet<&'static str>) -> String {
	if kinds.is_empty() {
		imports.insert("Geometry");
		return "Geometry".to_string();
	}
	kinds
		.iter()
		.map(|kind| {
			let symbol = match kind.to_ascii_lowercase().as_str() {
				"point" => "GeometryPoint",
				"line" | "linestring" => "GeometryLine",
				"polygon" => "GeometryPolygon",
				"multipoint" => "GeometryMultiPoint",
				"multiline" | "multilinestring" => "GeometryMultiLine",
				"multipolygon" => "GeometryMultiPolygon",
				"collection" => "GeometryCollection",
				_ => "Geometry",
			};
			imports.insert(symbol);
			symbol.to_string()
		})
		.collect::<Vec<_>>()
		.join(" | ")
}

fn object_to_ts(fields: &[ObjectField], imports: &mut BTreeSet<&'static str>) -> String {
	if fields.is_empty() {
		return "{ [key: string]: unknown }".to_string();
	}
	let inner = fields
		.iter()
		.map(|f| format!("{}: {}", format_key(&f.name), field_type_to_ts(&f.r#type, imports)))
		.collect::<Vec<_>>()
		.join("; ");
	format!("{{ {inner} }}")
}

fn literal_to_ts(value: &serde_json::Value) -> String {
	match value {
		serde_json::Value::String(s) => format!("{s:?}"),
		serde_json::Value::Number(n) => n.to_string(),
		serde_json::Value::Bool(b) => b.to_string(),
		serde_json::Value::Null => "null".to_string(),
		other => format!("{other}"),
	}
}

/// Wrap a rendered type as an array, parenthesising unions so `A | B` becomes
/// `(A | B)[]` rather than the ambiguous `A | B[]`.
fn wrap_array(inner: &str) -> String {
	if inner.contains(" | ") {
		format!("({inner})[]")
	} else {
		format!("{inner}[]")
	}
}

/// Split a path segment into `(name, is_array)`, stripping trailing `[*]`.
fn strip_array_marker(segment: &str) -> (String, bool) {
	let mut name = segment;
	let mut is_array = false;
	while let Some(stripped) = name.strip_suffix("[*]") {
		is_array = true;
		name = stripped;
	}
	(name.to_string(), is_array)
}

/// Quote a property key when it is not a plain identifier.
fn format_key(name: &str) -> String {
	if is_valid_identifier(name) {
		name.to_string()
	} else {
		format!("{name:?}")
	}
}

fn is_valid_identifier(s: &str) -> bool {
	let mut chars = s.chars();
	match chars.next() {
		Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
		_ => return false,
	}
	chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

/// Convert a table name to a PascalCase interface name (`user` → `User`,
/// `user_profile` → `UserProfile`).
fn pascal_case(name: &str) -> String {
	let mut out = String::new();
	for part in name.split(|c: char| !c.is_ascii_alphanumeric()) {
		if part.is_empty() {
			continue;
		}
		let mut chars = part.chars();
		if let Some(first) = chars.next() {
			out.extend(first.to_uppercase());
			out.push_str(chars.as_str());
		}
	}
	if out.is_empty() {
		name.to_string()
	} else {
		out
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::typegen::types::{FieldType, PrimitiveType};

	fn prim(name: PrimitiveType) -> FieldType {
		FieldType::Primitive {
			name,
		}
	}

	fn field(name: &str, ty: FieldType, optional: bool) -> FieldDef {
		FieldDef {
			name: name.to_string(),
			define: String::new(),
			r#type: ty,
			optional,
			flexible: false,
			readonly: false,
			has_default: false,
			raw_type: None,
		}
	}

	fn table(name: &str, fields: Vec<FieldDef>) -> TableDef {
		TableDef {
			name: name.to_string(),
			define: String::new(),
			schemafull: Some(true),
			kind: None,
			fields,
			events: vec![],
			indexes: vec![],
		}
	}

	fn doc(tables: Vec<TableDef>) -> SchemaTypes {
		SchemaTypes {
			version: 1,
			generated_at: String::new(),
			namespace: None,
			database: None,
			tables,
			functions: vec![],
			params: vec![],
			analyzers: vec![],
			accesses: vec![],
			apis: vec![],
			buckets: vec![],
			sequences: vec![],
			configs: vec![],
			models: vec![],
			users: vec![],
		}
	}

	#[test]
	fn pascal_case_variants() {
		assert_eq!(pascal_case("user"), "User");
		assert_eq!(pascal_case("user_profile"), "UserProfile");
		assert_eq!(pascal_case("blog-post"), "BlogPost");
		assert_eq!(pascal_case("User"), "User");
	}

	#[test]
	fn table_becomes_interface_with_typed_id() {
		let d = doc(vec![table("user", vec![field("name", prim(PrimitiveType::String), false)])]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("export interface User {"), "got:\n{ts}");
		assert!(ts.contains("id: RecordId<'user'>;"), "got:\n{ts}");
		assert!(ts.contains("name: string;"), "got:\n{ts}");
		assert!(ts.contains("import type { RecordId } from 'surrealdb';"), "got:\n{ts}");
	}

	#[test]
	fn optional_field_gets_question_mark() {
		let d =
			doc(vec![table("user", vec![field("nickname", prim(PrimitiveType::String), true)])]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("nickname?: string;"), "got:\n{ts}");
	}

	#[test]
	fn record_link_maps_to_record_id() {
		let d = doc(vec![table(
			"comment",
			vec![field(
				"author",
				FieldType::Record {
					tables: vec!["user".into()],
				},
				false,
			)],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("author: RecordId<'user'>;"), "got:\n{ts}");
	}

	#[test]
	fn array_of_string_maps_to_array() {
		let d = doc(vec![table(
			"post",
			vec![field(
				"tags",
				FieldType::Array {
					inner: Box::new(prim(PrimitiveType::String)),
					max: None,
				},
				false,
			)],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("tags: string[];"), "got:\n{ts}");
	}

	#[test]
	fn record_union_array_is_parenthesised() {
		let d = doc(vec![table(
			"post",
			vec![field(
				"refs",
				FieldType::Array {
					inner: Box::new(FieldType::Record {
						tables: vec!["user".into(), "org".into()],
					}),
					max: None,
				},
				false,
			)],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("refs: (RecordId<'user'> | RecordId<'org'>)[];"), "got:\n{ts}");
	}

	#[test]
	fn literal_union_renders() {
		let d = doc(vec![table(
			"task",
			vec![field(
				"status",
				FieldType::Union {
					variants: vec![
						FieldType::Literal {
							value: serde_json::json!("open"),
						},
						FieldType::Literal {
							value: serde_json::json!("done"),
						},
					],
				},
				false,
			)],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains(r#"status: "open" | "done";"#), "got:\n{ts}");
	}

	#[test]
	fn dotted_paths_become_nested_object() {
		let d = doc(vec![table(
			"user",
			vec![
				field("address.city", prim(PrimitiveType::String), false),
				field("address.zip", prim(PrimitiveType::String), true),
			],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("address: {"), "got:\n{ts}");
		assert!(ts.contains("city: string;"), "got:\n{ts}");
		assert!(ts.contains("zip?: string;"), "got:\n{ts}");
	}

	#[test]
	fn array_element_object_from_star_paths() {
		let d = doc(vec![table(
			"user",
			vec![
				field(
					"addresses",
					FieldType::Array {
						inner: Box::new(prim(PrimitiveType::Object)),
						max: None,
					},
					false,
				),
				field("addresses[*].street", prim(PrimitiveType::String), false),
			],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("addresses: ({"), "got:\n{ts}");
		assert!(ts.contains("street: string;"), "got:\n{ts}");
		assert!(ts.contains("})[];"), "got:\n{ts}");
	}

	#[test]
	fn sdk_wrapper_types_import() {
		let d = doc(vec![table(
			"event",
			vec![
				field("at", prim(PrimitiveType::Datetime), false),
				field("dur", prim(PrimitiveType::Duration), false),
				field("amount", prim(PrimitiveType::Decimal), false),
			],
		)]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("at: Date;"), "got:\n{ts}");
		assert!(ts.contains("dur: Duration;"), "got:\n{ts}");
		assert!(ts.contains("amount: Decimal;"), "got:\n{ts}");
		assert!(
			ts.contains("import type { Decimal, Duration, RecordId } from 'surrealdb';"),
			"got:\n{ts}"
		);
	}

	#[test]
	fn internal_tables_are_skipped() {
		let d = doc(vec![
			table("__entity", vec![field("key", prim(PrimitiveType::String), false)]),
			table("user", vec![field("name", prim(PrimitiveType::String), false)]),
		]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("export interface User {"), "got:\n{ts}");
		assert!(!ts.contains("__entity"), "internal table leaked, got:\n{ts}");
		assert!(!ts.contains("interface Entity"), "internal table leaked, got:\n{ts}");
	}

	#[test]
	fn introspected_id_field_is_skipped() {
		let d = doc(vec![table("user", vec![field("id", prim(PrimitiveType::String), false)])]);
		let ts = to_typescript(&d).unwrap();
		assert!(ts.contains("id: RecordId<'user'>;"), "got:\n{ts}");
		assert!(!ts.contains("id: string;"), "synthesized id must win, got:\n{ts}");
	}
}